@sentry/server-utils 11.17.0 → 11.19.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/config.js +2 -2
- package/build/cjs/chunks/config.js.map +1 -1
- package/build/cjs/chunks/exports.js +115 -10
- package/build/cjs/chunks/exports.js.map +1 -1
- package/build/cjs/index.js +148 -31
- package/build/cjs/index.js.map +1 -1
- package/build/cjs/index.no-diagnostic-channels.js +1 -0
- package/build/cjs/index.request-handler.js +48 -3
- package/build/cjs/index.request-handler.js.map +1 -1
- package/build/esm/ai/langchain/utils.js +1 -5
- package/build/esm/ai/langchain/utils.js.map +1 -1
- package/build/esm/ai/mistral/streaming.js.map +1 -1
- package/build/esm/exports.js +2 -1
- package/build/esm/index.js +3 -1
- package/build/esm/index.js.map +1 -1
- package/build/esm/index.no-diagnostic-channels.js +2 -1
- package/build/esm/index.request-handler.js +3 -1
- package/build/esm/integrations/amqplib.js.map +1 -1
- package/build/esm/integrations/anthropic.js.map +1 -1
- package/build/esm/integrations/bullmq/tracer.js.map +1 -1
- package/build/esm/integrations/graphql/utils.js.map +1 -1
- package/build/esm/integrations/hapi/hapi-utils.js +6 -9
- package/build/esm/integrations/hapi/hapi-utils.js.map +1 -1
- package/build/esm/integrations/hono/isMiddleware.js.map +1 -1
- package/build/esm/integrations/hono/middlewareHandlers.js +3 -1
- package/build/esm/integrations/hono/middlewareHandlers.js.map +1 -1
- package/build/esm/integrations/hono/patchRoute.js +2 -1
- package/build/esm/integrations/hono/patchRoute.js.map +1 -1
- package/build/esm/integrations/hono/unwrapThrownValue.js +20 -0
- package/build/esm/integrations/hono/unwrapThrownValue.js.map +1 -0
- package/build/esm/integrations/mongodb/mongodb-span.js +7 -9
- package/build/esm/integrations/mongodb/mongodb-span.js.map +1 -1
- package/build/esm/integrations/pino.js +2 -2
- package/build/esm/integrations/pino.js.map +1 -1
- package/build/esm/integrations/prisma/tracing-helper.js.map +1 -1
- package/build/esm/integrations/serveTunnel.js +2 -2
- package/build/esm/integrations/serveTunnel.js.map +1 -1
- package/build/esm/integrations/vercel-ai/extract.js +88 -0
- package/build/esm/integrations/vercel-ai/extract.js.map +1 -0
- package/build/esm/integrations/vercel-ai/util.js +5 -1
- package/build/esm/integrations/vercel-ai/util.js.map +1 -1
- package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js +19 -9
- package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -1
- package/build/esm/integrations/winston.js +2 -2
- package/build/esm/integrations/winston.js.map +1 -1
- package/build/esm/orchestrion/config/hono.js +2 -2
- package/build/esm/orchestrion/config/hono.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/esm/utils/installedModules.js +87 -0
- package/build/esm/utils/installedModules.js.map +1 -0
- package/build/esm/utils/module.js +29 -0
- package/build/esm/utils/module.js.map +1 -0
- package/build/esm/utils/serverTimingTraceHeader.js +49 -0
- package/build/esm/utils/serverTimingTraceHeader.js.map +1 -0
- package/build/esm/utils/sql.js +4 -3
- package/build/esm/utils/sql.js.map +1 -1
- package/build/esm/utils/tunnelServer.js +3 -3
- package/build/esm/utils/tunnelServer.js.map +1 -1
- package/build/esm/utils/wrapServerRequestHandler.js +5 -4
- package/build/esm/utils/wrapServerRequestHandler.js.map +1 -1
- package/build/types/ai/flue/types.d.ts +4 -8
- package/build/types/ai/flue/types.d.ts.map +1 -1
- package/build/types/ai/langchain/utils.d.ts.map +1 -1
- package/build/types/ai/mistral/streaming.d.ts.map +1 -1
- package/build/types/exports.d.ts +1 -0
- package/build/types/exports.d.ts.map +1 -1
- package/build/types/index.d.ts +3 -2
- package/build/types/index.d.ts.map +1 -1
- package/build/types/index.request-handler.d.ts +1 -0
- package/build/types/index.request-handler.d.ts.map +1 -1
- package/build/types/integrations/amqplib.d.ts.map +1 -1
- package/build/types/integrations/anthropic.d.ts.map +1 -1
- package/build/types/integrations/bullmq/tracer.d.ts.map +1 -1
- package/build/types/integrations/hapi/hapi-utils.d.ts.map +1 -1
- package/build/types/integrations/hono/isMiddleware.d.ts.map +1 -1
- package/build/types/integrations/hono/middlewareHandlers.d.ts.map +1 -1
- package/build/types/integrations/hono/patchRoute.d.ts.map +1 -1
- package/build/types/integrations/hono/unwrapThrownValue.d.ts +10 -0
- package/build/types/integrations/hono/unwrapThrownValue.d.ts.map +1 -0
- package/build/types/integrations/mongodb/mongodb-span.d.ts.map +1 -1
- package/build/types/integrations/prisma/tracing-helper.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/extract.d.ts +27 -0
- package/build/types/integrations/vercel-ai/extract.d.ts.map +1 -0
- package/build/types/integrations/vercel-ai/util.d.ts +2 -0
- package/build/types/integrations/vercel-ai/util.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts +1 -1
- package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts.map +1 -1
- package/build/types/utils/installedModules.d.ts +17 -0
- package/build/types/utils/installedModules.d.ts.map +1 -0
- package/build/types/utils/module.d.ts +3 -0
- package/build/types/utils/module.d.ts.map +1 -0
- package/build/types/utils/serverTimingTraceHeader.d.ts +18 -0
- package/build/types/utils/serverTimingTraceHeader.d.ts.map +1 -0
- package/build/types/utils/sql.d.ts.map +1 -1
- package/build/types/utils/tunnelServer.d.ts.map +1 -1
- package/build/types/utils/wrapServerRequestHandler.d.ts.map +1 -1
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"exports.js","names":["getActiveSpan","getRootSpan","spanToJSON","SENTRY_OP","HTTP_REQUEST_METHOD","HTTP_METHOD","HTTP_ROUTE","SENTRY_SEGMENT_NAME_SOURCE","getAsyncContextStrategy","getMainCarrier","AsyncLocalStorage","getDefaultCurrentScope","getDefaultIsolationScope","isContinuingTrace","generateTraceId","_INTERNAL_safeMathRandom","setAsyncContextStrategy","registerExternalPropagationContext","trace","isSpanContextValid","defineIntegration","dsnFromString","SENTRY_API_VERSION","FUNCTION","getClient","DEBUG_BUILD","debug","isObjectLike","GEN_AI_USAGE_INPUT_TOKENS","GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS","GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS","GEN_AI_USAGE_OUTPUT_TOKENS","GEN_AI_USAGE_TOTAL_TOKENS","stringify","setOutputMessagesAttribute","GEN_AI_OUTPUT_MESSAGES","SPAN_STATUS_ERROR","GEN_AI_RESPONSE_STREAMING","GEN_AI_RESPONSE_ID","GEN_AI_RESPONSE_MODEL","GEN_AI_USAGE_REASONING_OUTPUT_TOKENS","GEN_AI_RESPONSE_FINISH_REASONS","GEN_AI_RESPONSE_TEXT","GEN_AI_RESPONSE_TOOL_CALLS","isThenable","DEBUG_BUILD","debug","spanToJSON","GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK","timestampInSeconds","getDecisionInputMessages","toStateMessages","isObjectLike","addResponseAttributes","GEN_AI_RESPONSE_ID","GEN_AI_RESPONSE_MODEL","GEN_AI_CONVERSATION_ID","isObjectLike","GEN_AI_RESPONSE_FINISH_REASONS","GEN_AI_RESPONSE_TEXT","GEN_AI_RESPONSE_TOOL_CALLS","GEN_AI_OUTPUT_MESSAGES","GEN_AI_USAGE_INPUT_TOKENS","GEN_AI_USAGE_OUTPUT_TOKENS","GEN_AI_USAGE_TOTAL_TOKENS","GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS","GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS","GEN_AI_USAGE_REASONING_OUTPUT_TOKENS","extractRequestParameters","GEN_AI_REQUEST_MODEL","GEN_AI_REQUEST_TEMPERATURE","GEN_AI_REQUEST_TOP_P","GEN_AI_REQUEST_FREQUENCY_PENALTY","GEN_AI_REQUEST_PRESENCE_PENALTY","SPAN_STATUS_ERROR","captureException","instrumentStream","DEBUG_BUILD","debug","extractRequestAttributes","GEN_AI_PROVIDER_NAME","GEN_AI_OPERATION_NAME","SENTRY_ORIGIN","GEN_AI_TOOL_DEFINITIONS","extractRequestParameters","GEN_AI_INPUT_MESSAGES","getDecisionInputMessages","GEN_AI_REQUEST_MODEL","addRequestAttributes","GEN_AI_EMBEDDINGS_INPUT","stringify","GEN_AI_SYSTEM_INSTRUCTIONS","instrumentMethod","getClient","hasSpanStreamingEnabled","startSpanManual","instrumentStream","startSpan","addResponseAttributes","createDeepProxy","GEN_AI_SYSTEM_INSTRUCTIONS","GEN_AI_INPUT_MESSAGES","stringify","SPAN_STATUS_ERROR","captureException","GEN_AI_RESPONSE_TEXT","GEN_AI_RESPONSE_TOOL_CALLS","GEN_AI_RESPONSE_ID","GEN_AI_RESPONSE_MODEL","addResponseAttributes","isObjectLike","SPAN_STATUS_ERROR","processEvent","captureException","getClient","withIsolationScope","getDefaultCurrentScope","withScope","SPAN_STATUS_ERROR","withScope","getIsolationScope","startInactiveSpan","GEN_AI_INVOKE_AGENT","SENTRY_ORIGIN","GEN_AI_OPERATION_NAME","GEN_AI_PROVIDER_NAME","GEN_AI_CONVERSATION_ID","withActiveSpan","getActiveSpan","getCurrentScope","getDefaultCurrentScope","getDefaultIsolationScope","startNewTrace","getOriginalFunction","fill","startSpan","GEN_AI_EXECUTE_TOOL","GEN_AI_TOOL_NAME","GEN_AI_TOOL_DESCRIPTION","GEN_AI_TOOL_CALL_ARGUMENTS","stringify","handleCallbackErrors","GEN_AI_TOOL_CALL_RESULT","captureException","extractRequestAttributes","GEN_AI_PROVIDER_NAME","GEN_AI_OPERATION_NAME","SENTRY_ORIGIN","GEN_AI_TOOL_DEFINITIONS","GEN_AI_REQUEST_MODEL","GEN_AI_REQUEST_TEMPERATURE","GEN_AI_REQUEST_TOP_P","GEN_AI_REQUEST_TOP_K","GEN_AI_REQUEST_FREQUENCY_PENALTY","GEN_AI_REQUEST_MAX_TOKENS","addPrivateRequestAttributes","startSpanManual","instrumentMethod","getClient","hasSpanStreamingEnabled","startSpan","addResponseAttributes","isObjectLike","GEN_AI_OUTPUT_MESSAGES","isObjectLike","stringify","GEN_AI_OUTPUT_MESSAGES","SPAN_STATUS_ERROR","captureException","processChunk","GEN_AI_REQUEST_TEMPERATURE","GEN_AI_REQUEST_TOP_P","GEN_AI_REQUEST_TOP_K","GEN_AI_REQUEST_MAX_TOKENS","GEN_AI_REQUEST_FREQUENCY_PENALTY","GEN_AI_REQUEST_PRESENCE_PENALTY","extractRequestAttributes","GEN_AI_PROVIDER_NAME","GEN_AI_OPERATION_NAME","SENTRY_ORIGIN","GEN_AI_REQUEST_MODEL","GEN_AI_TOOL_DEFINITIONS","GEN_AI_INPUT_MESSAGES","GEN_AI_EMBEDDINGS_INPUT","stringify","GEN_AI_SYSTEM_INSTRUCTIONS","addResponseAttributes","GEN_AI_RESPONSE_MODEL","GEN_AI_USAGE_REASONING_OUTPUT_TOKENS","GEN_AI_RESPONSE_TEXT","GEN_AI_RESPONSE_TOOL_CALLS","instrumentMethod","getClient","hasSpanStreamingEnabled","startSpanManual","startSpan","handleCallbackErrors","createDeepProxy","getSpanName","GEN_AI_REQUEST_MODEL","GEN_AI_REQUEST_TEMPERATURE","GEN_AI_REQUEST_TOP_P","GEN_AI_REQUEST_MAX_TOKENS","GEN_AI_REQUEST_FREQUENCY_PENALTY","GEN_AI_REQUEST_PRESENCE_PENALTY","GEN_AI_REQUEST_SEED","addResponseAttributes","GEN_AI_RESPONSE_ID","GEN_AI_RESPONSE_MODEL","GEN_AI_USAGE_INPUT_TOKENS","GEN_AI_USAGE_OUTPUT_TOKENS","GEN_AI_USAGE_TOTAL_TOKENS","GEN_AI_RESPONSE_FINISH_REASONS","GEN_AI_RESPONSE_TEXT","GEN_AI_RESPONSE_TOOL_CALLS","setOutputMessagesAttribute","setOutputMessagesAttribute","extractToolDefinitions","stringify","extractRequestAttributes","GEN_AI_PROVIDER_NAME","GEN_AI_OPERATION_NAME","SENTRY_ORIGIN","GEN_AI_AGENT_NAME","GEN_AI_TOOL_DEFINITIONS","addRequestAttributes","GEN_AI_EMBEDDINGS_INPUT","GEN_AI_SYSTEM_INSTRUCTIONS","GEN_AI_INPUT_MESSAGES","getSpanName","startSpanManual","startSpan","addResponseAttributes","isObjectLike","startInactiveSpan","GEN_AI_DECIDE","SENTRY_ORIGIN","GEN_AI_OPERATION_NAME","GEN_AI_PROVIDER_NAME","GEN_AI_REQUEST_MODEL","GEN_AI_INPUT_MESSAGES","addResponseAttributes","GEN_AI_RESPONSE_MODEL","GEN_AI_USAGE_INPUT_TOKENS","GEN_AI_USAGE_OUTPUT_TOKENS","GEN_AI_USAGE_TOTAL_TOKENS","GEN_AI_OUTPUT_MESSAGES","SPAN_STATUS_ERROR","withActiveSpan","getActiveSpan","spanToJSON","SENTRY_ORIGIN","_INTERNAL_shouldSkipAiProviderWrapping","GEN_AI_CHAT","GEN_AI_EMBEDDINGS","GEN_AI_DECIDE","GEN_AI_EXTRACT","GEN_AI_PROVIDER_NAME","GEN_AI_OPERATION_NAME","SENTRY_ORIGIN","GEN_AI_REQUEST_MODEL","GEN_AI_REQUEST_TEMPERATURE","GEN_AI_REQUEST_MAX_TOKENS","GEN_AI_REQUEST_TOP_P","GEN_AI_REQUEST_TOP_K","GEN_AI_REQUEST_FREQUENCY_PENALTY","GEN_AI_REQUEST_PRESENCE_PENALTY","GEN_AI_INPUT_MESSAGES","stringify","GEN_AI_EMBEDDINGS_INPUT","GEN_AI_SYSTEM_INSTRUCTIONS","isObjectLike","addDecideResponseAttributes","GEN_AI_RESPONSE_ID","GEN_AI_RESPONSE_MODEL","GEN_AI_RESPONSE_TEXT","GEN_AI_RESPONSE_TOOL_CALLS","setOutputMessagesAttribute","GEN_AI_RESPONSE_FINISH_REASONS","GEN_AI_OUTPUT_MESSAGES","setOutputMessagesAttribute","getClient","hasSpanStreamingEnabled","SENTRY_OP","startSpanManual","startSpan","stringify","GEN_AI_REQUEST_TEMPERATURE","GEN_AI_REQUEST_MAX_TOKENS","GEN_AI_REQUEST_TOP_P","GEN_AI_REQUEST_FREQUENCY_PENALTY","GEN_AI_REQUEST_PRESENCE_PENALTY","GEN_AI_PROVIDER_NAME","GEN_AI_OPERATION_NAME","GEN_AI_REQUEST_MODEL","SENTRY_ORIGIN","GEN_AI_INPUT_MESSAGES","GEN_AI_SYSTEM_INSTRUCTIONS","GEN_AI_RESPONSE_TOOL_CALLS","isObjectLike","GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS","GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS","GEN_AI_RESPONSE_FINISH_REASONS","GEN_AI_RESPONSE_TEXT","GEN_AI_RESPONSE_MODEL","GEN_AI_RESPONSE_ID","GEN_AI_AGENT_NAME","GEN_AI_CONVERSATION_ID","isObjectLike","SENTRY_ORIGIN","addResponseAttributes","SENTRY_ORIGIN","SENTRY_OP","GEN_AI_EMBEDDINGS","GEN_AI_OPERATION_NAME","GEN_AI_REQUEST_MODEL","GEN_AI_PROVIDER_NAME","getClient","GEN_AI_EMBEDDINGS_INPUT","stringify","hasSpanStreamingEnabled","startSpan","SPAN_STATUS_ERROR","LRUMap","DEBUG_BUILD","debug","spanIsIgnored","getRootSpan","getActiveSpan","withActiveSpan","spanToJSON","GEN_AI_CONVERSATION_ID","GEN_AI_REQUEST_MODEL","GEN_AI_OPERATION_NAME","getClient","startInactiveSpan","hasSpanStreamingEnabled","SENTRY_OP","GEN_AI_CHAT","GEN_AI_TOOL_DEFINITIONS","SPAN_STATUS_ERROR","SENTRY_ORIGIN","GEN_AI_PIPELINE_NAME","GEN_AI_INVOKE_AGENT","GEN_AI_TOOL_NAME","GEN_AI_TOOL_CALL_ARGUMENTS","GEN_AI_EXECUTE_TOOL","GEN_AI_TOOL_CALL_RESULT","stringify","SENTRY_ORIGIN","SENTRY_OP","GEN_AI_EXECUTE_TOOL","GEN_AI_OPERATION_NAME","GEN_AI_TOOL_NAME","GEN_AI_AGENT_NAME","GEN_AI_TOOL_DESCRIPTION","GEN_AI_TOOL_CALL_ARGUMENTS","startSpan","GEN_AI_TOOL_CALL_RESULT","SPAN_STATUS_ERROR","GEN_AI_USAGE_INPUT_TOKENS","GEN_AI_USAGE_OUTPUT_TOKENS","GEN_AI_USAGE_TOTAL_TOKENS","GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS","GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS","GEN_AI_RESPONSE_MODEL","GEN_AI_RESPONSE_FINISH_REASONS","resultObj","stringify","setOutputMessagesAttribute","GEN_AI_RESPONSE_TEXT","GEN_AI_RESPONSE_TOOL_CALLS","SENTRY_ORIGIN","SENTRY_OP","GEN_AI_INVOKE_AGENT","GEN_AI_OPERATION_NAME","GEN_AI_PIPELINE_NAME","GEN_AI_AGENT_NAME","GEN_AI_REQUEST_MODEL","GEN_AI_TOOL_DEFINITIONS","GEN_AI_SYSTEM_INSTRUCTIONS","GEN_AI_INPUT_MESSAGES","stringify","startSpanManual","GEN_AI_RESPONSE_STREAMING","SPAN_STATUS_ERROR","startSpan","SPAN_STATUS_ERROR","GEN_AI_INVOKE_AGENT","GEN_AI_CHAT","GEN_AI_EXECUTE_TOOL","GEN_AI_EMBEDDINGS","GEN_AI_DECIDE","stringify","GEN_AI_USAGE_INPUT_TOKENS","GEN_AI_USAGE_OUTPUT_TOKENS","GEN_AI_USAGE_TOTAL_TOKENS","GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS","GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS","GEN_AI_USAGE_REASONING_OUTPUT_TOKENS","GEN_AI_OPERATION_NAME","ERROR_TYPE","GEN_AI_AGENT_NAME","GEN_AI_PIPELINE_NAME","GEN_AI_TOOL_DEFINITIONS","GEN_AI_SYSTEM_INSTRUCTIONS","GEN_AI_INPUT_MESSAGES","GEN_AI_OUTPUT_MESSAGES","GEN_AI_RESPONSE_TEXT","GEN_AI_REQUEST_MODEL","GEN_AI_PROVIDER_NAME","GEN_AI_RESPONSE_MODEL","GEN_AI_RESPONSE_ID","GEN_AI_RESPONSE_STREAMING","GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK","GEN_AI_RESPONSE_FINISH_REASONS","GEN_AI_REQUEST_TEMPERATURE","GEN_AI_REQUEST_MAX_TOKENS","GEN_AI_REQUEST_TOP_P","GEN_AI_REQUEST_TOP_K","GEN_AI_REQUEST_PRESENCE_PENALTY","GEN_AI_REQUEST_FREQUENCY_PENALTY","GEN_AI_REQUEST_SEED","GEN_AI_REQUEST_STOP_SEQUENCES","GEN_AI_TOOL_NAME","GEN_AI_TOOL_DESCRIPTION","GEN_AI_TOOL_CALL_ARGUMENTS","GEN_AI_TOOL_CALL_RESULT","LRUMap","LRUMap","getClient","DEBUG_BUILD","debug","sentryFlush","getActiveSpan","startInactiveSpan","GEN_AI_CONVERSATION_ID","SENTRY_OP","SENTRY_ORIGIN","SPAN_STATUS_ERROR","timestampInSeconds","GEN_AI_RESPONSE_MODEL","GLOBAL_OBJ","GLOBAL_OBJ","consoleSandbox","debug","getCurrentScope","isObjectLike","stringify","withActiveSpan","captureException","startInactiveSpan","SENTRY_ORIGIN","GEN_AI_OPERATION_NAME","GEN_AI_TOOL_NAME","GEN_AI_CONVERSATION_ID","GEN_AI_TOOL_CALL_ARGUMENTS","stringify","GEN_AI_TOOL_CALL_RESULT","SPAN_STATUS_ERROR","isObjectLike","piAiModuleNames","consoleSandbox","getDefaultIsolationScope","startNewTrace","withActiveSpan","LRUMap","withScope","startSpan","SENTRY_ORIGIN","GEN_AI_OPERATION_NAME","GEN_AI_AGENT_NAME","GEN_AI_CONVERSATION_ID","sentryTraceFromTraceparent","getActiveSpan","continueTrace","getIsolationScope","DB_QUERY_TEXT","DB_QUERY_SUMMARY","DB_OPERATION_NAME","DB_NAMESPACE","DB_SYSTEM_NAME","getClient","hasSpanStreamingEnabled","DEBUG_BUILD","debug","isObjectLike","DB_QUERY_TEXT","SENTRY_OP","DB","SENTRY_ORIGIN","DB_SYSTEM_NAME","startSpanManual","addNonEnumerableProperty","DB_OPERATION_NAME","SPAN_STATUS_ERROR","getActiveSpan","DB_NAMESPACE","SERVER_ADDRESS","SERVER_PORT","DB_RESPONSE_STATUS_CODE","ERROR_TYPE","HTTP_SERVER","getOriginalFunction","DEBUG_BUILD","debug","getActiveSpan","startSpan","SENTRY_OP","SENTRY_ORIGIN","isObjectLike","getOriginalFunction","getActiveSpan","getRootSpan","startInactiveSpan","SENTRY_OP","MIDDLEWARE","SENTRY_ORIGIN","SPAN_STATUS_ERROR","DEBUG_BUILD","debug","DEBUG_BUILD","debug","getOriginalFunction","DEBUG_BUILD","debug","isPlainObject","addNonEnumerableProperty","getActiveSpan","winterCGRequestToRequestData","getDefaultIsolationScope","getIsolationScope","getClient","getRootSpan","spanToJSON","CLIENT_ADDRESS","CLIENT_PORT","NETWORK_PEER_PORT","NETWORK_TRANSPORT","NETWORK_TYPE","NETWORK_PEER_ADDRESS","getClientIPAddress","winterCGHeadersToDict","captureException","updateSpanName","INTERNAL_setSegmentNameSourceIfSegment","HTTP_ROUTE","getIsolationScope","getDefaultIsolationScope","addNonEnumerableProperty"],"sources":["../../../src/utils/setHttpServerSpanRouteAttribute.ts","../../../src/async-context.ts","../../../src/opentelemetry.ts","../../../src/ai/core/utils.ts","../../../src/ai/core/span-hooks.ts","../../../src/ai/openai/constants.ts","../../../src/ai/core/streaming-tool-calls.ts","../../../src/ai/core/time-to-first-chunk.ts","../../../src/ai/core/gen-ai-attributes.ts","../../../src/ai/openai/mapping.ts","../../../src/ai/openai/utils.ts","../../../src/ai/openai/streaming.ts","../../../src/ai/openai/index.ts","../../../src/ai/anthropic-ai/constants.ts","../../../src/ai/anthropic-ai/utils.ts","../../../src/ai/anthropic-ai/streaming.ts","../../../src/utils/withCleanScopes.ts","../../../src/ai/anthropic-ai/tool-runner.ts","../../../src/ai/anthropic-ai/index.ts","../../../src/ai/google-genai/constants.ts","../../../src/ai/google-genai/decisions.ts","../../../src/ai/google-genai/utils.ts","../../../src/ai/google-genai/streaming.ts","../../../src/ai/google-genai/index.ts","../../../src/ai/mistral/constants.ts","../../../src/ai/mistral/utils.ts","../../../src/ai/mistral/streaming.ts","../../../src/ai/mistral/index.ts","../../../src/ai/typesafe/constants.ts","../../../src/ai/typesafe/index.ts","../../../src/ai/pi-ai/constants.ts","../../../src/ai/pi-ai/providers.ts","../../../src/ai/workers-ai/constants.ts","../../../src/ai/workers-ai/utils.ts","../../../src/ai/workers-ai/streaming.ts","../../../src/ai/workers-ai/index.ts","../../../src/ai/langchain/constants.ts","../../../src/ai/langchain/utils.ts","../../../src/ai/langchain/typesafe-classifier.ts","../../../src/ai/langchain/embeddings.ts","../../../src/ai/langchain/index.ts","../../../src/ai/langgraph/constants.ts","../../../src/ai/langgraph/utils.ts","../../../src/ai/langgraph/agent-span.ts","../../../src/ai/langgraph/stream.ts","../../../src/ai/langgraph/index.ts","../../../src/ai/mastra/constants.ts","../../../src/ai/mastra/utils.ts","../../../src/ai/mastra/classifier-evaluation.ts","../../../src/ai/mastra/span-registry.ts","../../../src/ai/mastra/index.ts","../../../src/utils/runtime.ts","../../../src/orchestrion/detect.ts","../../../src/ai/pi-ai/recording.ts","../../../src/ai/flue/constants.ts","../../../src/ai/pi-ai/messages.ts","../../../src/ai/flue/utils.ts","../../../src/ai/flue/index.ts","../../../src/utils/sql.ts","../../../src/integrations/postgresjs-wrapper.ts","../../../src/integrations/hono/constants.ts","../../../src/integrations/hono/sentryOriginalTraps.ts","../../../src/integrations/hono/patchAppRequest.ts","../../../src/integrations/hono/defaultShouldHandleError.ts","../../../src/integrations/hono/wrapMiddlewareSpan.ts","../../../src/integrations/hono/patchAppUse.ts","../../../src/integrations/hono/isMiddleware.ts","../../../src/integrations/hono/patchRoute.ts","../../../src/integrations/hono/applyPatches.ts","../../../src/integrations/hono/connInfo.ts","../../../src/integrations/hono/hono-context.ts","../../../src/integrations/hono/matchResult.ts","../../../src/integrations/hono/resolveRouteName.ts","../../../src/integrations/hono/middlewareHandlers.ts","../../../src/integrations/hono/createHonoMiddleware.ts"],"sourcesContent":["import {\n SENTRY_SEGMENT_NAME_SOURCE,\n HTTP_METHOD,\n HTTP_REQUEST_METHOD,\n HTTP_ROUTE,\n SENTRY_OP,\n} from '@sentry/conventions/attributes';\nimport { getActiveSpan, getRootSpan, spanToJSON } from '@sentry/core';\n\n/**\n * Set the `http.route` attribute on the root HTTP server span for the current trace.\n *\n * No-op when there is no active span, no root span, or the root span is not an\n * `http.server` span — so framework instrumentations can call this unconditionally\n * without risking attribute pollution on non-HTTP root spans.\n */\nexport function setHttpServerSpanRouteAttribute(route: string): void {\n const activeSpan = getActiveSpan();\n if (!activeSpan) {\n return;\n }\n const rootSpan = getRootSpan(activeSpan);\n if (!rootSpan) {\n return;\n }\n\n const attributes = spanToJSON(rootSpan).attributes;\n if (attributes[SENTRY_OP] !== 'http.server') {\n return;\n }\n\n // eslint-disable-next-line typescript/no-deprecated\n const method = attributes[HTTP_REQUEST_METHOD] || attributes[HTTP_METHOD] || 'GET';\n rootSpan.setAttribute(HTTP_ROUTE, route);\n rootSpan.updateName(`${method} ${route}`);\n rootSpan.setAttribute(SENTRY_SEGMENT_NAME_SOURCE, 'route');\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { Scope } from '@sentry/core';\nimport {\n getAsyncContextStrategy,\n _INTERNAL_safeMathRandom,\n generateTraceId,\n getDefaultCurrentScope,\n getDefaultIsolationScope,\n getMainCarrier,\n isContinuingTrace,\n setAsyncContextStrategy,\n} from '@sentry/core';\n\ntype ScopeStore = { scope: Scope; isolationScope: Scope };\n\n/**\n * Sets the async context strategy to use AsyncLocalStorage.\n *\n * Returns the underlying `AsyncLocalStorage` whose store is the `{ scope, isolationScope }` object, so\n * callers (e.g. `@sentry/node-native`) can read scope out of it from a native thread.\n */\nexport function setAsyncLocalStorageAsyncContextStrategy(): AsyncLocalStorage<ScopeStore> {\n // Re-use the AsyncLocalStorage of an already-installed strategy, if any. Otherwise a repeated\n // setup (e.g. a second `Sentry.init()`) would swap in a new store while integrations that captured\n // the previous one (via `getTracingChannelBinding().asyncLocalStorage`) keep reading the old one,\n // breaking scope propagation across async boundaries.\n const existingAsyncStorage = getAsyncContextStrategy(getMainCarrier()).getTracingChannelBinding?.()\n ?.asyncLocalStorage as AsyncLocalStorage<ScopeStore> | undefined;\n\n const asyncStorage = existingAsyncStorage ?? new AsyncLocalStorage<ScopeStore>();\n\n function getScopes(): { scope: Scope; isolationScope: Scope } {\n const scopes = asyncStorage.getStore();\n\n if (scopes) {\n return scopes;\n }\n\n // fallback behavior:\n // if, for whatever reason, we can't find scopes on the context here, we have to fix this somehow\n return {\n scope: getDefaultCurrentScope(),\n isolationScope: getDefaultIsolationScope(),\n };\n }\n\n function withScope<T>(callback: (scope: Scope) => T): T {\n const scope = getScopes().scope.clone();\n const isolationScope = getScopes().isolationScope;\n return asyncStorage.run({ scope, isolationScope }, () => {\n return callback(scope);\n });\n }\n\n // The isolation scope is shared, not forked, matching `withScope` above and the OpenTelemetry\n // strategy. Forking it would silently discard `setUser`/`setTag`/`setContext` calls made inside\n // the callback, as those write to the isolation scope.\n function withSetScope<T>(scope: Scope, callback: (scope: Scope) => T): T {\n const isolationScope = getScopes().isolationScope;\n return asyncStorage.run({ scope, isolationScope }, () => {\n return callback(scope);\n });\n }\n\n // The current scope is forked alongside the isolation scope, matching the OpenTelemetry strategy\n // (`buildContextWithSentryScopes` clones it on every fork). Sharing it by reference would let\n // current-scope mutations inside the callback leak back out to the caller.\n function withIsolationScope<T>(callback: (isolationScope: Scope) => T): T {\n const scope = getScopes().scope.clone();\n const isolationScope = getScopes().isolationScope.clone();\n\n // When forking an isolation scope, unless we are continuing an incoming\n // trace, we give the freshly forked scope its own trace. This way, new\n // root spans in an isolation scope will get separate traces. The previous\n // trace's `sampled` and `propagationSpanId` are dropped on purpose.\n // Carrying them over would apply the old trace's sampling decision to the\n // new one and propagate a span id from a different trace.\n if (!isContinuingTrace(scope.getPropagationContext())) {\n scope.setPropagationContext({\n traceId: generateTraceId(),\n sampleRand: _INTERNAL_safeMathRandom(),\n });\n }\n\n return asyncStorage.run({ scope, isolationScope }, () => {\n return callback(isolationScope);\n });\n }\n\n function withSetIsolationScope<T>(isolationScope: Scope, callback: (isolationScope: Scope) => T): T {\n const scope = getScopes().scope.clone();\n return asyncStorage.run({ scope, isolationScope }, () => {\n return callback(isolationScope);\n });\n }\n\n setAsyncContextStrategy({\n withScope,\n withSetScope,\n withIsolationScope,\n withSetIsolationScope,\n getCurrentScope: () => getScopes().scope,\n getIsolationScope: () => getScopes().isolationScope,\n getTracingChannelBinding: () => {\n return {\n asyncLocalStorage: asyncStorage,\n };\n },\n });\n\n return asyncStorage;\n}\n","import { isSpanContextValid, trace } from '@opentelemetry/api';\nimport type { IntegrationFn } from '@sentry/core';\nimport { defineIntegration, dsnFromString, SENTRY_API_VERSION, registerExternalPropagationContext } from '@sentry/core';\n\nconst INTEGRATION_NAME = 'OpenTelemetry' as const;\n\nconst _openTelemetryIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n\n setup(): void {\n registerExternalPropagationContext(() => {\n const activeSpan = trace.getActiveSpan();\n if (!activeSpan) {\n return undefined;\n }\n\n // OpenTelemetry hands out a span wrapping `INVALID_SPAN_CONTEXT` when tracing is suppressed,\n // or when a span is started before a tracer provider is registered. Its ids are all zeroes,\n // so fall back to the Sentry scope rather than stamping that onto everything we send.\n const spanContext = activeSpan.spanContext();\n if (!isSpanContextValid(spanContext)) {\n return undefined;\n }\n\n const { traceId, spanId } = spanContext;\n return { traceId, spanId };\n });\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Connects Sentry to an existing OpenTelemetry setup.\n *\n * Everything Sentry sends that carries trace information (errors, logs, metrics and check-ins) is\n * attached to the OpenTelemetry span that is active when it happens, so it shows up on the same\n * trace as the spans your OpenTelemetry SDK exports. Outgoing request propagation is left to your\n * OpenTelemetry propagator.\n *\n * An active Sentry span still takes precedence, so this only changes what happens when Sentry has no\n * span of its own, which is the usual setup when OpenTelemetry owns tracing.\n *\n * This does not export any spans. Configure your own span exporter and point it at Sentry using\n * {@link getOtlpTracesEndpoint}.\n */\nexport const openTelemetryIntegration = defineIntegration(_openTelemetryIntegration);\n\n/**\n * Builds the URL and auth headers for Sentry's OTLP traces endpoint, to configure an\n * `OTLPTraceExporter` with.\n *\n * Returns `undefined` if the DSN cannot be parsed.\n *\n * @example\n *\n * ```javascript\n * import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\n * import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';\n * import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';\n *\n * const provider = new NodeTracerProvider({\n * spanProcessors: [\n * new BatchSpanProcessor(new OTLPTraceExporter(Sentry.getOtlpTracesEndpoint('__DSN__'))),\n * ],\n * });\n *\n * provider.register();\n *\n * Sentry.init({\n * dsn: '__DSN__',\n * integrations: [Sentry.openTelemetryIntegration()],\n * });\n * ```\n */\nexport function getOtlpTracesEndpoint(dsn: string): { url: string; headers: Record<string, string> } | undefined {\n const parsedDsn = dsnFromString(dsn);\n if (!parsedDsn) {\n return undefined;\n }\n\n const { protocol, host, port, path, projectId, publicKey } = parsedDsn;\n const basePath = path ? `/${path}` : '';\n const portSuffix = port ? `:${port}` : '';\n\n return {\n url: `${protocol}://${host}${portSuffix}${basePath}/api/${projectId}/integration/otlp/v1/traces/`,\n headers: {\n 'X-Sentry-Auth': `Sentry sentry_version=${SENTRY_API_VERSION}, sentry_key=${publicKey}`,\n },\n };\n}\n","/* eslint-disable typescript-eslint/no-deprecated */\n/**\n * Shared utils for AI integrations (OpenAI, Anthropic, Verce.AI, etc.)\n */\nimport { debug, getClient, isObjectLike, isThenable, SPAN_STATUS_ERROR, stringify } from '@sentry/core';\nimport type { Span, SpanStatus } from '@sentry/core';\nimport {\n GEN_AI_OUTPUT_MESSAGES,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_STREAMING,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n} from '@sentry/conventions/attributes';\nimport { FUNCTION } from '@sentry/conventions/op';\nimport { DEBUG_BUILD } from '../../debug-build';\n\nexport interface GenAiOptions {\n /**\n * Record input messages/prompts on gen_ai spans. Defaults to the global\n * `dataCollection.genAI.inputs` setting; an explicit value here takes precedence.\n */\n recordInputs?: boolean;\n /**\n * Record output text/responses on gen_ai spans. Defaults to the global\n * `dataCollection.genAI.outputs` setting; an explicit value here takes precedence.\n */\n recordOutputs?: boolean;\n}\n\n/**\n * Whether to record the content of a gen_ai call: a boolean for every call, or a function that decides for\n * each call. The function runs once when the call starts, in the caller's async context, so it can read\n * request-scoped state. Returning `undefined` falls back to `dataCollection.genAI`. If it throws, the\n * content is not recorded.\n */\nexport type GenAiRecordingOption<TCall> = boolean | ((call: TCall) => boolean | undefined);\n\n/** {@link GenAiOptions} of an integration that can decide per call. `TCall` is what the function gets. */\nexport interface GenAiCallOptions<TCall> {\n /**\n * Record input messages/prompts on gen_ai spans. Defaults to the global\n * `dataCollection.genAI.inputs` setting; an explicit value here takes precedence.\n */\n recordInputs?: GenAiRecordingOption<TCall>;\n /**\n * Record output text/responses on gen_ai spans. Defaults to the global\n * `dataCollection.genAI.outputs` setting; an explicit value here takes precedence.\n */\n recordOutputs?: GenAiRecordingOption<TCall>;\n}\n\n/**\n * A method registry entry describes a single instrumented method:\n * which gen_ai operation it maps to and whether it is intrinsically streaming.\n */\nexport interface InstrumentedMethodEntry {\n /** Operation name (e.g. 'chat', 'embeddings', 'generate_content'). Omit for factory methods that only need result proxying. */\n operation?: string;\n /** True if the method itself is always streaming (not param-based) */\n streaming?: boolean;\n /** When set, the method's return value is re-proxied with this as the base path */\n proxyResultPath?: string;\n}\n\n/**\n * Maps method paths to their registry entries.\n * Used by proxy-based AI client instrumentations to determine which methods\n * to instrument, what operation name to use, and whether they stream.\n */\nexport type InstrumentedMethodRegistry = Record<string, InstrumentedMethodEntry>;\n\n// Operation names that are not inference calls: `unknown` is the fallback for methods with no\n// registered operation. It should not surface as a `gen_ai.*` op (an unknown string must not\n// masquerade as a convention), so it maps to the generic `function` op. The operation name itself\n// is preserved on `gen_ai.operation.name`.\nconst NON_INFERENCE_OPERATIONS = new Set(['unknown']);\n\n/**\n * Derive the span op from a gen_ai operation name. Inference operations become `gen_ai.<operation>`;\n * non-inference operations (`unknown`) become the generic `function` op.\n */\nexport function getGenAiSpanOp(operationName: string): string {\n return NON_INFERENCE_OPERATIONS.has(operationName) ? FUNCTION : `gen_ai.${operationName}`;\n}\n\n/**\n * Resolves AI recording options by falling back to the client's `dataCollection.genAI` settings.\n * Precedence: explicit option > dataCollection.genAI > true (genAI data collected by default)\n */\nexport function resolveAIRecordingOptions<T extends GenAiOptions>(options?: T): T & Required<GenAiOptions> {\n const genAI = getClient()?.getDataCollectionOptions().genAI;\n return {\n ...options,\n recordInputs: options?.recordInputs ?? genAI?.inputs ?? true,\n recordOutputs: options?.recordOutputs ?? genAI?.outputs ?? true,\n } as T & Required<GenAiOptions>;\n}\n\n/**\n * Resolves the recording options of one call, like {@link resolveAIRecordingOptions}, and calls the\n * options that are functions with `call`. Call it once when the call starts, so the functions run in the\n * caller's async context.\n */\nexport function resolveGenAiCallRecording<TCall>(\n options: GenAiCallOptions<TCall> | undefined,\n call: TCall,\n): Required<GenAiOptions> {\n const genAI = getClient()?.getDataCollectionOptions().genAI;\n return {\n recordInputs: resolveRecordingOption(options?.recordInputs, call) ?? genAI?.inputs ?? true,\n recordOutputs: resolveRecordingOption(options?.recordOutputs, call) ?? genAI?.outputs ?? true,\n };\n}\n\n/** Calls `option` with `call` when it is a function; `undefined` means the option does not decide. */\nexport function resolveRecordingOption<TCall>(\n option: GenAiRecordingOption<TCall> | undefined,\n call: TCall,\n): boolean | undefined {\n if (typeof option !== 'function') {\n return option;\n }\n try {\n const result = option(call);\n return result === undefined ? undefined : result === true;\n } catch (error) {\n DEBUG_BUILD && debug.warn('[gen_ai] `recordInputs`/`recordOutputs` threw, not recording content', error);\n return false;\n }\n}\n\n/**\n * Build method path from current traversal\n */\nexport function buildMethodPath(currentPath: string, prop: string): string {\n return currentPath ? `${currentPath}.${prop}` : prop;\n}\n\n/**\n * A minimal structural check for a web `ReadableStream`.\n *\n * The chunk type is the caller's assumption about the provider's stream (e.g. `Uint8Array` for SSE\n * byte streams); the check itself only looks for the `ReadableStream` methods we rely on.\n */\nexport function isReadableStream<T = unknown>(value: unknown): value is ReadableStream<T> {\n return (\n isObjectLike(value) &&\n typeof (value as { pipeThrough?: unknown }).pipeThrough === 'function' &&\n typeof (value as { getReader?: unknown }).getReader === 'function'\n );\n}\n\n/**\n * Build token usage attributes. Input tokens include cache reads and writes, which are subsets.\n */\nexport function getTokenUsageAttributes(\n promptTokens?: number,\n completionTokens?: number,\n cacheCreationInputTokens?: number,\n cacheReadInputTokens?: number,\n totalTokens?: number,\n): Record<string, number> {\n const attributes: Record<string, number> = {};\n\n if (typeof promptTokens === 'number') {\n attributes[GEN_AI_USAGE_INPUT_TOKENS] = promptTokens;\n }\n if (typeof cacheCreationInputTokens === 'number') {\n attributes[GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS] = cacheCreationInputTokens;\n }\n if (typeof cacheReadInputTokens === 'number') {\n attributes[GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS] = cacheReadInputTokens;\n }\n if (typeof completionTokens === 'number') {\n attributes[GEN_AI_USAGE_OUTPUT_TOKENS] = completionTokens;\n }\n if (typeof totalTokens === 'number') {\n attributes[GEN_AI_USAGE_TOTAL_TOKENS] = totalTokens;\n } else if (typeof promptTokens === 'number' || typeof completionTokens === 'number') {\n attributes[GEN_AI_USAGE_TOTAL_TOKENS] =\n (typeof promptTokens === 'number' ? promptTokens : 0) +\n (typeof completionTokens === 'number' ? completionTokens : 0);\n }\n return attributes;\n}\n\n/** Serialize the `state` and `questions` of an evaluation request (TypeSafe, Workers AI, Mastra classifiers). */\nexport function getEvaluationInputMessages(request: Record<string, unknown>): string | undefined {\n return stringify([{ type: 'evaluation', state: request.state, questions: request.questions }]);\n}\n\n/** Serialize the `answers` of an evaluation result (TypeSafe, Workers AI, Mastra classifiers). */\nexport function getEvaluationOutputMessages(answers: unknown): string | undefined {\n return stringify([{ type: 'evaluation', answers }]);\n}\n\n/** One assistant turn for {@link setOutputMessagesAttribute}. */\nexport interface GenAiOutputMessage {\n /** The message's text content, already flattened out of any content-part array. */\n responseText?: string;\n /** Tool calls in either the OpenAI-compatible (`function.name`) or flat (`name`) shape. */\n toolCalls?: unknown[];\n /** Recorded as `finish_reason` on the message, per the `gen_ai.output.messages` schema. */\n finishReason?: string;\n}\n\n/**\n * Build the `gen_ai.output.messages` value (assistant messages with text and/or tool-call parts).\n *\n * We set this in addition to the deprecated `gen_ai.response.text` / `gen_ai.response.tool_calls`\n * attributes because Sentry's product reads the model output from `gen_ai.output.messages` first.\n * Relay migrates `gen_ai.response.text` into `gen_ai.output.messages`, but the tool-calls half of\n * that migration is lossy — so tool-call turns would otherwise render an empty Output.\n *\n * Pass an array for providers that can return more than one choice per response; a single object is\n * the common case of one assistant turn.\n */\nexport function setOutputMessagesAttribute(span: Span, messages: GenAiOutputMessage | GenAiOutputMessage[]): void {\n const serialized = (Array.isArray(messages) ? messages : [messages])\n .map(buildOutputMessage)\n .filter((message): message is Record<string, unknown> => !!message);\n\n if (serialized.length > 0) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, JSON.stringify(serialized));\n }\n}\n\nfunction buildOutputMessage({\n responseText,\n toolCalls,\n finishReason,\n}: GenAiOutputMessage): Record<string, unknown> | undefined {\n const parts: Array<Record<string, unknown>> = [];\n\n if (typeof responseText === 'string' && responseText.length > 0) {\n parts.push({ type: 'text', content: responseText });\n }\n\n if (Array.isArray(toolCalls)) {\n for (const toolCall of toolCalls) {\n if (!toolCall || typeof toolCall !== 'object') {\n continue;\n }\n const call = toolCall as {\n id?: unknown;\n function?: { name?: unknown; arguments?: unknown };\n name?: unknown;\n arguments?: unknown;\n };\n // Normalize both the OpenAI-compatible shape (name/arguments nested under `function`)\n // and the flat shape some providers use.\n const name = call.function?.name ?? call.name;\n const args = call.function?.arguments ?? call.arguments;\n parts.push({\n type: 'tool_call',\n id: call.id,\n name,\n arguments: stringify(args ?? {}, String),\n });\n }\n }\n\n if (parts.length === 0) {\n return undefined;\n }\n\n return finishReason ? { role: 'assistant', parts, finish_reason: finishReason } : { role: 'assistant', parts };\n}\n\nexport interface StreamResponseState {\n responseId?: string;\n responseModel?: string;\n finishReasons: string[];\n responseTexts: string[];\n toolCalls: unknown[];\n promptTokens?: number;\n completionTokens?: number;\n totalTokens?: number;\n cacheCreationInputTokens?: number;\n cacheReadInputTokens?: number;\n reasoningOutputTokens?: number;\n}\n\n/**\n * Reads `signal` from the request options OpenAI and Anthropic take as their second argument.\n */\nexport function getRequestSignal(requestOptions: unknown): AbortSignal | undefined {\n return isObjectLike(requestOptions) ? (requestOptions.signal as AbortSignal | undefined) : undefined;\n}\n\n/**\n * Checks the signal rather than the error name, because SDK timeouts also throw an `AbortError`. A caller's\n * own `AbortSignal.timeout()` is a timeout too, not a cancellation.\n */\nexport function isCallerAbort(abortSignal: AbortSignal | undefined): boolean {\n return !!abortSignal?.aborted && (abortSignal.reason as { name?: unknown } | undefined)?.name !== 'TimeoutError';\n}\n\n/**\n * A caller's abort is `cancelled`, anything else `internal_error`.\n */\nexport function getErrorStatus(abortSignal: AbortSignal | undefined): SpanStatus {\n return { code: SPAN_STATUS_ERROR, message: isCallerAbort(abortSignal) ? 'cancelled' : 'internal_error' };\n}\n\n/**\n * Overrides the status of a span whose call the caller aborted.\n */\nexport function markCancelledIfAborted(span: Span, abortSignal: AbortSignal | undefined): void {\n if (isCallerAbort(abortSignal)) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n }\n}\n\n/**\n * Ends a streaming span by setting all accumulated response attributes and ending the span.\n * Shared across OpenAI, Anthropic, and Google GenAI streaming implementations.\n * `beforeSpanEnd` runs after the attributes are set, right before the span ends.\n */\nexport function endStreamSpan(\n span: Span,\n state: StreamResponseState,\n recordOutputs: boolean,\n beforeSpanEnd?: () => void,\n): void {\n if (!span.isRecording()) {\n return;\n }\n\n const attrs: Record<string, string | number | boolean> = {\n [GEN_AI_RESPONSE_STREAMING]: true,\n };\n\n if (state.responseId) attrs[GEN_AI_RESPONSE_ID] = state.responseId;\n if (state.responseModel) attrs[GEN_AI_RESPONSE_MODEL] = state.responseModel;\n\n Object.assign(\n attrs,\n getTokenUsageAttributes(\n state.promptTokens,\n state.completionTokens,\n state.cacheCreationInputTokens,\n state.cacheReadInputTokens,\n state.totalTokens,\n ),\n );\n if (typeof state.reasoningOutputTokens === 'number') {\n attrs[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS] = state.reasoningOutputTokens;\n }\n\n if (state.finishReasons.length) {\n attrs[GEN_AI_RESPONSE_FINISH_REASONS] = JSON.stringify(state.finishReasons);\n }\n if (recordOutputs && state.responseTexts.length) {\n attrs[GEN_AI_RESPONSE_TEXT] = state.responseTexts.join('');\n }\n if (recordOutputs && state.toolCalls.length) {\n attrs[GEN_AI_RESPONSE_TOOL_CALLS] = JSON.stringify(state.toolCalls);\n }\n\n span.setAttributes(attrs);\n beforeSpanEnd?.();\n span.end();\n}\n\n/**\n * Extract system instructions from messages array.\n * Finds the first system message and formats it according to OpenTelemetry semantic conventions.\n *\n * @param messages - Array of messages to extract system instructions from\n * @returns systemInstructions (JSON string) and filteredMessages (without system message)\n */\nexport function extractSystemInstructions(messages: unknown[] | unknown): {\n systemInstructions: string | undefined;\n filteredMessages: unknown[] | unknown;\n} {\n if (!Array.isArray(messages)) {\n return { systemInstructions: undefined, filteredMessages: messages };\n }\n\n const systemMessageIndex = messages.findIndex(\n msg => msg && typeof msg === 'object' && 'role' in msg && (msg as { role: string }).role === 'system',\n );\n\n if (systemMessageIndex === -1) {\n return { systemInstructions: undefined, filteredMessages: messages };\n }\n\n const systemMessage = messages[systemMessageIndex] as { role: string; content?: string | unknown };\n const systemContent =\n typeof systemMessage.content === 'string'\n ? systemMessage.content\n : systemMessage.content !== undefined\n ? JSON.stringify(systemMessage.content)\n : undefined;\n\n if (!systemContent) {\n return { systemInstructions: undefined, filteredMessages: messages };\n }\n\n const systemInstructions = JSON.stringify([{ type: 'text', content: systemContent }]);\n const filteredMessages = [...messages.slice(0, systemMessageIndex), ...messages.slice(systemMessageIndex + 1)];\n\n return { systemInstructions, filteredMessages };\n}\n\n/**\n * Creates a wrapped version of .withResponse() that replaces the data field\n * with the instrumented result while preserving metadata (response, request_id).\n */\nasync function createWithResponseWrapper<T>(\n originalWithResponse: Promise<unknown>,\n instrumentedPromise: Promise<T>,\n): Promise<unknown> {\n // Awaited together rather than in sequence so both promises get a handler attached synchronously.\n // Awaiting them one after the other leaves the second unobserved when the first rejects, which\n // surfaces as an unhandled rejection.\n const [instrumentedResult, originalWrapper] = await Promise.all([instrumentedPromise, originalWithResponse]);\n\n // Combine instrumented result with original metadata\n if (originalWrapper && typeof originalWrapper === 'object' && 'data' in originalWrapper) {\n return {\n ...originalWrapper,\n data: instrumentedResult,\n };\n }\n return instrumentedResult;\n}\n\n/**\n * Wraps a promise-like object to preserve additional methods (like .withResponse())\n * that AI SDK clients (OpenAI, Anthropic) attach to their APIPromise return values.\n *\n * Standard Promise methods (.then, .catch, .finally) are routed to the instrumented\n * promise to preserve Sentry's span instrumentation, while custom SDK methods are\n * forwarded to the original promise to maintain the SDK's API surface.\n */\nexport function wrapPromiseWithMethods<R>(\n originalPromiseLike: Promise<R>,\n instrumentedPromise: Promise<R>,\n): Promise<R> {\n // If the original result is not thenable, return the instrumented promise\n if (!isThenable(originalPromiseLike)) {\n return instrumentedPromise;\n }\n\n // Create a proxy that forwards Promise methods to instrumentedPromise\n // and preserves additional methods from the original result\n return new Proxy(originalPromiseLike, {\n get(target: object, prop: string | symbol): unknown {\n // For standard Promise methods (.then, .catch, .finally, Symbol.toStringTag),\n // use instrumentedPromise to preserve Sentry instrumentation.\n // For custom methods (like .withResponse()), use the original target.\n const useInstrumentedPromise = prop in Promise.prototype || prop === Symbol.toStringTag;\n const source = useInstrumentedPromise ? instrumentedPromise : target;\n\n const value = Reflect.get(source, prop) as unknown;\n\n // Special handling for .withResponse() to preserve instrumentation\n // .withResponse() returns { data: T, response: Response, request_id: string }\n if (prop === 'withResponse' && typeof value === 'function') {\n return function wrappedWithResponse(this: unknown): unknown {\n const originalWithResponse = (value as (...args: unknown[]) => unknown).call(target);\n return createWithResponseWrapper(originalWithResponse, instrumentedPromise);\n };\n }\n\n return typeof value === 'function' ? value.bind(source) : value;\n },\n }) as Promise<R>;\n}\n","import { debug } from '@sentry/core';\nimport type { Span } from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\n\n/** How a gen_ai call ended, as passed to {@link GenAiSpanHooks.onSpanEnd}. */\nexport interface GenAiSpanResult<TResponse> {\n /** The response as the library returned it. `undefined` for streams and failed calls. */\n response?: TResponse;\n /** Set when the call failed. */\n error?: unknown;\n}\n\n/**\n * Hooks that let an integration's users add their own attributes to its gen_ai spans. `TCall` is the same\n * call info that `recordInputs`/`recordOutputs` get, and both hooks get the same object.\n *\n * They only run for spans that are recorded. A hook that throws is logged and does not affect the call.\n */\nexport interface GenAiSpanHooks<TCall, TResponse = unknown> {\n /**\n * Runs after the span started and the SDK set its request attributes, in the caller's async context, so\n * it can read request-scoped state.\n */\n onSpanStart?: (span: Span, call: TCall) => void;\n /**\n * Runs after the SDK set its response attributes, right before the span ends. That can be in another\n * async context than the call, for example when a stream is consumed later.\n */\n onSpanEnd?: (span: Span, call: TCall, result: GenAiSpanResult<TResponse>) => void;\n}\n\n/** Runs {@link GenAiSpanHooks.onSpanStart}. */\nexport function runGenAiSpanStart<TCall>(\n hooks: Pick<GenAiSpanHooks<TCall>, 'onSpanStart'>,\n span: Span,\n call: TCall,\n): void {\n const onSpanStart = hooks.onSpanStart;\n if (onSpanStart && span.isRecording()) {\n runGenAiSpanHook('onSpanStart', () => onSpanStart(span, call));\n }\n}\n\n/** Runs {@link GenAiSpanHooks.onSpanEnd}. Call it right before the span ends. */\nexport function runGenAiSpanEnd<TCall, TResponse>(\n hooks: GenAiSpanHooks<TCall, TResponse>,\n span: Span,\n call: TCall,\n result: GenAiSpanResult<TResponse>,\n): void {\n const onSpanEnd = hooks.onSpanEnd;\n if (onSpanEnd && span.isRecording()) {\n runGenAiSpanHook('onSpanEnd', () => onSpanEnd(span, call, result));\n }\n}\n\nfunction runGenAiSpanHook(name: string, hook: () => void): void {\n try {\n hook();\n } catch (error) {\n DEBUG_BUILD && debug.warn(`[gen_ai] \\`${name}\\` threw`, error);\n }\n}\n","import type { InstrumentedMethodRegistry } from '../core/utils';\n\nexport const OPENAI_INTEGRATION_NAME = 'OpenAI' as const;\n\n// https://platform.openai.com/docs/quickstart?api-mode=responses\n// https://platform.openai.com/docs/quickstart?api-mode=chat\n// https://platform.openai.com/docs/api-reference/conversations\nexport const OPENAI_METHOD_REGISTRY = {\n 'responses.create': { operation: 'chat' },\n 'chat.completions.create': { operation: 'chat' },\n 'embeddings.create': { operation: 'embeddings' },\n // Conversations API - for conversation state management\n // https://platform.openai.com/docs/guides/conversation-state\n 'conversations.create': { operation: 'chat' },\n // https://developers.openai.com/api/docs/guides/decisions\n 'decisions.create': { operation: 'decide' },\n} as const satisfies InstrumentedMethodRegistry;\nexport const RESPONSES_TOOL_CALL_EVENT_TYPES = [\n 'response.output_item.added',\n 'response.function_call_arguments.delta',\n 'response.function_call_arguments.done',\n 'response.output_item.done',\n] as const;\nexport const RESPONSE_EVENT_TYPES = [\n 'response.created',\n 'response.in_progress',\n 'response.failed',\n 'response.completed',\n 'response.incomplete',\n 'response.queued',\n 'response.output_text.delta',\n ...RESPONSES_TOOL_CALL_EVENT_TYPES,\n] as const;\n","interface ToolCallKeyState {\n calls: Map<string, { id?: string }>;\n keyByIndex: Map<number, string>;\n lastKey?: string;\n}\n\n/**\n * Find the key of the call a tool call delta belongs to. A numeric `index` groups deltas, except that a different\n * non-empty `id` arriving on an index that is already taken opens a new call (a known `id` continues its own call).\n * Some providers omit the index and send each parallel call whole: a known `id` continues that call, a new `id` (or\n * a name without an id) starts a new call, and anything else continues the latest one.\n */\nexport function getToolCallKey(\n toolCall: { index?: number | null; id?: string },\n name: string | undefined,\n accumulator: ToolCallKeyState,\n): string {\n const { calls } = accumulator;\n const findById = (id: string): string | undefined => {\n for (const [key, call] of calls) {\n if (call.id === id) return key;\n }\n return undefined;\n };\n\n if (typeof toolCall.index === 'number') {\n const key = accumulator.keyByIndex.get(toolCall.index) ?? `index-${toolCall.index}`;\n const known = toolCall.id ? findById(toolCall.id) : undefined;\n if (known !== undefined) {\n accumulator.keyByIndex.set(toolCall.index, known);\n return known;\n }\n const existingId = calls.get(key)?.id;\n if (existingId && toolCall.id && existingId !== toolCall.id) {\n const next = findById(toolCall.id) ?? `index-${toolCall.index}-${calls.size}`;\n accumulator.keyByIndex.set(toolCall.index, next);\n return next;\n }\n return key;\n }\n if (toolCall.id) {\n const known = findById(toolCall.id);\n if (known !== undefined) {\n return known;\n }\n }\n if (toolCall.id || name || accumulator.lastKey === undefined) {\n return `no-index-${calls.size}`;\n }\n return accumulator.lastKey;\n}\n","import { spanToJSON, timestampInSeconds } from '@sentry/core';\nimport type { Span } from '@sentry/core';\nimport { GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK } from '@sentry/conventions/attributes';\n\n/**\n * Sets `gen_ai.response.time_to_first_chunk` on a streamed span, in seconds from the span start.\n * Call it for each received chunk. Only the first call per span records a value.\n */\nexport function recordTimeToFirstChunk(span: Span): void {\n const { attributes, start_timestamp } = spanToJSON(span);\n if (attributes[GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK] === undefined) {\n span.setAttribute(GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK, timestampInSeconds() - start_timestamp);\n }\n}\n","/**\n * Gen-AI telemetry attributes that are not (yet) covered by `@sentry/conventions`.\n *\n * Attributes with an equivalent in `@sentry/conventions/attributes` are imported from there directly\n * at their call sites. The constants below either have no conventions equivalent, are Sentry-internal\n * meta attributes, are span-operation values (not attribute keys), or intentionally emit a different\n * key than the current conventions attribute.\n *\n * Based on OpenTelemetry Semantic Conventions for Generative AI\n * @see https://opentelemetry.io/docs/specs/semconv/gen-ai/\n */\n\n/**\n * Whether streaming was enabled for the request\n */\nexport const GEN_AI_REQUEST_STREAM_ATTRIBUTE = 'gen_ai.request.stream';\n\n/**\n * The encoding format for the model request\n */\nexport const GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE = 'gen_ai.request.encoding_format';\n\n/**\n * The dimensions for the model request\n */\nexport const GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE = 'gen_ai.request.dimensions';\n\n/**\n * The reason why the model stopped generating tokens\n */\nexport const GEN_AI_RESPONSE_STOP_REASON_ATTRIBUTE = 'gen_ai.response.stop_reason';\n\n/**\n * The tool call ID\n */\nexport const GEN_AI_TOOL_CALL_ID_ATTRIBUTE = 'gen_ai.tool.call.id';\n","/**\n * Maps OpenAI decisions requests and responses to the format Jev calls are recorded in, so Sentry renders\n * both the same way.\n */\nimport { isObjectLike } from '@sentry/core';\nimport { getEvaluationInputMessages, getEvaluationOutputMessages } from '../core/utils';\nimport type { GenAiMessage, GenAiMessagePart } from '../types';\n\n/**\n * Serialize a decisions request. Its evidence is `input` where Jev's is `state`; it is recorded as `state`\n * so both render the same.\n */\nexport function getDecisionInputMessages(params: Record<string, unknown>): string | undefined {\n const questions = Array.isArray(params.questions) ? params.questions.map(toJevQuestionFormat) : params.questions;\n return getEvaluationInputMessages({ state: toStateMessages(params.input), questions: keyByName(questions) });\n}\n\n/**\n * Lay out evidence messages as gen_ai messages, so they render like Google's. Other input items (tool calls and\n * their outputs) keep their layout, with output parts mapped like message parts.\n */\nfunction toStateMessages(input: unknown): unknown {\n if (!Array.isArray(input)) {\n return input;\n }\n\n return input.map(item => {\n if (!isObjectLike(item)) {\n return item;\n }\n if (typeof item.role === 'string') {\n return {\n // The gen_ai conventions have no `developer` role.\n role: (item.role === 'developer' ? 'system' : item.role) as GenAiMessage['role'],\n parts: Array.isArray(item.content)\n ? item.content.filter(isObjectLike).map(toMessagePart)\n : [{ type: 'text', content: item.content }],\n } satisfies GenAiMessage;\n }\n return Array.isArray(item.output) ? { ...item, output: item.output.filter(isObjectLike).map(toMessagePart) } : item;\n });\n}\n\n/**\n * An image in a data URL is reported by its media type only: the URL holds base64, which the conventions require to be\n * dropped.\n */\nfunction toMessagePart(part: Record<PropertyKey, unknown>): GenAiMessagePart {\n if (part.type === 'input_image' && typeof part.image_url === 'string') {\n const dataUrlMimeType = /^data:([^;,]+)/.exec(part.image_url)?.[1];\n return part.image_url.startsWith('data:')\n ? { type: 'blob', modality: 'image', mime_type: dataUrlMimeType }\n : { type: 'uri', modality: 'image', uri: part.image_url };\n }\n if (part.type === 'input_json') {\n return { type: 'object', content: part.data };\n }\n return { type: 'text', content: part.text ?? part.refusal };\n}\n\n/** Serialize the answers of a decisions response, laid out and keyed like Jev answers. */\nexport function getDecisionOutputMessages(answers: unknown[]): string | undefined {\n return getEvaluationOutputMessages(keyByName(answers.map(toJevAnswerFormat)));\n}\n\n/**\n * Lay out a decisions question like a Jev question, with its options in `criteria`: choices as\n * `{ [value]: description }` (an empty description when there is none), and score levels as their labels,\n * indexed by score value, with any level descriptions in `descriptions`, keyed by score value.\n */\nfunction toJevQuestionFormat(question: unknown): unknown {\n if (!isObjectLike(question)) {\n return question;\n }\n\n if (question.type === 'choice' && Array.isArray(question.choices)) {\n const { choices, ...rest } = question;\n const criteria = Object.fromEntries(\n choices\n .filter(isObjectLike)\n .map(choice => [String(choice.value), typeof choice.description === 'string' ? choice.description : '']),\n );\n return { ...rest, criteria };\n }\n\n if (question.type === 'score' && Array.isArray(question.levels)) {\n const { levels, ...rest } = question;\n const criteria = levels.map(level => (isObjectLike(level) ? level.label : level));\n // Sentry renders score criteria as a list of labels only, so level descriptions go in their own field,\n // keyed by score value like an answer's `legend`.\n const descriptions = Object.fromEntries(\n levels.flatMap((level, index) =>\n isObjectLike(level) && typeof level.description === 'string' ? [[String(index), level.description]] : [],\n ),\n );\n return Object.keys(descriptions).length ? { ...rest, criteria, descriptions } : { ...rest, criteria };\n }\n\n return question;\n}\n\n/**\n * Lay out choice and score answers like Jev answers: probabilities keyed by option or score value, with\n * score labels in a `legend`. Predicate answers are already in the shape Sentry renders.\n */\nfunction toJevAnswerFormat(answer: unknown): unknown {\n if (\n !isObjectLike(answer) ||\n (answer.type !== 'choice' && answer.type !== 'score') ||\n !Array.isArray(answer.probabilities)\n ) {\n return answer;\n }\n\n const options = answer.probabilities.filter(isObjectLike);\n const probabilities = Object.fromEntries(options.map(option => [String(option.value), option.probability]));\n if (answer.type === 'choice') {\n // Choice values can be booleans, but Sentry renders a choice as a string, like its `probabilities` keys.\n return { ...answer, choice: String(answer.choice), probabilities };\n }\n\n const legend = Object.fromEntries(\n options.filter(option => typeof option.label === 'string').map(option => [String(option.value), option.label]),\n );\n return { ...answer, probabilities, legend };\n}\n\n/**\n * The decisions API lists questions and answers as arrays with an optional `name`, where the conventions\n * key them by question name. An unnamed item is keyed by its position.\n */\nfunction keyByName(items: unknown): unknown {\n if (!Array.isArray(items)) {\n return items;\n }\n\n return Object.fromEntries(\n items.map((item, index) => {\n if (!isObjectLike(item)) {\n return [String(index), item];\n }\n const { name, ...rest } = item;\n return [typeof name === 'string' ? name : String(index), rest];\n }),\n );\n}\n","/* eslint-disable typescript-eslint/no-deprecated */\nimport { isObjectLike } from '@sentry/core';\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_OUTPUT_MESSAGES,\n GEN_AI_REQUEST_FREQUENCY_PENALTY,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_REQUEST_PRESENCE_PENALTY,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_REQUEST_TOP_P,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n} from '@sentry/conventions/attributes';\nimport {\n GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE,\n GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE,\n GEN_AI_REQUEST_STREAM_ATTRIBUTE,\n} from '../core/gen-ai-attributes';\nimport { getDecisionOutputMessages } from './mapping';\nimport type { ChatCompletionChunk, ResponseStreamingEvent } from './types';\n\n/**\n * Check if streaming event is from the Responses API\n */\nexport function isResponsesApiStreamEvent(event: unknown): event is ResponseStreamingEvent {\n return (\n event !== null &&\n typeof event === 'object' &&\n 'type' in event &&\n typeof (event as Record<string, unknown>).type === 'string' &&\n ((event as Record<string, unknown>).type as string).startsWith('response.')\n );\n}\n\n/**\n * Check if streaming event is a chat completion chunk\n */\nexport function isChatCompletionChunk(event: unknown): event is ChatCompletionChunk {\n return (\n event !== null &&\n typeof event === 'object' &&\n 'object' in event &&\n (event as Record<string, unknown>).object === 'chat.completion.chunk'\n );\n}\n\n/**\n * Add response attributes to a span using duck-typing.\n * Works for Chat Completions, Responses API, Embeddings, and Conversations API responses. Decision\n * answers are only recorded when `operationName` is `decide`.\n */\nexport function addResponseAttributes(\n span: Span,\n result: unknown,\n recordOutputs?: boolean,\n operationName?: string,\n): void {\n if (!result || typeof result !== 'object') return;\n\n const response = result as Record<string, unknown>;\n const attrs: Record<string, SpanAttributeValue> = {};\n\n // Response ID\n if (typeof response.id === 'string') {\n attrs[GEN_AI_RESPONSE_ID] = response.id;\n }\n\n // Response model\n if (typeof response.model === 'string') {\n attrs[GEN_AI_RESPONSE_MODEL] = response.model;\n }\n\n // Conversation ID (conversation objects use id as conversation link)\n if (response.object === 'conversation' && typeof response.id === 'string') {\n attrs[GEN_AI_CONVERSATION_ID] = response.id;\n }\n\n if (isObjectLike(response.usage)) {\n addUsageAttributes(attrs, response.usage);\n }\n\n // Finish reasons from choices (chat completions)\n if (Array.isArray(response.choices)) {\n const choices = response.choices as Array<Record<string, unknown>>;\n const finishReasons = choices\n .map(choice => choice.finish_reason)\n .filter((reason): reason is string => typeof reason === 'string');\n if (finishReasons.length > 0) {\n attrs[GEN_AI_RESPONSE_FINISH_REASONS] = JSON.stringify(finishReasons);\n }\n\n if (recordOutputs) {\n // Response text from choices\n const responseTexts = choices.map(choice => {\n const message = choice.message as Record<string, unknown> | undefined;\n return (message?.content as string) || '';\n });\n attrs[GEN_AI_RESPONSE_TEXT] = JSON.stringify(responseTexts);\n\n // Tool calls from choices\n const toolCalls = choices\n .map(choice => {\n const message = choice.message as Record<string, unknown> | undefined;\n return message?.tool_calls;\n })\n .filter(calls => Array.isArray(calls) && calls.length > 0)\n .flat();\n\n if (toolCalls.length > 0) {\n attrs[GEN_AI_RESPONSE_TOOL_CALLS] = JSON.stringify(toolCalls);\n }\n }\n }\n\n // Finish reason from status (responses API)\n if (typeof response.status === 'string') {\n // Only set if not already set from choices\n if (!attrs[GEN_AI_RESPONSE_FINISH_REASONS]) {\n attrs[GEN_AI_RESPONSE_FINISH_REASONS] = JSON.stringify([response.status]);\n }\n }\n\n if (recordOutputs) {\n // Response text from output_text (responses API)\n if (typeof response.output_text === 'string' && !attrs[GEN_AI_RESPONSE_TEXT]) {\n attrs[GEN_AI_RESPONSE_TEXT] = response.output_text;\n }\n\n // Typed answers (decisions API)\n if (operationName === 'decide' && Array.isArray(response.answers)) {\n const outputMessages = getDecisionOutputMessages(response.answers);\n if (outputMessages) {\n attrs[GEN_AI_OUTPUT_MESSAGES] = outputMessages;\n }\n }\n\n // Tool calls from output array (responses API)\n if (Array.isArray(response.output) && response.output.length > 0 && !attrs[GEN_AI_RESPONSE_TOOL_CALLS]) {\n const functionCalls = (response.output as Array<Record<string, unknown>>).filter(\n item => item?.type === 'function_call',\n );\n if (functionCalls.length > 0) {\n attrs[GEN_AI_RESPONSE_TOOL_CALLS] = JSON.stringify(functionCalls);\n }\n }\n }\n\n span.setAttributes(attrs);\n}\n\n/**\n * Token usage, in both naming conventions (chat: prompt_tokens/completion_tokens,\n * responses and decisions: input_tokens/output_tokens).\n */\nfunction addUsageAttributes(attrs: Record<string, SpanAttributeValue>, usage: Record<string, unknown>): void {\n const inputTokens = usage.prompt_tokens ?? usage.input_tokens;\n if (typeof inputTokens === 'number') {\n attrs[GEN_AI_USAGE_INPUT_TOKENS] = inputTokens;\n }\n\n const outputTokens = usage.completion_tokens ?? usage.output_tokens;\n if (typeof outputTokens === 'number') {\n attrs[GEN_AI_USAGE_OUTPUT_TOKENS] = outputTokens;\n }\n\n if (typeof usage.total_tokens === 'number') {\n attrs[GEN_AI_USAGE_TOTAL_TOKENS] = usage.total_tokens;\n }\n const inputDetails = usage.prompt_tokens_details ?? usage.input_tokens_details;\n if (isObjectLike(inputDetails)) {\n if (typeof inputDetails.cached_tokens === 'number') {\n attrs[GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS] = inputDetails.cached_tokens;\n }\n if (typeof inputDetails.cache_write_tokens === 'number') {\n attrs[GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS] = inputDetails.cache_write_tokens;\n }\n }\n const outputDetails = usage.completion_tokens_details ?? usage.output_tokens_details;\n if (isObjectLike(outputDetails) && typeof outputDetails.reasoning_tokens === 'number') {\n attrs[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS] = outputDetails.reasoning_tokens;\n }\n}\n\n/**\n * Extract the Conversations API id (`conversation: \"conv_...\"`) from request parameters.\n * `previous_response_id` is deliberately not read: it names the previous response, so it changes on\n * every turn and cannot group a conversation's spans.\n * @see https://platform.openai.com/docs/guides/conversation-state\n */\nfunction extractConversationId(params: Record<string, unknown>): string | undefined {\n return 'conversation' in params && typeof params.conversation === 'string' ? params.conversation : undefined;\n}\n\n/**\n * Extract request parameters including model settings and conversation context\n */\nexport function extractRequestParameters(params: Record<string, unknown>): Record<string, unknown> {\n const attributes: Record<string, unknown> = {\n [GEN_AI_REQUEST_MODEL]: params.model ?? 'unknown',\n };\n\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 ('frequency_penalty' in params) attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY] = params.frequency_penalty;\n if ('presence_penalty' in params) attributes[GEN_AI_REQUEST_PRESENCE_PENALTY] = params.presence_penalty;\n if ('stream' in params) attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE] = params.stream;\n if ('encoding_format' in params) attributes[GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE] = params.encoding_format;\n if ('dimensions' in params) attributes[GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE] = params.dimensions;\n\n // Capture conversation ID for linking messages across API calls\n const conversationId = extractConversationId(params);\n if (conversationId) {\n attributes[GEN_AI_CONVERSATION_ID] = conversationId;\n }\n\n return attributes;\n}\n","import { captureException, SPAN_STATUS_ERROR } from '@sentry/core';\nimport type { Span } from '@sentry/core';\nimport { getToolCallKey } from '../core/streaming-tool-calls';\nimport type { GenAiSpanResult } from '../core/span-hooks';\nimport { endStreamSpan } from '../core/utils';\nimport { recordTimeToFirstChunk } from '../core/time-to-first-chunk';\nimport { RESPONSE_EVENT_TYPES } from './constants';\nimport type {\n ChatCompletionChunk,\n ChatCompletionToolCall,\n OpenAIResponseObject,\n ResponseFunctionCall,\n ResponseStreamingEvent,\n} from './types';\nimport { isChatCompletionChunk, isResponsesApiStreamEvent } from './utils';\n\n/**\n * State object used to accumulate information from a stream of OpenAI events/chunks.\n */\ninterface StreamingState {\n /** Types of events encountered in the stream. */\n eventTypes: string[];\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 prompt/input tokens used. */\n promptTokens: number | undefined;\n /** Number of completion/output tokens used. */\n completionTokens: number | undefined;\n /** Total number of tokens used (prompt + completion). */\n totalTokens: number | undefined;\n cacheReadInputTokens: number | undefined;\n cacheCreationInputTokens: number | undefined;\n /**\n * Accumulated tool calls from Chat Completion streaming, keyed by string in the order they were opened.\n * @see https://platform.openai.com/docs/guides/function-calling?api-mode=chat#streaming\n */\n chatCompletionToolCalls: Map<string, ChatCompletionToolCall>;\n /** Key of the latest tool call, which unindexed argument fragments continue. */\n lastChatCompletionToolCallKey?: string;\n /** Key of the call currently open for a reported `index`, when a new `id` reused that index. */\n chatCompletionToolCallKeyByIndex?: Map<number, string>;\n /**\n * Accumulated function calls from Responses API streaming.\n * @see https://platform.openai.com/docs/guides/function-calling?api-mode=responses#streaming\n */\n responsesApiToolCalls: Array<ResponseFunctionCall | unknown>;\n}\n\n/**\n * Processes tool calls from a chat completion chunk delta.\n * Follows the pattern: accumulate by index, then convert to array at the end.\n *\n * @param toolCalls - Array of tool calls from the delta.\n * @param state - The current streaming state to update.\n *\n * @see https://platform.openai.com/docs/guides/function-calling#streaming\n */\nfunction processChatCompletionToolCalls(toolCalls: ChatCompletionToolCall[], state: StreamingState): void {\n for (const toolCall of toolCalls) {\n if (!toolCall.function) continue;\n const index = getToolCallKey(toolCall, toolCall.function.name, {\n calls: state.chatCompletionToolCalls,\n keyByIndex: (state.chatCompletionToolCallKeyByIndex ??= new Map()),\n lastKey: state.lastChatCompletionToolCallKey,\n });\n\n // Initialize tool call if this is the first chunk for this index\n const existingToolCall = state.chatCompletionToolCalls.get(index);\n if (!existingToolCall) {\n state.chatCompletionToolCalls.set(index, {\n ...toolCall,\n function: {\n name: toolCall.function.name,\n arguments: toolCall.function.arguments || '',\n },\n });\n } else {\n // Accumulate function arguments from subsequent chunks\n if (toolCall.function.arguments && existingToolCall.function) {\n existingToolCall.function.arguments += toolCall.function.arguments;\n }\n }\n state.lastChatCompletionToolCallKey = index;\n }\n}\n\n/**\n * Processes a single OpenAI ChatCompletionChunk event, updating the streaming state.\n *\n * @param chunk - The ChatCompletionChunk event to process.\n * @param state - The current streaming state to update.\n * @param recordOutputs - Whether to record output text fragments.\n */\nfunction processChatCompletionChunk(chunk: ChatCompletionChunk, state: StreamingState, recordOutputs: boolean): void {\n state.responseId = chunk.id ?? state.responseId;\n state.responseModel = chunk.model ?? state.responseModel;\n\n if (chunk.usage) {\n // For stream responses, the input tokens remain constant across all events in the stream.\n // Output tokens, however, are only finalized in the last event.\n // Since we can't guarantee that the last event will include usage data or even be a typed event,\n // we update the output token values on every event that includes them.\n // This ensures that output token usage is always set, even if the final event lacks it.\n state.promptTokens = chunk.usage.prompt_tokens;\n state.completionTokens = chunk.usage.completion_tokens;\n state.totalTokens = chunk.usage.total_tokens;\n state.cacheReadInputTokens = chunk.usage.prompt_tokens_details?.cached_tokens ?? state.cacheReadInputTokens;\n state.cacheCreationInputTokens =\n chunk.usage.prompt_tokens_details?.cache_write_tokens ?? state.cacheCreationInputTokens;\n }\n\n for (const choice of chunk.choices ?? []) {\n if (recordOutputs) {\n if (choice.delta?.content) {\n state.responseTexts.push(choice.delta.content);\n }\n\n // Handle tool calls from delta\n if (choice.delta?.tool_calls) {\n processChatCompletionToolCalls(choice.delta.tool_calls, state);\n }\n }\n if (choice.finish_reason) {\n state.finishReasons.push(choice.finish_reason);\n }\n }\n}\n\n/**\n * Processes a single OpenAI Responses API streaming event, updating the streaming state and span.\n *\n * @param streamEvent - The event to process (may be an error or unknown object).\n * @param state - The current streaming state to update.\n * @param recordOutputs - Whether to record output text fragments.\n * @param span - The span to update with error status if needed.\n */\nfunction processResponsesApiEvent(\n streamEvent: ResponseStreamingEvent | unknown | Error,\n state: StreamingState,\n recordOutputs: boolean,\n span: Span,\n): void {\n if (!(streamEvent && typeof streamEvent === 'object')) {\n state.eventTypes.push('unknown:non-object');\n return;\n }\n if (streamEvent instanceof Error) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n captureException(streamEvent, {\n mechanism: {\n handled: false,\n type: 'auto.ai.openai.stream-response',\n },\n });\n return;\n }\n\n if (!('type' in streamEvent)) return;\n const event = streamEvent as ResponseStreamingEvent;\n\n if (!RESPONSE_EVENT_TYPES.includes(event.type)) {\n state.eventTypes.push(event.type);\n return;\n }\n\n // Handle output text delta\n if (recordOutputs) {\n // Handle tool call events for Responses API\n if (event.type === 'response.output_item.done' && 'item' in event) {\n state.responsesApiToolCalls.push(event.item);\n }\n\n if (event.type === 'response.output_text.delta' && 'delta' in event && event.delta) {\n state.responseTexts.push(event.delta);\n return;\n }\n }\n\n if ('response' in event) {\n const { response } = event as { response: OpenAIResponseObject };\n state.responseId = response.id ?? state.responseId;\n state.responseModel = response.model ?? state.responseModel;\n\n if (response.usage) {\n // For stream responses, the input tokens remain constant across all events in the stream.\n // Output tokens, however, are only finalized in the last event.\n // Since we can't guarantee that the last event will include usage data or even be a typed event,\n // we update the output token values on every event that includes them.\n // This ensures that output token usage is always set, even if the final event lacks it.\n state.promptTokens = response.usage.input_tokens;\n state.completionTokens = response.usage.output_tokens;\n state.totalTokens = response.usage.total_tokens;\n state.cacheReadInputTokens = response.usage.input_tokens_details?.cached_tokens ?? state.cacheReadInputTokens;\n state.cacheCreationInputTokens =\n response.usage.input_tokens_details?.cache_write_tokens ?? state.cacheCreationInputTokens;\n }\n\n if (response.status) {\n state.finishReasons.push(response.status);\n }\n\n if (recordOutputs && response.output_text) {\n state.responseTexts.push(response.output_text);\n }\n }\n}\n\n/**\n * Instruments a stream of OpenAI events, updating the provided span with relevant attributes and\n * optionally recording output text. This function yields each event from the input stream as it is processed.\n *\n * @template T - The type of events in the stream.\n * @param stream - The async iterable stream of events to instrument.\n * @param span - The span to add attributes to and to finish at the end of the stream.\n * @param recordOutputs - Whether to record output text fragments in the span.\n * @param beforeSpanEnd - Runs right before the span ends, with the error when the stream failed.\n * @returns An async generator yielding each event from the input stream.\n */\nexport async function* instrumentStream<T>(\n stream: AsyncIterable<T>,\n span: Span,\n recordOutputs: boolean,\n beforeSpanEnd?: (result: GenAiSpanResult<never>) => void,\n): AsyncGenerator<T, void, unknown> {\n const state: StreamingState = {\n eventTypes: [],\n responseTexts: [],\n finishReasons: [],\n responseId: '',\n responseModel: '',\n promptTokens: undefined,\n completionTokens: undefined,\n totalTokens: undefined,\n cacheReadInputTokens: undefined,\n cacheCreationInputTokens: undefined,\n chatCompletionToolCalls: new Map(),\n responsesApiToolCalls: [],\n };\n\n const result: GenAiSpanResult<never> = {};\n\n try {\n for await (const event of stream) {\n recordTimeToFirstChunk(span);\n if (isChatCompletionChunk(event)) {\n processChatCompletionChunk(event, state, recordOutputs);\n } else if (isResponsesApiStreamEvent(event)) {\n processResponsesApiEvent(event, state, recordOutputs, span);\n }\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 const allToolCalls = [...state.chatCompletionToolCalls.values(), ...state.responsesApiToolCalls];\n endStreamSpan(span, { ...state, toolCalls: allToolCalls }, recordOutputs, () => beforeSpanEnd?.(result));\n }\n}\n","/* eslint-disable typescript-eslint/no-deprecated */\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { getClient, hasSpanStreamingEnabled, startSpan, startSpanManual, debug, stringify } from '@sentry/core';\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_TOOL_DEFINITIONS,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport type { InstrumentedMethodEntry } from '../core/utils';\nimport {\n buildMethodPath,\n extractSystemInstructions,\n getErrorStatus,\n getGenAiSpanOp,\n getRequestSignal,\n resolveGenAiCallRecording,\n wrapPromiseWithMethods,\n} from '../core/utils';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport { OPENAI_METHOD_REGISTRY } from './constants';\nimport { instrumentStream } from './streaming';\nimport type { ChatCompletionChunk, OpenAiCallInfo, OpenAiOptions, OpenAIStream, ResponseStreamingEvent } from './types';\nimport { getDecisionInputMessages } from './mapping';\nimport { addResponseAttributes, extractRequestParameters } from './utils';\n\n/**\n * Extract available tools from request parameters\n */\nfunction extractAvailableTools(params: Record<string, unknown>): string | undefined {\n const tools = Array.isArray(params.tools) ? params.tools : [];\n const hasWebSearchOptions = params.web_search_options && typeof params.web_search_options === 'object';\n const webSearchOptions = hasWebSearchOptions\n ? [{ type: 'web_search_options', ...(params.web_search_options as Record<string, unknown>) }]\n : [];\n\n const availableTools = [...tools, ...webSearchOptions];\n if (availableTools.length === 0) {\n return undefined;\n }\n\n try {\n return JSON.stringify(availableTools);\n } catch (error) {\n DEBUG_BUILD && debug.error('Failed to serialize OpenAI tools:', error);\n return undefined;\n }\n}\n\n/**\n * Extract request attributes from method arguments\n */\nexport function extractRequestAttributes(\n args: unknown[],\n operationName: string,\n recordInputs: boolean,\n): Record<string, unknown> {\n const attributes: Record<string, unknown> = {\n [GEN_AI_PROVIDER_NAME]: 'openai',\n [GEN_AI_OPERATION_NAME]: operationName,\n [SENTRY_ORIGIN]: 'auto.ai.openai',\n };\n\n if (args.length > 0 && typeof args[0] === 'object' && args[0] !== null) {\n const params = args[0] as Record<string, unknown>;\n\n if (recordInputs) {\n attributes[GEN_AI_TOOL_DEFINITIONS] = extractAvailableTools(params);\n }\n\n Object.assign(attributes, extractRequestParameters(params));\n\n if (recordInputs && operationName === 'decide') {\n attributes[GEN_AI_INPUT_MESSAGES] = getDecisionInputMessages(params);\n }\n } else {\n attributes[GEN_AI_REQUEST_MODEL] = 'unknown';\n }\n\n return attributes;\n}\n\n// Extract and record AI request inputs, if present. This is intentionally separate from response attributes.\nexport function addRequestAttributes(span: Span, params: Record<string, unknown>, operationName: string): void {\n // A decision's input is recorded when its span starts, in `extractRequestAttributes`.\n if (operationName === 'decide') {\n return;\n }\n\n // Store embeddings input on a separate attribute\n if (operationName === 'embeddings' && 'input' in params) {\n const input = params.input;\n\n // No input provided\n if (input == null) {\n return;\n }\n\n // Empty input string\n if (typeof input === 'string' && input.length === 0) {\n return;\n }\n\n // Empty array input\n if (Array.isArray(input) && input.length === 0) {\n return;\n }\n\n span.setAttribute(GEN_AI_EMBEDDINGS_INPUT, stringify(input, String));\n return;\n }\n\n const src = 'input' in params ? params.input : 'messages' in params ? params.messages : undefined;\n\n if (!src) {\n return;\n }\n\n if (Array.isArray(src) && src.length === 0) {\n return;\n }\n\n const { systemInstructions, filteredMessages } = extractSystemInstructions(src);\n\n if (systemInstructions) {\n span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS, systemInstructions);\n }\n\n span.setAttribute(GEN_AI_INPUT_MESSAGES, stringify(filteredMessages));\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) => Promise<R>,\n methodPath: string,\n instrumentedMethod: InstrumentedMethodEntry,\n context: unknown,\n options: OpenAiOptions,\n): (...args: T) => Promise<R> {\n return function instrumentedCall(...args: T): Promise<R> {\n const operationName = instrumentedMethod.operation || 'unknown';\n const params = args[0] as Record<string, unknown> | undefined;\n const call: OpenAiCallInfo = { operation: operationName, request: params };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n const requestAttributes = extractRequestAttributes(args, operationName, recordInputs);\n const model = (requestAttributes[GEN_AI_REQUEST_MODEL] as string) || 'unknown';\n\n const isStreamRequested = params && typeof params === 'object' && params.stream === true;\n const abortSignal = getRequestSignal(args[1]);\n const client = getClient();\n\n const spanConfig = {\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name:\n model !== 'unknown' || !(client && hasSpanStreamingEnabled(client))\n ? `${operationName} ${model}`\n : operationName,\n op: getGenAiSpanOp(operationName),\n attributes: requestAttributes as Record<string, SpanAttributeValue>,\n };\n\n if (isStreamRequested) {\n let originalResult!: Promise<R>;\n\n const instrumentedPromise = startSpanManual(spanConfig, (span: Span) => {\n originalResult = originalMethod.apply(context, args);\n\n if (recordInputs && params) {\n addRequestAttributes(span, params, operationName);\n }\n runGenAiSpanStart(options, span, call);\n\n // Return async processing\n return (async () => {\n try {\n const result = await originalResult;\n return instrumentStream(\n result as OpenAIStream<ChatCompletionChunk | ResponseStreamingEvent>,\n span,\n recordOutputs,\n streamResult => runGenAiSpanEnd(options, span, call, streamResult),\n ) as unknown as R;\n } catch (error) {\n span.setStatus(getErrorStatus(abortSignal));\n runGenAiSpanEnd(options, span, call, { error });\n span.end();\n throw error;\n }\n })();\n });\n\n return wrapPromiseWithMethods(originalResult, instrumentedPromise);\n }\n\n // Non-streaming\n let originalResult!: Promise<R>;\n\n const instrumentedPromise = startSpan(spanConfig, (span: Span) => {\n // Call synchronously to capture the promise\n originalResult = originalMethod.apply(context, args);\n\n if (recordInputs && params) {\n addRequestAttributes(span, params, operationName);\n }\n runGenAiSpanStart(options, span, call);\n\n return originalResult.then(\n result => {\n addResponseAttributes(span, result, recordOutputs, operationName);\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 * Create a deep proxy for OpenAI client instrumentation\n */\nfunction createDeepProxy<T extends object>(target: T, currentPath = '', options: OpenAiOptions): T {\n const propertyCache = new Map<PropertyKey, { original: unknown; wrapped: unknown }>();\n\n return new Proxy(target, {\n get(obj: object, prop: string | symbol): unknown {\n const value = Reflect.get(obj, prop) as unknown;\n const cachedEntry = propertyCache.get(prop);\n if (cachedEntry) {\n if (cachedEntry.original === value) {\n return cachedEntry.wrapped;\n }\n propertyCache.delete(prop);\n }\n\n const methodPath = buildMethodPath(currentPath, String(prop));\n\n const instrumentedMethod = OPENAI_METHOD_REGISTRY[methodPath as keyof typeof OPENAI_METHOD_REGISTRY];\n if (typeof value === 'function' && instrumentedMethod) {\n const wrappedMethod = instrumentMethod(\n value as (...args: unknown[]) => Promise<unknown>,\n methodPath,\n instrumentedMethod,\n obj,\n options,\n );\n propertyCache.set(prop, { original: value, wrapped: wrappedMethod });\n return wrappedMethod;\n }\n\n if (typeof value === 'function') {\n // Bind non-instrumented functions to preserve the original `this` context,\n // which is required for accessing private class fields (e.g. #baseURL) in OpenAI SDK v5.\n const boundMethod = value.bind(obj);\n propertyCache.set(prop, { original: value, wrapped: boundMethod });\n return boundMethod;\n }\n\n if (value && typeof value === 'object') {\n const nestedProxy = createDeepProxy(value, methodPath, options);\n propertyCache.set(prop, { original: value, wrapped: nestedProxy });\n return nestedProxy;\n }\n\n return value;\n },\n }) as T;\n}\n\n/**\n * Instrument an OpenAI client with Sentry tracing\n * Can be used across Node.js, Cloudflare Workers, and Vercel Edge\n */\nexport function instrumentOpenAiClient<T extends object>(client: T, options?: OpenAiOptions): T {\n return createDeepProxy(client, '', options ?? {});\n}\n","import type { InstrumentedMethodRegistry } from '../core/utils';\n\nexport const ANTHROPIC_AI_INTEGRATION_NAME = 'Anthropic_AI' as const;\n\n// https://docs.anthropic.com/en/api/messages\nexport const ANTHROPIC_METHOD_REGISTRY = {\n 'messages.create': { operation: 'chat' },\n 'messages.stream': { operation: 'chat', streaming: true },\n 'completions.create': { operation: 'chat' },\n 'beta.messages.create': { operation: 'chat' },\n} as const satisfies InstrumentedMethodRegistry;\n\nexport const ANTHROPIC_AI_ORIGIN = 'auto.ai.anthropic';\n","/* eslint-disable typescript-eslint/no-deprecated */\nimport { captureException, isObjectLike, SPAN_STATUS_ERROR, stringify } from '@sentry/core';\nimport type { Span, SpanStatusType } from '@sentry/core';\nimport {\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n} from '@sentry/conventions/attributes';\nimport { extractSystemInstructions, getTokenUsageAttributes } from '../core/utils';\nimport type { AnthropicAiResponse, ContentBlock } from './types';\n\n/**\n * The `gen_ai.provider.name` of the client that owns an SDK resource such as `messages`. The SDK's clients\n * for other platforms set their own, e.g. `aws.bedrock` for `AnthropicBedrock`.\n */\nexport function getProviderName(resource: unknown): string {\n const name = (resource as { _client?: { _genAIProviderName?: unknown } } | null | undefined)?._client\n ?._genAIProviderName;\n return typeof name === 'string' && name ? name : 'anthropic';\n}\n\n/**\n * Get the input messages attribute, with system instructions extracted into their own attribute.\n */\nexport function getMessagesAttributes(messages: unknown): Record<string, string | undefined> {\n if (Array.isArray(messages) && messages.length === 0) {\n return {};\n }\n\n const { systemInstructions, filteredMessages } = extractSystemInstructions(messages);\n\n const attributes: Record<string, string | undefined> = {};\n if (systemInstructions) {\n attributes[GEN_AI_SYSTEM_INSTRUCTIONS] = systemInstructions;\n }\n attributes[GEN_AI_INPUT_MESSAGES] = stringify(filteredMessages);\n return attributes;\n}\n\nconst ANTHROPIC_ERROR_TYPE_TO_SPAN_STATUS: Record<string, SpanStatusType> = {\n invalid_request_error: 'invalid_argument',\n authentication_error: 'unauthenticated',\n permission_error: 'permission_denied',\n not_found_error: 'not_found',\n request_too_large: 'failed_precondition',\n rate_limit_error: 'resource_exhausted',\n api_error: 'internal_error',\n overloaded_error: 'unavailable',\n};\n\n/**\n * Map an Anthropic API error type to a SpanStatusType value.\n * @see https://docs.anthropic.com/en/api/errors#error-shapes\n */\nexport function mapAnthropicErrorToStatusMessage(errorType: string | undefined): SpanStatusType {\n if (!errorType) {\n return 'internal_error';\n }\n return ANTHROPIC_ERROR_TYPE_TO_SPAN_STATUS[errorType] || 'internal_error';\n}\n\n/**\n * Capture error information from the response\n * @see https://docs.anthropic.com/en/api/errors#error-shapes\n */\nfunction handleResponseError(span: Span, response: AnthropicAiResponse): void {\n if (response.error) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: mapAnthropicErrorToStatusMessage(response.error.type) });\n\n captureException(response.error, {\n mechanism: {\n handled: false,\n type: 'auto.ai.anthropic.anthropic_error',\n },\n });\n }\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/** Anthropic accepts the system prompt as a string or as an array of text blocks. */\nfunction systemToText(system: unknown): string | undefined {\n if (!Array.isArray(system)) {\n return typeof system === 'string' ? system : undefined;\n }\n return system\n .map(block => (isObjectLike(block) ? block.text : undefined))\n .filter(text => typeof text === 'string' && text)\n .join('\\n');\n}\n\n/**\n * Include the system prompt in the messages list, if available\n */\nexport function messagesFromParams(params: Record<string, unknown>): unknown[] {\n const { system, messages, input, prompt } = params;\n\n const systemText = systemToText(system);\n const systemMessages = systemText ? [{ role: 'system', content: systemText }] : [];\n\n const inputParamMessages = Array.isArray(input) ? input : input != null ? [input] : undefined;\n\n const messagesParamMessages = Array.isArray(messages) ? messages : messages != null ? [messages] : [];\n\n // The legacy Completions API takes a single raw `prompt` string instead of a message list. Model\n // it as one user message so it lands on `gen_ai.input.messages` like every other request shape.\n const promptMessages = prompt != null ? [{ role: 'user', content: stringify(prompt, String) }] : [];\n\n const userMessages = inputParamMessages ?? (messagesParamMessages.length ? messagesParamMessages : promptMessages);\n\n return [...systemMessages, ...userMessages];\n}\n","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","import type { Scope } from '@sentry/core';\nimport { getClient, getDefaultCurrentScope, withIsolationScope, withScope } from '@sentry/core';\n\n/**\n * Run `callback` with `isolationScope` and a fresh copy of the default current scope. For work that\n * a library schedules from whichever async context last woke it: a forked scope would carry over the\n * data of that context, such as the conversation id of another run. Only the client of that context\n * is kept, because an SDK that initializes inside each request, such as `@sentry/cloudflare`, binds\n * it to the request's scope alone.\n */\nexport function withCleanScopes<T>(isolationScope: Scope, callback: () => T): T {\n const client = getClient();\n return withIsolationScope(isolationScope, () => {\n const scope = getDefaultCurrentScope().clone();\n if (client) {\n scope.setClient(client);\n }\n return withScope(scope, callback);\n });\n}\n","import type { Span, WrappedFunction } from '@sentry/core';\nimport {\n captureException,\n fill,\n getActiveSpan,\n getCurrentScope,\n getDefaultCurrentScope,\n getDefaultIsolationScope,\n getIsolationScope,\n getOriginalFunction,\n handleCallbackErrors,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n startNewTrace,\n startSpan,\n stringify,\n withActiveSpan,\n withScope,\n} from '@sentry/core';\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_OPERATION_NAME,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DESCRIPTION,\n GEN_AI_TOOL_NAME,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_EXECUTE_TOOL, GEN_AI_INVOKE_AGENT } from '@sentry/conventions/op';\nimport { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport { getErrorStatus, resolveGenAiCallRecording } from '../core/utils';\nimport { withCleanScopes } from '../../utils/withCleanScopes';\nimport { ANTHROPIC_AI_ORIGIN } from './constants';\nimport type { AnthropicAiCallInfo, AnthropicAiOptions } from './types';\n\ntype AnyFunction = (...args: unknown[]) => unknown;\ntype RunnableTool = { name: string; description?: unknown };\ntype RunContext = { toolUse?: { id?: unknown }; toolUseBlock?: { id?: unknown }; signal?: AbortSignal } | undefined;\ntype ToolRunner = { params?: { tools?: unknown } };\ntype SessionToolRunner = { tools?: unknown; sessionId?: unknown };\n\n/** Wrap the `toolRunner()` method of `owner` so the runners it returns trace their tool calls. */\nexport function instrumentToolRunnerFactory(\n owner: object,\n instrumentRunner: (runner: unknown, options: AnthropicAiOptions) => void,\n options: AnthropicAiOptions,\n): void {\n wrapInPlace(owner, 'toolRunner', (toolRunner, thisArg, args) => {\n const runner = toolRunner.apply(thisArg, args);\n instrumentRunner(runner, options);\n return runner;\n });\n}\n\n/** Give each tool call of a tool runner a `gen_ai.execute_tool` span. */\nexport function instrumentToolRunner(runner: unknown, options: AnthropicAiOptions): void {\n if (!runner || typeof runner !== 'object') {\n return;\n }\n\n instrumentTools((runner as ToolRunner).params?.tools, options);\n\n // `addTools()` keeps its tools out of `params`.\n wrapInPlace(runner, 'addTools', (addTools, thisArg, tools) => {\n instrumentTools(tools, options);\n return addTools.apply(thisArg, tools);\n });\n wrapInPlace(runner, 'setMessagesParams', (setMessagesParams, thisArg, args) => {\n const result = setMessagesParams.apply(thisArg, args);\n instrumentTools((runner as ToolRunner).params?.tools, options);\n return result;\n });\n}\n\n/** Give each tool call of a Managed Agents session runner an `execute_tool` span, under one `invoke_agent` span per session. */\nexport function instrumentSessionToolRunner(runner: unknown, options: AnthropicAiOptions): void {\n if (!runner || typeof runner !== 'object') {\n return;\n }\n\n const { tools, sessionId } = runner as SessionToolRunner;\n // The session runner has no `addTools()`: it only runs the tools it was created with.\n instrumentTools(tools, options);\n wrapInPlace(runner, Symbol.asyncIterator, (iterate, thisArg) =>\n traceSessionLoop(\n iterate.call(thisArg) as AsyncIterator<unknown>,\n typeof sessionId === 'string' ? sessionId : undefined,\n ),\n );\n}\n\n/** Wraps the SDK's session iterator so the whole session runs inside one `invoke_agent` span. */\nasync function* traceSessionLoop(\n sdkIterator: AsyncIterator<unknown>,\n sessionId: string | undefined,\n): AsyncGenerator<unknown> {\n const { span, firstResult } = startSession(sdkIterator, sessionId);\n\n try {\n let result = await firstResult;\n while (!result.done) {\n yield result.value;\n result = await sdkIterator.next();\n }\n } catch (error) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n throw error;\n } finally {\n try {\n // After a `break`, closing the SDK loop waits for its in-flight tools, so the span ends after them.\n await sdkIterator.return?.();\n } finally {\n span.end();\n }\n }\n}\n\n// The SDK starts its tool loop on the first `next()`, so that call runs in the session and every tool inherits it.\nfunction startSession(\n sdkIterator: AsyncIterator<unknown>,\n sessionId: string | undefined,\n): { span: Span; firstResult: Promise<IteratorResult<unknown>> } {\n const start = (): { span: Span; firstResult: Promise<IteratorResult<unknown>> } =>\n withScope(scope => {\n // A tool shared between runners can't tell its session, so the id reaches its spans through the scope, unless\n // the app set one with `Sentry.setConversationId()`.\n if (sessionId && !scope.getScopeData().conversationId && !getIsolationScope().getScopeData().conversationId) {\n scope.setConversationId(sessionId);\n }\n\n const span = startInactiveSpan({\n name: 'invoke_agent',\n op: GEN_AI_INVOKE_AGENT,\n attributes: {\n [SENTRY_ORIGIN]: ANTHROPIC_AI_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'invoke_agent',\n [GEN_AI_PROVIDER_NAME]: 'anthropic',\n ...(sessionId ? { [GEN_AI_CONVERSATION_ID]: sessionId } : {}),\n },\n });\n // `async`, so a `next()` that throws rejects `firstResult` and still ends the span.\n return { span, firstResult: withActiveSpan(span, async () => sdkIterator.next()) };\n });\n\n // At top level all sessions would share the process's trace, so each gets its own; anywhere else it stays in the\n // caller's.\n return !getActiveSpan() && getCurrentScope() === getDefaultCurrentScope()\n ? withCleanScopes(getDefaultIsolationScope().clone(), () => startNewTrace(start))\n : start();\n}\n\nfunction instrumentTools(tools: unknown, options: AnthropicAiOptions): void {\n if (!Array.isArray(tools)) {\n return;\n }\n\n for (const tool of tools) {\n // Toolsets are nameless entries whose `run` takes `(ctx, toolUse)`, so only named tools are wrapped.\n if (tool && typeof tool === 'object' && typeof (tool as RunnableTool).name === 'string') {\n wrapInPlace(tool, 'run', (run, thisArg, args) => runWithSpan(tool as RunnableTool, run, thisArg, args, options));\n }\n }\n}\n\nfunction wrapInPlace(\n owner: object,\n key: string | symbol,\n call: (original: AnyFunction, thisArg: unknown, args: unknown[]) => unknown,\n): void {\n const current = (owner as Record<string | symbol, unknown>)[key];\n if (typeof current === 'function' && !getOriginalFunction(current as WrappedFunction)) {\n fill(\n owner,\n key,\n (original: AnyFunction) =>\n function (this: unknown, ...args: unknown[]): unknown {\n return call(original, this, args);\n },\n );\n }\n}\n\nfunction runWithSpan(\n tool: RunnableTool,\n run: AnyFunction,\n thisArg: unknown,\n args: unknown[],\n options: AnthropicAiOptions,\n): unknown {\n const [input, context] = args as [unknown, RunContext];\n const call: AnthropicAiCallInfo = { operation: 'execute_tool', tool, input };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n // SDK versions before `toolUse` existed pass only `toolUseBlock`.\n const callId = (context?.toolUse ?? context?.toolUseBlock)?.id;\n\n return startSpan(\n {\n name: `execute_tool ${tool.name}`,\n op: GEN_AI_EXECUTE_TOOL,\n attributes: {\n [SENTRY_ORIGIN]: ANTHROPIC_AI_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'execute_tool',\n [GEN_AI_TOOL_NAME]: tool.name,\n ...(typeof tool.description === 'string' ? { [GEN_AI_TOOL_DESCRIPTION]: tool.description } : {}),\n ...(typeof callId === 'string' ? { [GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: callId } : {}),\n ...(recordInputs ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(input) } : {}),\n },\n },\n span => {\n runGenAiSpanStart(options, span, call);\n return handleCallbackErrors(\n () => run.apply(thisArg, args),\n error => {\n handleToolError(span, error, context);\n runGenAiSpanEnd(options, span, call, { error });\n },\n undefined,\n result => {\n if (recordOutputs) {\n span.setAttribute(GEN_AI_TOOL_CALL_RESULT, stringify(result));\n }\n runGenAiSpanEnd(options, span, call, { response: result });\n },\n );\n },\n );\n}\n\nfunction handleToolError(span: Span, error: unknown, context: RunContext): void {\n span.setStatus(getErrorStatus(context?.signal));\n // An aborted tool, caller abort or timeout, throws because the run stopped, not because the tool failed.\n if (context?.signal?.aborted) {\n return;\n }\n\n // Only a runner passes `toolUse`/`toolUseBlock` (SDK 0.85+), and it hands the throw to the model as a result.\n // A direct call rethrows to its caller, and a `ToolError` is sent on purpose, so neither is captured.\n const fromRunner = !!(context?.toolUse ?? context?.toolUseBlock);\n if (fromRunner && (error as Error | undefined)?.name !== 'ToolError') {\n captureException(error, { mechanism: { handled: true, type: ANTHROPIC_AI_ORIGIN } });\n }\n}\n","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","import type { InstrumentedMethodRegistry } from '../core/utils';\n\nexport const GOOGLE_GENAI_INTEGRATION_NAME = 'Google_GenAI' as const;\n\n// https://ai.google.dev/api/rest/v1/models/generateContent\n// https://ai.google.dev/api/rest/v1/chats/sendMessage\n// https://googleapis.github.io/js-genai/release_docs/classes/models.Models.html#generatecontentstream\n// https://googleapis.github.io/js-genai/release_docs/classes/chats.Chat.html#sendmessagestream\n// https://ai.google.dev/api/decisions\nexport const GOOGLE_GENAI_METHOD_REGISTRY = {\n 'models.generateContent': { operation: 'generate_content' },\n 'models.generateContentStream': { operation: 'generate_content', streaming: true },\n 'models.embedContent': { operation: 'embeddings' },\n 'chats.create': { proxyResultPath: 'chat' },\n 'chat.sendMessage': { operation: 'chat' },\n 'chat.sendMessageStream': { operation: 'chat', streaming: true },\n 'decisions.create': { operation: 'decide' },\n} as const satisfies InstrumentedMethodRegistry;\n\n// Constants for internal use\nexport const GOOGLE_GENAI_SYSTEM_NAME = 'google_genai';\n","// Google's questions and answers already use Jev's layout, so only the evaluated input is mapped.\nimport { GEN_AI_OUTPUT_MESSAGES } from '@sentry/conventions/attributes';\nimport type { Span } from '@sentry/core';\nimport { isObjectLike } from '@sentry/core';\nimport { getEvaluationInputMessages, getEvaluationOutputMessages, getTokenUsageAttributes } from '../core/utils';\nimport type { GenAiMessage, GenAiMessagePart } from '../types';\n\n/**\n * Serialize a decisions request. Its evidence is `input` where Jev's is `state`; it is recorded as `state`\n * so both render the same.\n */\nexport function getDecisionInputMessages(params: Record<string, unknown>): string | undefined {\n return getEvaluationInputMessages({ state: toStateMessages(params.input), questions: params.questions });\n}\n\n/**\n * Multimodal evidence is one part or a list of parts, recorded as one user message so it renders like OpenAI's.\n * Inline media is reported by modality and media type only: its `data` is base64, which the conventions require\n * to be dropped.\n */\nfunction toStateMessages(input: unknown): unknown {\n if (typeof input === 'string') {\n return input;\n }\n\n const parts = (Array.isArray(input) ? input : [input]).filter(isObjectLike).map((part): GenAiMessagePart => {\n if (part.type === 'text') {\n return { type: 'text', content: part.text };\n }\n if (typeof part.uri === 'string') {\n return { type: 'uri', modality: part.type, mime_type: part.mime_type, uri: part.uri };\n }\n return { type: 'blob', modality: part.type, mime_type: part.mime_type };\n });\n return [{ role: 'user', parts } satisfies GenAiMessage];\n}\n\nexport function addDecisionResponseAttributes(span: Span, response: unknown, recordOutputs: boolean): void {\n if (!isObjectLike(response)) {\n return;\n }\n\n if (isObjectLike(response.usage)) {\n const usage = response.usage as Record<string, number | undefined>;\n span.setAttributes(\n getTokenUsageAttributes(\n usage.total_input_tokens,\n usage.total_output_tokens,\n undefined,\n usage.total_cached_tokens,\n usage.total_tokens,\n ),\n );\n }\n\n if (recordOutputs && response.answers !== undefined) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, getEvaluationOutputMessages(response.answers));\n }\n}\n","import { isObjectLike, stringify } from '@sentry/core';\nimport type { Span } from '@sentry/core';\nimport { GEN_AI_OUTPUT_MESSAGES } from '@sentry/conventions/attributes';\n\n// Copied from https://googleapis.github.io/js-genai/release_docs/index.html\nexport type ContentListUnion = Content | Content[] | PartListUnion;\nexport type ContentUnion = Content | PartUnion[] | PartUnion;\nexport type Content = {\n parts?: Part[];\n role?: string;\n};\nexport type PartUnion = Part | string;\nexport type Part = Record<string, unknown> & {\n inlineData?: {\n data?: string;\n displayName?: string;\n mimeType?: string;\n };\n text?: string;\n};\nexport type PartListUnion = PartUnion[] | PartUnion;\n\n/**\n * A message part as described in https://develop.sentry.dev/sdk/telemetry/traces/modules/ai-agents/.\n * Parts Sentry cannot type are dropped when the message is rendered, so Google's own `Part` shape\n * (`{ text }`, `{ functionCall }`, ...) has to be translated into this one.\n */\nexport type MessagePart = Record<string, unknown> & { type: string };\n\nexport type Message = {\n role: string;\n parts: MessagePart[];\n};\n\n// `gen_ai` roles are `user`, `assistant`, `tool` and `system`; Google only ever emits `user` or `model`.\nfunction normalizeRole(role: string): string {\n return role === 'model' ? 'assistant' : role;\n}\n\nfunction mimeTypeOf(value: Record<PropertyKey, unknown>): string | undefined {\n return typeof value.mimeType === 'string' ? value.mimeType : undefined;\n}\n\n/**\n * Binary payloads are reported by media type only: `inlineData.data` is base64 bytes, which the\n * conventions require to be dropped rather than recorded.\n */\nexport function partToMessagePart(part: unknown): MessagePart | undefined {\n if (typeof part === 'string') {\n return { type: 'text', content: part };\n }\n\n if (!isObjectLike(part)) {\n return undefined;\n }\n\n if (typeof part.text === 'string') {\n return { type: part.thought === true ? 'reasoning' : 'text', content: part.text };\n }\n\n const { functionCall, functionResponse, inlineData, fileData } = part;\n\n if (isObjectLike(functionCall)) {\n return {\n type: 'tool_call',\n id: functionCall.id,\n name: functionCall.name,\n arguments: stringify(functionCall.args ?? {}, String),\n };\n }\n\n if (isObjectLike(functionResponse)) {\n return {\n type: 'tool_call_response',\n id: functionResponse.id,\n name: functionResponse.name,\n result: stringify(functionResponse.response ?? {}, String),\n };\n }\n\n if (isObjectLike(inlineData)) {\n return { type: 'blob', mime_type: mimeTypeOf(inlineData) };\n }\n\n if (isObjectLike(fileData)) {\n return { type: 'uri', mime_type: mimeTypeOf(fileData), uri: fileData.fileUri };\n }\n\n // Part kinds we don't know yet render as JSON rather than disappearing.\n return { type: 'object', content: part };\n}\n\nfunction partsToMessageParts(parts: unknown): MessagePart[] {\n const list = Array.isArray(parts) ? parts : parts != null ? [parts] : [];\n return list.map(partToMessagePart).filter((part): part is MessagePart => part !== undefined);\n}\n\nfunction isContent(value: unknown): value is Content {\n return isObjectLike(value) && (typeof value.role === 'string' || Array.isArray(value.parts));\n}\n\nfunction contentToMessage(content: Content, role: string): Message {\n return {\n role: normalizeRole(typeof content.role === 'string' ? content.role : role),\n parts: partsToMessageParts(content.parts),\n };\n}\n\n/**\n * Bare parts are collected into one message rather than one message each: `[{ text }, { inlineData }]`\n * is a single multimodal turn in Google's API, not two turns.\n */\nexport function contentUnionToMessages(content: ContentListUnion, role = 'user'): Message[] {\n if (Array.isArray(content)) {\n const messages: Message[] = [];\n let looseParts: MessagePart[] = [];\n\n const flushLooseParts = (): void => {\n if (looseParts.length) {\n messages.push({ role: normalizeRole(role), parts: looseParts });\n looseParts = [];\n }\n };\n\n for (const item of content) {\n if (isContent(item)) {\n flushLooseParts();\n const message = contentToMessage(item, role);\n if (message.parts.length) {\n messages.push(message);\n }\n } else {\n const part = partToMessagePart(item);\n if (part) {\n looseParts.push(part);\n }\n }\n }\n\n flushLooseParts();\n return messages;\n }\n\n if (isContent(content)) {\n const message = contentToMessage(content, role);\n return message.parts.length ? [message] : [];\n }\n\n const part = partToMessagePart(content);\n return part ? [{ role: normalizeRole(role), parts: [part] }] : [];\n}\n\n/** Collect the message parts of every candidate in a response. */\nexport function candidatesToMessageParts(candidates: unknown): MessagePart[] {\n if (!Array.isArray(candidates)) {\n return [];\n }\n\n return candidates.flatMap(candidate =>\n isObjectLike(candidate) && isObjectLike(candidate.content)\n ? partsToMessageParts(candidate.content.parts as PartListUnion | undefined)\n : [],\n );\n}\n\n/**\n * A streamed response delivers its text a few characters at a time, so the parts collected across\n * chunks would otherwise be hundreds of one-word fragments.\n */\nfunction mergeAdjacentTextParts(parts: MessagePart[]): MessagePart[] {\n const merged: MessagePart[] = [];\n\n for (const part of parts) {\n const previous = merged[merged.length - 1];\n const mergeable = part.type === 'text' || part.type === 'reasoning';\n\n if (mergeable && previous?.type === part.type && typeof previous.content === 'string') {\n previous.content += typeof part.content === 'string' ? part.content : '';\n } else {\n merged.push({ ...part });\n }\n }\n\n return merged;\n}\n\n/**\n * Set alongside the deprecated `gen_ai.response.text` / `gen_ai.response.tool_calls`: Relay migrates\n * those into `gen_ai.output.messages`, but the tool-calls half of that migration is lossy, so a turn\n * that only calls a tool would otherwise render an empty Output.\n */\nexport function setOutputMessagesAttribute(span: Span, parts: MessagePart[]): void {\n const merged = mergeAdjacentTextParts(parts);\n if (merged.length) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, JSON.stringify([{ role: 'assistant', parts: merged }]));\n }\n}\n\n/** Flatten a `ContentUnion` instruction into the plain text `gen_ai.system_instructions` expects. */\nexport function systemInstructionToText(systemInstruction: unknown): string | undefined {\n const texts = contentUnionToMessages(systemInstruction as ContentUnion, 'system')\n .flatMap(message => message.parts)\n .map(part => (part.type === 'text' && typeof part.content === 'string' ? part.content : ''))\n .filter(text => text.length > 0);\n\n return texts.length ? texts.join('\\n') : undefined;\n}\n","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 { GoogleGenAIResponse } from './types';\nimport type { MessagePart } from './utils';\nimport { candidatesToMessageParts, setOutputMessagesAttribute } from './utils';\n\n/**\n * State object used to accumulate information from a stream of Google GenAI 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 prompt/input tokens used. Tool-use prompt tokens are added when the stream ends. */\n promptTokens?: number;\n toolUsePromptTokens?: number;\n /** Number of completion/output tokens used. */\n completionTokens?: number;\n candidateTokens?: number;\n reasoningOutputTokens?: number;\n /** Number of total tokens used. */\n totalTokens?: number;\n cacheReadInputTokens?: number;\n /** Accumulated tool calls (finalized) */\n toolCalls: Array<Record<string, unknown>>;\n /** Accumulated output message parts (for output recording). */\n outputParts: MessagePart[];\n}\n\n/**\n * Checks if a response chunk contains an error\n * @param chunk - The response chunk to check\n * @param span - The span to update if error is found\n * @returns Whether an error occurred\n */\nfunction isErrorChunk(chunk: GoogleGenAIResponse, span: Span): boolean {\n const feedback = chunk?.promptFeedback;\n if (feedback?.blockReason) {\n const message = feedback.blockReasonMessage ?? feedback.blockReason;\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n captureException(`Content blocked: ${message}`, {\n mechanism: { handled: false, type: 'auto.ai.google_genai' },\n });\n return true;\n }\n return false;\n}\n\n/**\n * Processes response metadata from a chunk\n * @param chunk - The response chunk to process\n * @param state - The state of the streaming process\n */\nfunction handleResponseMetadata(chunk: GoogleGenAIResponse, state: StreamingState): void {\n if (typeof chunk.responseId === 'string') state.responseId = chunk.responseId;\n if (typeof chunk.modelVersion === 'string') state.responseModel = chunk.modelVersion;\n\n const usage = chunk.usageMetadata;\n if (usage) {\n if (typeof usage.promptTokenCount === 'number') state.promptTokens = usage.promptTokenCount;\n if (typeof usage.toolUsePromptTokenCount === 'number') state.toolUsePromptTokens = usage.toolUsePromptTokenCount;\n if (typeof usage.candidatesTokenCount === 'number') state.candidateTokens = usage.candidatesTokenCount;\n if (typeof usage.thoughtsTokenCount === 'number') state.reasoningOutputTokens = usage.thoughtsTokenCount;\n if (state.candidateTokens !== undefined || state.reasoningOutputTokens !== undefined) {\n state.completionTokens = (state.candidateTokens ?? 0) + (state.reasoningOutputTokens ?? 0);\n }\n if (typeof usage.totalTokenCount === 'number') state.totalTokens = usage.totalTokenCount;\n if (typeof usage.cachedContentTokenCount === 'number') state.cacheReadInputTokens = usage.cachedContentTokenCount;\n }\n}\n\n/**\n * Processes candidate content from a response chunk\n * @param chunk - The response chunk to process\n * @param state - The state of the streaming process\n * @param recordOutputs - Whether to record outputs\n */\nfunction handleCandidateContent(chunk: GoogleGenAIResponse, state: StreamingState, recordOutputs: boolean): void {\n // The SDK getter already extracts function calls from candidate parts.\n if (Array.isArray(chunk.functionCalls)) {\n state.toolCalls.push(...chunk.functionCalls);\n }\n\n if (recordOutputs) {\n state.outputParts.push(...candidatesToMessageParts(chunk.candidates));\n }\n\n for (const candidate of chunk.candidates ?? []) {\n if (candidate?.finishReason && !state.finishReasons.includes(candidate.finishReason)) {\n state.finishReasons.push(candidate.finishReason);\n }\n\n for (const part of candidate?.content?.parts ?? []) {\n if (recordOutputs && part.text) state.responseTexts.push(part.text);\n }\n }\n}\n\n/**\n * Processes a single chunk from the Google GenAI stream\n * @param chunk - The chunk 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 processChunk(chunk: GoogleGenAIResponse, state: StreamingState, recordOutputs: boolean, span: Span): void {\n if (!chunk || isErrorChunk(chunk, span)) return;\n recordTimeToFirstChunk(span);\n handleResponseMetadata(chunk, state);\n handleCandidateContent(chunk, state, recordOutputs);\n}\n\n/**\n * Instruments an async iterable stream of Google GenAI response chunks, updates the span with\n * streaming attributes and (optionally) the aggregated output text, and yields\n * each chunk from the input stream unchanged.\n */\nexport async function* instrumentStream(\n stream: AsyncIterable<GoogleGenAIResponse>,\n span: Span,\n recordOutputs: boolean,\n abortSignal?: AbortSignal,\n beforeSpanEnd?: (result: GenAiSpanResult<never>) => void,\n): AsyncGenerator<GoogleGenAIResponse, void, unknown> {\n const state: StreamingState = {\n responseTexts: [],\n finishReasons: [],\n toolCalls: [],\n outputParts: [],\n };\n const result: GenAiSpanResult<never> = {};\n\n try {\n for await (const chunk of stream) {\n processChunk(chunk, state, recordOutputs, span);\n yield chunk;\n }\n } catch (error) {\n span.setStatus(getErrorStatus(abortSignal));\n result.error = error;\n throw error;\n } finally {\n if (recordOutputs) {\n setOutputMessagesAttribute(span, state.outputParts);\n }\n if (typeof state.promptTokens === 'number') state.promptTokens += state.toolUsePromptTokens ?? 0;\n endStreamSpan(span, state, recordOutputs, () => beforeSpanEnd?.(result));\n }\n}\n","/* eslint-disable typescript-eslint/no-deprecated */\n/* eslint-disable max-lines */\nimport {\n getClient,\n handleCallbackErrors,\n hasSpanStreamingEnabled,\n startSpan,\n startSpanManual,\n stringify,\n} from '@sentry/core';\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_INPUT_MESSAGES,\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_PRESENCE_PENALTY,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_REQUEST_TOP_K,\n GEN_AI_REQUEST_TOP_P,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_TOOL_DEFINITIONS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { InstrumentedMethodEntry } from '../core/utils';\nimport {\n buildMethodPath,\n getErrorStatus,\n getGenAiSpanOp,\n getRequestSignal,\n getTokenUsageAttributes,\n resolveGenAiCallRecording,\n} from '../core/utils';\nimport { GOOGLE_GENAI_METHOD_REGISTRY, GOOGLE_GENAI_SYSTEM_NAME } from './constants';\nimport { addDecisionResponseAttributes, getDecisionInputMessages } from './decisions';\nimport { instrumentStream } from './streaming';\nimport type { Candidate, ContentPart, GoogleGenAICallInfo, GoogleGenAIOptions, GoogleGenAIResponse } from './types';\nimport type { ContentListUnion, Message, PartListUnion } from './utils';\nimport {\n candidatesToMessageParts,\n contentUnionToMessages,\n setOutputMessagesAttribute,\n systemInstructionToText,\n} from './utils';\n\n/**\n * Extract model from parameters or chat context object\n * For chat instances, the model is available on the chat object as 'model' (older versions) or 'modelVersion' (newer versions)\n */\nexport function extractModel(params: Record<string, unknown>, context?: unknown): string {\n if ('model' in params && typeof params.model === 'string') {\n return params.model;\n }\n\n // Try to get model from chat context object (chat instance has model property)\n if (context && typeof context === 'object') {\n const contextObj = context as Record<string, unknown>;\n\n // Check for 'model' property (older versions, and streaming)\n if ('model' in contextObj && typeof contextObj.model === 'string') {\n return contextObj.model;\n }\n\n // Check for 'modelVersion' property (newer versions)\n if ('modelVersion' in contextObj && typeof contextObj.modelVersion === 'string') {\n return contextObj.modelVersion;\n }\n }\n\n return 'unknown';\n}\n\n/**\n * Extract generation config parameters\n */\nfunction extractConfigAttributes(config: Record<string, unknown>): Record<string, SpanAttributeValue> {\n const attributes: Record<string, SpanAttributeValue> = {};\n\n if ('temperature' in config && typeof config.temperature === 'number') {\n attributes[GEN_AI_REQUEST_TEMPERATURE] = config.temperature;\n }\n if ('topP' in config && typeof config.topP === 'number') {\n attributes[GEN_AI_REQUEST_TOP_P] = config.topP;\n }\n if ('topK' in config && typeof config.topK === 'number') {\n attributes[GEN_AI_REQUEST_TOP_K] = config.topK;\n }\n if ('maxOutputTokens' in config && typeof config.maxOutputTokens === 'number') {\n attributes[GEN_AI_REQUEST_MAX_TOKENS] = config.maxOutputTokens;\n }\n if ('frequencyPenalty' in config && typeof config.frequencyPenalty === 'number') {\n attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY] = config.frequencyPenalty;\n }\n if ('presencePenalty' in config && typeof config.presencePenalty === 'number') {\n attributes[GEN_AI_REQUEST_PRESENCE_PENALTY] = config.presencePenalty;\n }\n\n return attributes;\n}\n\n/**\n * Extract request attributes from method arguments\n * Builds the base attributes for span creation including system info, model, and config\n */\nexport function extractRequestAttributes(\n operationName: string,\n params?: Record<string, unknown>,\n context?: unknown,\n recordInputs = true,\n): Record<string, SpanAttributeValue> {\n const attributes: Record<string, SpanAttributeValue> = {\n [GEN_AI_PROVIDER_NAME]: GOOGLE_GENAI_SYSTEM_NAME,\n [GEN_AI_OPERATION_NAME]: operationName,\n [SENTRY_ORIGIN]: 'auto.ai.google_genai',\n };\n\n if (params) {\n attributes[GEN_AI_REQUEST_MODEL] = extractModel(params, context);\n\n // Extract generation config parameters\n if ('config' in params && typeof params.config === 'object' && params.config) {\n const config = params.config as Record<string, unknown>;\n Object.assign(attributes, extractConfigAttributes(config));\n\n // Extract available tools from config\n if (recordInputs && 'tools' in config && Array.isArray(config.tools)) {\n const functionDeclarations = config.tools.flatMap(\n (tool: { functionDeclarations: unknown[] }) => tool.functionDeclarations,\n );\n attributes[GEN_AI_TOOL_DEFINITIONS] = JSON.stringify(functionDeclarations);\n }\n }\n\n const decisionInput = recordInputs && operationName === 'decide' ? getDecisionInputMessages(params) : undefined;\n if (decisionInput) {\n attributes[GEN_AI_INPUT_MESSAGES] = decisionInput;\n }\n } else {\n attributes[GEN_AI_REQUEST_MODEL] = extractModel({}, context);\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 * Handles different parameter formats for different Google GenAI methods.\n */\nexport function addPrivateRequestAttributes(span: Span, params: Record<string, unknown>, operationName: string): void {\n if (operationName === 'embeddings') {\n const contents = params.contents;\n if (contents != null) {\n span.setAttribute(GEN_AI_EMBEDDINGS_INPUT, stringify(contents, String));\n }\n return;\n }\n\n // config.systemInstruction: ContentUnion. It has its own attribute, so it never joins the message list.\n if (\n 'config' in params &&\n params.config &&\n typeof params.config === 'object' &&\n 'systemInstruction' in params.config &&\n params.config.systemInstruction\n ) {\n const systemInstructions = systemInstructionToText(params.config.systemInstruction);\n if (systemInstructions) {\n span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS, JSON.stringify([{ type: 'text', content: systemInstructions }]));\n }\n }\n\n const messages: Message[] = [];\n\n // For chats.create: history contains the conversation history\n if ('history' in params) {\n messages.push(...contentUnionToMessages(params.history as PartListUnion, 'user'));\n }\n\n // For models.generateContent: ContentListUnion\n if ('contents' in params) {\n messages.push(...contentUnionToMessages(params.contents as ContentListUnion, 'user'));\n }\n\n // For chat.sendMessage: message can be PartListUnion\n if ('message' in params) {\n messages.push(...contentUnionToMessages(params.message as PartListUnion, 'user'));\n }\n\n if (messages.length) {\n span.setAttributes({\n [GEN_AI_INPUT_MESSAGES]: stringify(messages),\n });\n }\n}\n\n/**\n * Add response attributes from the Google GenAI response\n * @see https://github.com/googleapis/js-genai/blob/v1.19.0/src/types.ts#L2313\n */\nexport function addResponseAttributes(\n span: Span,\n response: GoogleGenAIResponse,\n recordOutputs?: boolean,\n operationName?: string,\n): void {\n if (!response || typeof response !== 'object') return;\n\n if (operationName === 'decide') {\n addDecisionResponseAttributes(span, response, !!recordOutputs);\n return;\n }\n\n if (response.modelVersion) {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, response.modelVersion);\n }\n\n // Add usage metadata if present\n if (response.usageMetadata && typeof response.usageMetadata === 'object') {\n const usage = response.usageMetadata;\n const hasOutput = typeof usage.candidatesTokenCount === 'number' || typeof usage.thoughtsTokenCount === 'number';\n span.setAttributes(\n getTokenUsageAttributes(\n typeof usage.promptTokenCount === 'number'\n ? usage.promptTokenCount + (usage.toolUsePromptTokenCount ?? 0)\n : undefined,\n hasOutput ? (usage.candidatesTokenCount ?? 0) + (usage.thoughtsTokenCount ?? 0) : undefined,\n undefined,\n usage.cachedContentTokenCount,\n usage.totalTokenCount,\n ),\n );\n if (typeof usage.thoughtsTokenCount === 'number') {\n span.setAttribute(GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, usage.thoughtsTokenCount);\n }\n }\n\n if (recordOutputs) {\n setOutputMessagesAttribute(span, candidatesToMessageParts(response.candidates));\n }\n\n // Add response text if recordOutputs is enabled\n if (recordOutputs && Array.isArray(response.candidates) && response.candidates.length > 0) {\n const responseTexts = response.candidates\n .map((candidate: Candidate) => {\n if (candidate.content?.parts && Array.isArray(candidate.content.parts)) {\n return candidate.content.parts\n .map((part: ContentPart) => (typeof part.text === 'string' ? part.text : ''))\n .filter((text: string) => text.length > 0)\n .join('');\n }\n return '';\n })\n .filter((text: string) => text.length > 0);\n\n if (responseTexts.length > 0) {\n span.setAttributes({\n [GEN_AI_RESPONSE_TEXT]: responseTexts.join(''),\n });\n }\n }\n\n // Add tool calls if recordOutputs is enabled\n if (recordOutputs && response.functionCalls) {\n const functionCalls = response.functionCalls;\n if (Array.isArray(functionCalls) && functionCalls.length > 0) {\n span.setAttributes({\n [GEN_AI_RESPONSE_TOOL_CALLS]: JSON.stringify(functionCalls),\n });\n }\n }\n}\n\n/**\n * Recover the config a chat message sends but does not carry in its own arguments.\n *\n * `chats.create()` takes a config that `@google/genai` reuses for every message, resolving each\n * request as `params.config ?? chat.config`. A per-message config therefore replaces the chat\n * config rather than merging into it, and the chat config applies only when the message omits one.\n * That config lives on the chat instance, which both instrumentation paths already hold: the client\n * proxy passes it as the method's `context`, the diagnostics-channel path as `data.self`.\n *\n * The chat `history` stays off the message spans. The SDK does send it, folded into `contents`, and\n * the instance carries the whole transcript, but repeating every past turn on every message span\n * duplicates what earlier spans already reported and grows without bound.\n */\nexport function resolveChatParams(\n operationName: string,\n params: Record<string, unknown> | undefined,\n context: unknown,\n): Record<string, unknown> | undefined {\n // `!= null` mirrors the SDK's `??`: an explicit `null` config falls back to the chat's.\n if (operationName !== 'chat' || params?.config != null || !context || typeof context !== 'object') {\n return params;\n }\n\n const chatConfig = (context as Record<string, unknown>).config;\n if (!chatConfig || typeof chatConfig !== 'object') {\n return params;\n }\n\n return { ...params, config: chatConfig };\n}\n\n/**\n * Reads the caller's `config.abortSignal` from params resolved by `resolveChatParams`.\n */\nexport function getAbortSignal(params: Record<string, unknown> | undefined): AbortSignal | undefined {\n return (params?.config as { abortSignal?: AbortSignal } | undefined)?.abortSignal;\n}\n\n/** `decisions.create` takes its abort signal in its request options, not in a `config`. */\nexport function getCallAbortSignal(\n operationName: string,\n params: Record<string, unknown> | undefined,\n requestOptions: unknown,\n): AbortSignal | undefined {\n return operationName === 'decide' ? getRequestSignal(requestOptions) : getAbortSignal(params);\n}\n\n/**\n * Instrument any async or synchronous genai method with Sentry spans\n * Handles operations like models.generateContent and chat.sendMessage and chats.create\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: GoogleGenAIOptions,\n): (...args: T) => R | Promise<R> {\n const isEmbeddings = instrumentedMethod.operation === 'embeddings';\n\n return new Proxy(originalMethod, {\n apply(target, _, args: T): R | Promise<R> {\n const operationName = instrumentedMethod.operation || 'unknown';\n const params = args[0] as Record<string, unknown> | undefined;\n const call: GoogleGenAICallInfo = { operation: operationName, request: params };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n const attributeParams = resolveChatParams(operationName, params, context);\n const abortSignal = getCallAbortSignal(operationName, attributeParams, args[1]);\n const requestAttributes = extractRequestAttributes(operationName, attributeParams, context, recordInputs);\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 spanName =\n (typeof model === 'string' && model !== 'unknown') || !(client && hasSpanStreamingEnabled(client))\n ? `${operationName} ${model}`\n : operationName;\n\n // Check if this is a streaming method\n if (instrumentedMethod.streaming) {\n // Use startSpanManual for streaming methods to control span lifecycle\n return startSpanManual(\n {\n name: spanName,\n op: getGenAiSpanOp(operationName),\n attributes: requestAttributes,\n },\n async (span: Span) => {\n try {\n if (recordInputs && attributeParams) {\n addPrivateRequestAttributes(span, attributeParams, operationName);\n }\n runGenAiSpanStart(options, span, call);\n const stream = await target.apply(context, args);\n return instrumentStream(stream, span, recordOutputs, abortSignal, result =>\n runGenAiSpanEnd(options, span, call, result),\n ) as R;\n } catch (error) {\n span.setStatus(getErrorStatus(abortSignal));\n runGenAiSpanEnd(options, span, call, { error });\n span.end();\n throw error;\n }\n },\n );\n }\n // Single span for both sync and async operations\n return startSpan(\n {\n name: spanName,\n op: getGenAiSpanOp(operationName),\n attributes: requestAttributes,\n },\n (span: Span) => {\n if (recordInputs && attributeParams) {\n addPrivateRequestAttributes(span, attributeParams, operationName);\n }\n runGenAiSpanStart(options, span, call);\n\n // The rejection is rethrown to the caller. `startSpan` keeps the status set here.\n return handleCallbackErrors(\n () => target.apply(context, args),\n error => {\n span.setStatus(getErrorStatus(abortSignal));\n runGenAiSpanEnd(options, span, call, { error });\n },\n () => {},\n result => {\n // Only add response attributes for content-producing methods, not for embeddings\n if (!isEmbeddings) {\n addResponseAttributes(span, result, recordOutputs, operationName);\n }\n runGenAiSpanEnd(options, span, call, { response: result });\n },\n );\n },\n );\n },\n });\n}\n\n/**\n * Create a deep proxy for Google GenAI client instrumentation\n * Recursively instruments methods and handles special cases like chats.create\n */\nfunction createDeepProxy<T extends object>(target: T, currentPath = '', options: GoogleGenAIOptions): T {\n const propertyCache = new Map<PropertyKey, { original: unknown; wrapped: unknown }>();\n\n return new Proxy(target, {\n get: (t, prop, receiver) => {\n const value = Reflect.get(t, prop, receiver);\n const cachedEntry = propertyCache.get(prop);\n if (cachedEntry) {\n if (cachedEntry.original === value) {\n return cachedEntry.wrapped;\n }\n propertyCache.delete(prop);\n }\n\n const methodPath = buildMethodPath(currentPath, String(prop));\n\n const instrumentedMethod: InstrumentedMethodEntry | undefined =\n GOOGLE_GENAI_METHOD_REGISTRY[methodPath as keyof typeof GOOGLE_GENAI_METHOD_REGISTRY];\n if (typeof value === 'function' && instrumentedMethod) {\n // If an operation is specified, we need to instrument the method itself\n const wrappedMethod = instrumentedMethod.operation\n ? instrumentMethod(value as (...args: unknown[]) => unknown, methodPath, instrumentedMethod, t, options)\n : value.bind(t);\n\n if (!instrumentedMethod.proxyResultPath) {\n propertyCache.set(prop, { original: value, wrapped: wrappedMethod });\n return wrappedMethod;\n }\n\n // If a proxyResultPath is specified, we need to proxy the result of the method.\n // Note: This currently only properly handles synchronous methods. For async methods,\n // the Promise itself would be proxied instead of the resolved value. Currently we\n // don't have a case where this is needed, so I'll keep it simple for now.\n const methodWithProxiedResult = function (...args: unknown[]): unknown {\n const result = wrappedMethod(...args);\n if (result && typeof result === 'object') {\n return createDeepProxy(result as object, instrumentedMethod.proxyResultPath, options);\n }\n return result;\n };\n propertyCache.set(prop, { original: value, wrapped: methodWithProxiedResult });\n return methodWithProxiedResult;\n }\n\n if (typeof value === 'function') {\n // Bind non-instrumented functions to preserve the original `this` context\n const boundMethod = value.bind(t);\n propertyCache.set(prop, { original: value, wrapped: boundMethod });\n return boundMethod;\n }\n\n if (value && typeof value === 'object') {\n const nestedProxy = createDeepProxy(value, methodPath, options);\n propertyCache.set(prop, { original: value, wrapped: nestedProxy });\n return nestedProxy;\n }\n\n return value;\n },\n });\n}\n\n/**\n * Instrument a Google GenAI 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 client object\n * @param client - The Google GenAI 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 *\n * @example\n * ```typescript\n * import { GoogleGenAI } from '@google/genai';\n * import { instrumentGoogleGenAIClient } from '@sentry/node';\n *\n * const genAI = new GoogleGenAI({ apiKey: process.env.GOOGLE_GENAI_API_KEY });\n * const instrumentedClient = instrumentGoogleGenAIClient(genAI);\n *\n * // Now both chats.create and sendMessage will be instrumented\n * const chat = instrumentedClient.chats.create({ model: 'gemini-1.5-pro' });\n * const response = await chat.sendMessage({ message: 'Hello' });\n * ```\n */\nexport function instrumentGoogleGenAIClient<T extends object>(client: T, options?: GoogleGenAIOptions): T {\n return createDeepProxy(client, '', options ?? {});\n}\n","import type { InstrumentedMethodRegistry } from '../core/utils';\n\nexport const MISTRAL_INTEGRATION_NAME = 'Mistral' as const;\n\n// Matches the value `inferSystemFromInstance` reports for `@langchain/mistralai`, so a call recorded\n// through LangChain and a call recorded here carry the same provider.\nexport const MISTRAL_PROVIDER_NAME = 'mistralai' as const;\n\nexport const MISTRAL_ORIGIN = 'auto.ai.mistralai' as const;\n\n// https://docs.mistral.ai/api/\n// `*.stream` methods are intrinsically streaming (no `stream: true` param), so they are flagged here.\n// `parse`/`parseStream` are the structured-output entry points; they call the underlying request\n// functions directly rather than `this.complete`/`this.stream`, so they need their own entries and\n// cannot produce a duplicate span.\nexport const MISTRAL_METHOD_REGISTRY = {\n 'chat.complete': { operation: 'chat' },\n 'chat.stream': { operation: 'chat', streaming: true },\n 'chat.parse': { operation: 'chat' },\n 'chat.parseStream': { operation: 'chat', streaming: true },\n 'embeddings.create': { operation: 'embeddings' },\n 'agents.complete': { operation: 'invoke_agent' },\n 'agents.stream': { operation: 'invoke_agent', streaming: true },\n} as const satisfies InstrumentedMethodRegistry;\n","/* eslint-disable typescript-eslint/no-deprecated */\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport type { GenAiOutputMessage } from '../core/utils';\nimport { setOutputMessagesAttribute } from '../core/utils';\nimport {\n GEN_AI_REQUEST_FREQUENCY_PENALTY,\n GEN_AI_REQUEST_MAX_TOKENS,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_REQUEST_PRESENCE_PENALTY,\n GEN_AI_REQUEST_SEED,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_REQUEST_TOP_P,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n} from '@sentry/conventions/attributes';\n\n/**\n * Turn a Mistral message content (string or content-chunk array) into a plain string.\n */\nexport function contentToString(content: unknown): string {\n if (typeof content === 'string') {\n return content;\n }\n if (Array.isArray(content)) {\n return content\n .map(part =>\n part && typeof part === 'object' && typeof (part as { text?: unknown }).text === 'string'\n ? (part as { text: string }).text\n : '',\n )\n .join('');\n }\n return '';\n}\n\n/**\n * Build the span name for an instrumented Mistral call. Agent ids and a missing model are left out\n * to keep the name low cardinality.\n */\nexport function getSpanName(operationName: string, attributes: Record<string, unknown>): string {\n const model = attributes[GEN_AI_REQUEST_MODEL];\n\n if (operationName === 'invoke_agent' || typeof model !== 'string') {\n return operationName;\n }\n\n return `${operationName} ${model}`;\n}\n\n/**\n * Reads the caller's signal from Mistral's request options. The SDK spreads `options` over\n * `options.fetchOptions`, so a top-level `signal` wins.\n */\nexport function getMistralRequestSignal(requestOptions: unknown): AbortSignal | undefined {\n const options = requestOptions as { signal?: AbortSignal; fetchOptions?: { signal?: AbortSignal } } | undefined;\n return options?.signal ?? options?.fetchOptions?.signal;\n}\n\n/**\n * Extract request parameters. Mistral request fields are camelCase.\n */\nexport function extractRequestParameters(params: Record<string, unknown>): Record<string, unknown> {\n const attributes: Record<string, unknown> = {};\n\n if (params.model != null) attributes[GEN_AI_REQUEST_MODEL] = params.model;\n if ('temperature' in params) attributes[GEN_AI_REQUEST_TEMPERATURE] = params.temperature;\n if ('topP' in params) attributes[GEN_AI_REQUEST_TOP_P] = params.topP;\n if ('maxTokens' in params) attributes[GEN_AI_REQUEST_MAX_TOKENS] = params.maxTokens;\n if ('frequencyPenalty' in params) attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY] = params.frequencyPenalty;\n if ('presencePenalty' in params) attributes[GEN_AI_REQUEST_PRESENCE_PENALTY] = params.presencePenalty;\n if ('randomSeed' in params) attributes[GEN_AI_REQUEST_SEED] = params.randomSeed;\n\n return attributes;\n}\n\n/**\n * Add response attributes to a span using duck-typing. Mistral responses are camelCase\n * (`choices[].message`, `usage.promptTokens`), matching the SDK's deserialized objects.\n */\nexport function addResponseAttributes(span: Span, result: unknown, recordOutputs?: boolean): void {\n if (!result || typeof result !== 'object') return;\n\n const response = result as Record<string, unknown>;\n const attrs: Record<string, SpanAttributeValue> = {};\n\n if (typeof response.id === 'string') {\n attrs[GEN_AI_RESPONSE_ID] = response.id;\n }\n\n if (typeof response.model === 'string') {\n attrs[GEN_AI_RESPONSE_MODEL] = response.model;\n }\n\n if (response.usage && typeof response.usage === 'object') {\n const usage = response.usage as Record<string, unknown>;\n if (typeof usage.promptTokens === 'number') attrs[GEN_AI_USAGE_INPUT_TOKENS] = usage.promptTokens;\n if (typeof usage.completionTokens === 'number') attrs[GEN_AI_USAGE_OUTPUT_TOKENS] = usage.completionTokens;\n if (typeof usage.totalTokens === 'number') attrs[GEN_AI_USAGE_TOTAL_TOKENS] = usage.totalTokens;\n }\n\n let outputMessages: GenAiOutputMessage[] = [];\n\n if (Array.isArray(response.choices)) {\n const choices = response.choices as Array<Record<string, unknown>>;\n\n const finishReasons = choices\n .map(choice => choice.finishReason)\n .filter((reason): reason is string => typeof reason === 'string');\n if (finishReasons.length > 0) {\n attrs[GEN_AI_RESPONSE_FINISH_REASONS] = JSON.stringify(finishReasons);\n }\n\n if (recordOutputs) {\n // One entry per choice: Mistral can return several when `n` > 1, and both attributes are\n // specified as arrays of messages rather than one merged blob.\n outputMessages = choices.map(choice => {\n const message = choice.message as Record<string, unknown> | undefined;\n return {\n responseText: contentToString(message?.content),\n toolCalls: Array.isArray(message?.toolCalls) ? message.toolCalls : undefined,\n finishReason: typeof choice.finishReason === 'string' ? choice.finishReason : undefined,\n };\n });\n\n const responseTexts = outputMessages.map(message => message.responseText).filter(Boolean);\n if (responseTexts.length > 0) {\n attrs[GEN_AI_RESPONSE_TEXT] = JSON.stringify(responseTexts);\n }\n\n const toolCalls = outputMessages.flatMap(message => message.toolCalls ?? []);\n if (toolCalls.length > 0) {\n attrs[GEN_AI_RESPONSE_TOOL_CALLS] = JSON.stringify(toolCalls);\n }\n }\n }\n\n span.setAttributes(attrs);\n\n if (recordOutputs) {\n setOutputMessagesAttribute(span, outputMessages);\n }\n}\n","import type { Span } from '@sentry/core';\nimport type { GenAiSpanResult } from '../core/span-hooks';\nimport { endStreamSpan, getErrorStatus, setOutputMessagesAttribute } from '../core/utils';\nimport { recordTimeToFirstChunk } from '../core/time-to-first-chunk';\nimport type { MistralCompletionChunk, MistralToolCall } from './types';\nimport { contentToString } from './utils';\n\n/**\n * State accumulated while consuming a Mistral event stream.\n */\ninterface StreamingState {\n responseTexts: string[];\n finishReasons: string[];\n responseId: string;\n responseModel: string;\n promptTokens: number | undefined;\n completionTokens: number | undefined;\n totalTokens: number | undefined;\n /** Tool calls accumulated by their delta `index`; `function.arguments` arrives fragmented. */\n toolCalls: Record<number, MistralToolCall>;\n}\n\n/** Which drain path owns accumulation. See {@link instrumentEventStream}. */\ntype StreamConsumer = 'iterator' | 'reader';\n\ntype AsyncIterableStream = { [Symbol.asyncIterator]: () => AsyncIterator<unknown> };\n\ninterface StreamReaderLike {\n read: () => Promise<{ done: boolean; value?: unknown }>;\n cancel?: (reason?: unknown) => Promise<unknown>;\n}\n\ninterface ReadableStreamLike {\n getReader?: (...args: unknown[]) => StreamReaderLike;\n cancel?: (reason?: unknown) => Promise<unknown>;\n tee?: () => unknown;\n pipeTo?: (destination: unknown, options?: unknown) => Promise<unknown>;\n pipeThrough?: (transform: unknown, options?: unknown) => unknown;\n}\n\n/** Whether a value can be drained with `for await`. */\nexport function isAsyncIterable(value: unknown): value is AsyncIterableStream {\n return !!value && typeof (value as AsyncIterableStream)[Symbol.asyncIterator] === 'function';\n}\n\nfunction createStreamingState(): StreamingState {\n return {\n responseTexts: [],\n finishReasons: [],\n responseId: '',\n responseModel: '',\n promptTokens: undefined,\n completionTokens: undefined,\n totalTokens: undefined,\n toolCalls: {},\n };\n}\n\nfunction processToolCalls(toolCalls: MistralToolCall[], state: StreamingState): void {\n for (const toolCall of toolCalls) {\n const index = toolCall.index;\n if (index === undefined || !toolCall.function) {\n continue;\n }\n\n const existing = state.toolCalls[index];\n if (!existing) {\n state.toolCalls[index] = {\n ...toolCall,\n function: { name: toolCall.function.name, arguments: toolCall.function.arguments ?? '' },\n };\n } else if (toolCall.function.arguments && existing.function) {\n existing.function.arguments = `${existing.function.arguments}${toolCall.function.arguments}`;\n }\n }\n}\n\nfunction processChunk(chunk: MistralCompletionChunk, state: StreamingState, recordOutputs: boolean): void {\n state.responseId = chunk.id ?? state.responseId;\n state.responseModel = chunk.model ?? state.responseModel;\n\n if (chunk.usage) {\n // Input tokens stay constant across the stream; output tokens are only finalized in the last\n // event, so we overwrite on every event that carries usage to guarantee the totals are set.\n state.promptTokens = chunk.usage.promptTokens;\n state.completionTokens = chunk.usage.completionTokens;\n state.totalTokens = chunk.usage.totalTokens;\n }\n\n for (const choice of chunk.choices ?? []) {\n if (recordOutputs) {\n // Deltas carry either a plain string or the same content-chunk array the non-streaming\n // responses use, so both go through `contentToString`.\n const content = contentToString(choice.delta?.content);\n if (content) {\n state.responseTexts.push(content);\n }\n if (choice.delta?.toolCalls) {\n processToolCalls(choice.delta.toolCalls, state);\n }\n }\n if (choice.finishReason) {\n state.finishReasons.push(choice.finishReason);\n }\n }\n}\n\n/** Mistral yields `CompletionEvent` objects that wrap the chunk under `data`. */\nfunction processEvent(event: unknown, state: StreamingState, recordOutputs: boolean): void {\n const chunk = (event as { data?: MistralCompletionChunk } | undefined)?.data;\n if (chunk && typeof chunk === 'object') {\n processChunk(chunk, state, recordOutputs);\n }\n}\n\nasync function* instrumentIterator(\n iterate: () => AsyncIterator<unknown>,\n state: StreamingState,\n recordOutputs: boolean,\n claim: (consumer: StreamConsumer) => boolean,\n settle: (error?: unknown) => void,\n): AsyncGenerator<unknown, void, unknown> {\n try {\n for await (const event of { [Symbol.asyncIterator]: iterate }) {\n if (claim('iterator')) {\n processEvent(event, state, recordOutputs);\n }\n yield event;\n }\n } catch (error) {\n settle(error);\n throw error;\n } finally {\n settle();\n }\n}\n\nfunction wrapReader(\n reader: StreamReaderLike,\n state: StreamingState,\n recordOutputs: boolean,\n claim: (consumer: StreamConsumer) => boolean,\n settle: (error?: unknown) => void,\n markCancelled: () => void,\n): StreamReaderLike {\n // Captured before the proxy exists so the wrappers below call the real reader, not themselves.\n const originalRead = reader.read;\n const originalCancel = reader.cancel;\n const read = (): Promise<{ done: boolean; value?: unknown }> => originalRead.call(reader);\n const cancel =\n typeof originalCancel === 'function'\n ? (reason?: unknown): Promise<unknown> => originalCancel.call(reader, reason)\n : undefined;\n\n return new Proxy(reader, {\n get(target: StreamReaderLike, prop: string | symbol): unknown {\n if (prop === 'read') {\n return async (): Promise<{ done: boolean; value?: unknown }> => {\n try {\n const result = await read();\n if (result.done) {\n settle();\n } else if (claim('reader')) {\n processEvent(result.value, state, recordOutputs);\n }\n return result;\n } catch (error) {\n settle(error);\n throw error;\n }\n };\n }\n\n if (prop === 'cancel' && cancel) {\n return async (reason?: unknown): Promise<unknown> => {\n markCancelled();\n try {\n return await cancel(reason);\n } finally {\n settle();\n }\n };\n }\n\n const value = Reflect.get(target, prop, target) as unknown;\n return typeof value === 'function' ? value.bind(target) : value;\n },\n });\n}\n\n/**\n * A stream that pulls through `readable`'s instrumented reader.\n *\n * `tee`, `pipeTo` and `pipeThrough` acquire their reader through internal slots rather than by\n * calling the public `getReader`, so patching that method alone leaves them uninstrumented: the\n * chunks bypass accumulation and the span is never ended. Handing them this stream instead routes\n * them back through the wrapped reader, so there is still exactly one accumulating consumer.\n *\n * Same idea as `monitorStream` in `@sentry/deno`, with two deliberate differences: chunks are pulled\n * on demand rather than drained in a `start` loop, so backpressure still reaches the source, and\n * `cancel` is forwarded (the hole #24054 fixed there) so the source stops producing when the\n * consumer disconnects.\n */\nfunction instrumentedSource(readable: ReadableStreamLike): ReadableStream<unknown> {\n // The patched `getReader`, so reads are accumulated and the span is ended by the shared logic.\n const reader = readable.getReader!();\n\n return new ReadableStream({\n async pull(controller) {\n const { done, value } = await reader.read();\n if (done) {\n controller.close();\n return;\n }\n controller.enqueue(value);\n },\n async cancel(reason) {\n await reader.cancel?.(reason);\n },\n });\n}\n\n/**\n * Instrument a Mistral event stream in place: accumulate response attributes as it is drained and\n * end `span` when it finishes.\n *\n * The stream is patched rather than replaced because `EventStream` extends `ReadableStream`, so\n * handing back a bare async generator would drop `getReader`, `tee`, `pipeTo` and the rest of the\n * `ReadableStream` API the caller is entitled to.\n *\n * Both `for await` and `getReader()` are valid ways to drain a `ReadableStream`, and the SDK's\n * iterator polyfill reads through `getReader()`, so both are wrapped. The first path to see a chunk\n * claims accumulation and the other stays a pass-through, which keeps a chunk from being counted\n * twice when one path drives the other.\n *\n * Returns `false` for a value that is not a stream, leaving it untouched.\n */\nexport function instrumentEventStream(\n stream: unknown,\n span: Span,\n recordOutputs: boolean,\n abortSignal?: AbortSignal,\n beforeSpanEnd?: (result: GenAiSpanResult<never>) => void,\n): boolean {\n if (!isAsyncIterable(stream)) {\n return false;\n }\n\n const state = createStreamingState();\n let consumer: StreamConsumer | undefined;\n let settled = false;\n let cancelled = false;\n\n // Called for each received event.\n const claim = (candidate: StreamConsumer): boolean => {\n recordTimeToFirstChunk(span);\n consumer ??= candidate;\n return consumer === candidate;\n };\n\n // Set synchronously when the caller asks to cancel, before the underlying cancel is awaited.\n // Cancelling can reject an in-flight `read()` (it aborts the HTTP body the stream reads from), and\n // that rejection would otherwise reach `settle` first and record a deliberate abort as a failure.\n const markCancelled = (): void => {\n cancelled = true;\n };\n\n const settle = (error?: unknown): void => {\n if (settled) {\n return;\n }\n settled = true;\n if (error !== undefined && !cancelled) {\n span.setStatus(getErrorStatus(abortSignal));\n }\n\n const toolCalls = Object.values(state.toolCalls);\n\n if (recordOutputs) {\n // Set the authoritative `gen_ai.output.messages` alongside the deprecated response attributes\n // `endStreamSpan` writes, so tool calls survive Relay's lossy migration. A stream is a single\n // assistant turn, so the accumulated fragments make up one message.\n setOutputMessagesAttribute(span, {\n responseText: state.responseTexts.join(''),\n toolCalls,\n finishReason: state.finishReasons[0],\n });\n }\n\n endStreamSpan(span, { ...state, toolCalls }, recordOutputs, () =>\n beforeSpanEnd?.(error !== undefined && !cancelled ? { error } : {}),\n );\n };\n\n const iterate = stream[Symbol.asyncIterator].bind(stream);\n const instrumented = instrumentIterator(iterate, state, recordOutputs, claim, settle);\n stream[Symbol.asyncIterator] = () => instrumented;\n\n const readable = stream as ReadableStreamLike;\n\n if (typeof readable.getReader === 'function') {\n const getReader = readable.getReader.bind(readable);\n readable.getReader = (...args: unknown[]) =>\n wrapReader(getReader(...args), state, recordOutputs, claim, settle, markCancelled);\n }\n\n if (typeof readable.cancel === 'function') {\n const cancel = readable.cancel.bind(readable);\n readable.cancel = async (reason?: unknown): Promise<unknown> => {\n markCancelled();\n try {\n return await cancel(reason);\n } finally {\n settle();\n }\n };\n }\n\n // Only patched when `getReader` is present, since that is what `instrumentedSource` pulls through.\n if (typeof readable.getReader === 'function') {\n if (typeof readable.tee === 'function') {\n readable.tee = () => instrumentedSource(readable).tee();\n }\n\n if (typeof readable.pipeTo === 'function') {\n readable.pipeTo = (destination: unknown, options?: unknown) =>\n instrumentedSource(readable).pipeTo(destination as WritableStream<unknown>, options as StreamPipeOptions);\n }\n\n if (typeof readable.pipeThrough === 'function') {\n readable.pipeThrough = (transform: unknown, options?: unknown) =>\n instrumentedSource(readable).pipeThrough(\n transform as ReadableWritablePair<unknown, unknown>,\n options as StreamPipeOptions,\n );\n }\n }\n\n return true;\n}\n","import { startSpan, startSpanManual, stringify } from '@sentry/core';\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_AGENT_NAME,\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_TOOL_DEFINITIONS,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { InstrumentedMethodEntry } from '../core/utils';\nimport {\n buildMethodPath,\n extractSystemInstructions,\n getErrorStatus,\n getGenAiSpanOp,\n resolveGenAiCallRecording,\n wrapPromiseWithMethods,\n} from '../core/utils';\nimport { GEN_AI_REQUEST_STREAM_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport { MISTRAL_METHOD_REGISTRY, MISTRAL_ORIGIN, MISTRAL_PROVIDER_NAME } from './constants';\nimport { instrumentEventStream } from './streaming';\nimport type { MistralCallInfo, MistralOptions } from './types';\nimport { addResponseAttributes, extractRequestParameters, getMistralRequestSignal, getSpanName } from './utils';\n\n/**\n * Serialize tool definitions from request parameters, if present.\n */\nfunction extractToolDefinitions(params: Record<string, unknown>): string | undefined {\n if (!Array.isArray(params.tools) || params.tools.length === 0) {\n return undefined;\n }\n return stringify(params.tools);\n}\n\n/**\n * Extract request attributes from method arguments.\n *\n * `streaming` comes from the called method, not the request: v2 streams only through the dedicated\n * `*.stream` methods, and their `stream` request field is optional, so a params-derived value would\n * be missing on most streaming calls.\n */\nexport function extractRequestAttributes(\n args: unknown[],\n operationName: string,\n recordInputs: boolean,\n streaming: boolean,\n): Record<string, unknown> {\n const attributes: Record<string, unknown> = {\n [GEN_AI_PROVIDER_NAME]: MISTRAL_PROVIDER_NAME,\n [GEN_AI_OPERATION_NAME]: operationName,\n [SENTRY_ORIGIN]: MISTRAL_ORIGIN,\n [GEN_AI_REQUEST_STREAM_ATTRIBUTE]: streaming,\n };\n\n if (args.length > 0 && typeof args[0] === 'object' && args[0] !== null) {\n const params = args[0] as Record<string, unknown>;\n\n if (operationName === 'invoke_agent' && typeof params.agentId === 'string') {\n attributes[GEN_AI_AGENT_NAME] = params.agentId;\n }\n\n const tools = recordInputs ? extractToolDefinitions(params) : undefined;\n if (tools) {\n attributes[GEN_AI_TOOL_DEFINITIONS] = tools;\n }\n\n Object.assign(attributes, extractRequestParameters(params));\n }\n\n return attributes;\n}\n\n/**\n * Record AI request inputs on the span, if recording is enabled.\n */\nexport function addRequestAttributes(span: Span, params: Record<string, unknown>, operationName: string): void {\n if (operationName === 'embeddings') {\n const input = params.inputs;\n if (input == null || (typeof input === 'string' && input.length === 0) || (Array.isArray(input) && !input.length)) {\n return;\n }\n span.setAttribute(GEN_AI_EMBEDDINGS_INPUT, stringify(input, String));\n return;\n }\n\n const src = 'messages' in params ? params.messages : undefined;\n if (!src || (Array.isArray(src) && src.length === 0)) {\n return;\n }\n\n const { systemInstructions, filteredMessages } = extractSystemInstructions(src);\n if (systemInstructions) {\n span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS, systemInstructions);\n }\n span.setAttribute(GEN_AI_INPUT_MESSAGES, stringify(filteredMessages));\n}\n\n/**\n * Instrument a single Mistral SDK method with a gen_ai span.\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) => Promise<R>,\n instrumentedMethod: InstrumentedMethodEntry,\n context: unknown,\n options: MistralOptions,\n): (...args: T) => Promise<R> {\n return function instrumentedCall(...args: T): Promise<R> {\n const operationName = instrumentedMethod.operation || 'unknown';\n const isStreamRequested = !!instrumentedMethod.streaming;\n const params = args[0] as Record<string, unknown> | undefined;\n const abortSignal = getMistralRequestSignal(args[1]);\n const call: MistralCallInfo = { operation: operationName, request: params };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n const requestAttributes = extractRequestAttributes(args, operationName, recordInputs, isStreamRequested);\n\n const spanConfig = {\n name: getSpanName(operationName, requestAttributes),\n op: getGenAiSpanOp(operationName),\n attributes: requestAttributes as Record<string, SpanAttributeValue>,\n };\n\n if (isStreamRequested) {\n let originalResult!: Promise<R>;\n\n const instrumentedPromise = startSpanManual(spanConfig, (span: Span) => {\n originalResult = originalMethod.apply(context, args);\n\n if (recordInputs && params) {\n addRequestAttributes(span, params, operationName);\n }\n runGenAiSpanStart(options, span, call);\n\n return originalResult.then(\n result => {\n // Patched in place so the caller keeps the real `EventStream`; `instrumentEventStream`\n // takes over ending the span once the stream is drained.\n const isStream = instrumentEventStream(result, span, recordOutputs, abortSignal, streamResult =>\n runGenAiSpanEnd(options, span, call, streamResult),\n );\n if (!isStream) {\n runGenAiSpanEnd(options, span, call, { response: result });\n span.end();\n }\n return result;\n },\n error => {\n span.setStatus(getErrorStatus(abortSignal));\n runGenAiSpanEnd(options, span, call, { error });\n span.end();\n throw error;\n },\n );\n });\n\n return wrapPromiseWithMethods(originalResult, instrumentedPromise);\n }\n\n let originalResult!: Promise<R>;\n\n const instrumentedPromise = startSpan(spanConfig, (span: Span) => {\n originalResult = originalMethod.apply(context, args);\n\n if (recordInputs && params) {\n addRequestAttributes(span, params, operationName);\n }\n runGenAiSpanStart(options, span, call);\n\n return originalResult.then(\n result => {\n addResponseAttributes(span, result, 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 * Create a deep proxy for Mistral client instrumentation.\n */\nfunction createDeepProxy<T extends object>(target: T, currentPath = '', options: MistralOptions): T {\n return new Proxy(target, {\n get(obj: object, prop: string): unknown {\n const value = (obj as Record<string, unknown>)[prop];\n const methodPath = buildMethodPath(currentPath, String(prop));\n\n const instrumentedMethod = MISTRAL_METHOD_REGISTRY[methodPath as keyof typeof MISTRAL_METHOD_REGISTRY];\n if (typeof value === 'function' && instrumentedMethod) {\n return instrumentMethod(value as (...args: unknown[]) => Promise<unknown>, instrumentedMethod, obj, options);\n }\n\n if (typeof value === 'function') {\n // Preserve the original `this` for uninstrumented methods (private class fields).\n return value.bind(obj);\n }\n\n if (value && typeof value === 'object') {\n return createDeepProxy(value, methodPath, options);\n }\n\n return value;\n },\n }) as T;\n}\n\n/**\n * Instrument a Mistral client with Sentry tracing.\n * Can be used across Node.js, Cloudflare Workers, and Vercel Edge.\n */\nexport function instrumentMistralAiClient<T extends object>(client: T, options?: MistralOptions): T {\n return createDeepProxy(client, '', options ?? {});\n}\n","export const TYPESAFE_INTEGRATION_NAME = 'TypeSafe' as const;\n\nexport const TYPESAFE_PROVIDER_NAME = 'typesafe' as const;\n\nexport const TYPESAFE_ORIGIN = 'auto.ai.typesafe' as const;\n","import {\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_OUTPUT_MESSAGES,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_DECIDE } from '@sentry/conventions/op';\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport { isObjectLike, SPAN_STATUS_ERROR, startInactiveSpan, withActiveSpan } from '@sentry/core';\nimport type { GenAiSpanHooks } from '../core/span-hooks';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { GenAiCallOptions } from '../core/utils';\nimport { getEvaluationInputMessages, getEvaluationOutputMessages, resolveGenAiCallRecording } from '../core/utils';\nimport { TYPESAFE_ORIGIN, TYPESAFE_PROVIDER_NAME } from './constants';\n\n/** The call that `recordInputs`/`recordOutputs` decide on, and that the span hooks get. */\nexport interface TypeSafeCallInfo {\n /** The request, the first argument of `systemOne` as passed. */\n request: unknown;\n}\n\n/** Options for the TypeSafe integration. `onSpanEnd` gets the parsed `systemOne` result. */\nexport type TypeSafeOptions = GenAiCallOptions<TypeSafeCallInfo> & GenAiSpanHooks<TypeSafeCallInfo>;\n\n/**\n * Start the span for a `systemOne(request)` call. The request model falls back to the client's\n * `defaultModel`, the same way the SDK resolves it.\n */\nexport function startDecideSpan(\n request: unknown,\n client: unknown,\n recordInputs: boolean,\n attributes?: SpanAttributes,\n): Span {\n const params = isObjectLike(request) ? request : {};\n const defaultModel = isObjectLike(client) ? client.defaultModel : undefined;\n const model =\n typeof params.model === 'string' ? params.model : typeof defaultModel === 'string' ? defaultModel : undefined;\n\n return startInactiveSpan({\n name: model ? `decide ${model}` : 'decide',\n // oxlint-disable-next-line typescript/no-deprecated -- the rename to `gen_ai.decide` comes in a follow-up\n op: GEN_AI_DECIDE,\n // Extra attributes (e.g. another integration's origin) are set at start, so samplers see them.\n attributes: { ...getRequestAttributes(params, model, recordInputs), ...attributes },\n });\n}\n\nfunction getRequestAttributes(\n request: Record<string, unknown>,\n model: string | undefined,\n recordInputs: boolean,\n): SpanAttributes {\n return {\n [SENTRY_ORIGIN]: TYPESAFE_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'decide',\n [GEN_AI_PROVIDER_NAME]: TYPESAFE_PROVIDER_NAME,\n [GEN_AI_REQUEST_MODEL]: model,\n ...(recordInputs ? { [GEN_AI_INPUT_MESSAGES]: getEvaluationInputMessages(request) } : {}),\n };\n}\n\n/**\n * Add the response model, token usage and (optionally) the answers of a `systemOne` result.\n * Also used for TypeSafe models on Workers AI.\n */\nexport function addResponseAttributes(span: Span, result: unknown, recordOutputs: boolean): void {\n if (!isObjectLike(result)) {\n return;\n }\n\n if (typeof result.model === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, result.model);\n }\n\n const usage = isObjectLike(result.usage) ? result.usage : undefined;\n const inputTokens = typeof usage?.input_tokens === 'number' ? usage.input_tokens : undefined;\n const outputTokens = typeof usage?.output_tokens === 'number' ? usage.output_tokens : undefined;\n if (inputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, inputTokens);\n }\n if (outputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, outputTokens);\n }\n if (inputTokens !== undefined && outputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, inputTokens + outputTokens);\n }\n\n if (recordOutputs && result.answers !== undefined) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, getEvaluationOutputMessages(result.answers));\n }\n}\n\n/**\n * `systemOne` returns a lazy `APIPromise` before the request settles, and parses the body on the first\n * `.then()`. Wait on `asResponse()` (the raw fetch, which does not parse the body) and read a clone of\n * the body, so the caller's own parse is unaffected. Call this before the caller can await the result,\n * so the clone is taken first. Returns `false` when `result` is not an `APIPromise`.\n */\nexport function onSystemOneResponse(\n result: unknown,\n onBody: (body: unknown) => void,\n onError: (error: unknown) => void,\n): boolean {\n if (!isObjectLike(result) || typeof result.asResponse !== 'function') {\n return false;\n }\n\n (result.asResponse() as Promise<Response>).then(\n response =>\n response\n .clone()\n .json()\n .then(\n body => onBody(body),\n () => onBody(undefined),\n ),\n error => onError(error),\n );\n\n return true;\n}\n\n/**\n * Instrument a TypeSafe client (`@typesafe-ai/sdk`) with Sentry tracing.\n */\nexport function instrumentTypeSafeClient<T extends object>(client: T, options?: TypeSafeOptions): T {\n return new Proxy(client, {\n get(target, prop) {\n // Read with the real client as receiver: the SDK keeps its API key in a private class field.\n const value: unknown = Reflect.get(target, prop, target);\n if (typeof value !== 'function') {\n return value;\n }\n if (prop === 'systemOne') {\n return (...args: unknown[]) =>\n instrumentSystemOne(value as (...args: unknown[]) => unknown, target, args, options ?? {});\n }\n return value.bind(target);\n },\n });\n}\n\nfunction instrumentSystemOne(\n systemOne: (...args: unknown[]) => unknown,\n client: object,\n args: unknown[],\n options: TypeSafeOptions,\n): unknown {\n const call: TypeSafeCallInfo = { request: args[0] };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n const span = startDecideSpan(args[0], client, recordInputs);\n runGenAiSpanStart(options, span, call);\n const endWithError = (error: unknown): void => {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n runGenAiSpanEnd(options, span, call, { error });\n span.end();\n };\n\n let result: unknown;\n try {\n result = withActiveSpan(span, () => systemOne.apply(client, args));\n } catch (error) {\n endWithError(error);\n throw error;\n }\n\n const waiting = onSystemOneResponse(\n result,\n body => {\n addResponseAttributes(span, body, recordOutputs);\n runGenAiSpanEnd(options, span, call, { response: body });\n span.end();\n },\n endWithError,\n );\n if (!waiting) {\n runGenAiSpanEnd(options, span, call, { response: result });\n span.end();\n }\n\n return result;\n}\n","export const PI_AI_INTEGRATION_NAME = 'PiAi' as const;\n\nexport const PI_AI_ORIGIN = 'auto.ai.pi_ai';\n","import { SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { _INTERNAL_shouldSkipAiProviderWrapping, getActiveSpan, spanToJSON } from '@sentry/core';\nimport { PI_AI_ORIGIN } from './constants';\n\n/**\n * Whether the active span is a pi-ai `chat` span, which means a provider SDK call being made is pi-ai\n * sending its request.\n */\nexport function isInsidePiAiSpan(): boolean {\n const span = getActiveSpan();\n return !!span && spanToJSON(span).attributes[SENTRY_ORIGIN] === PI_AI_ORIGIN;\n}\n\n/**\n * Whether a provider integration should leave a call alone, because the integration driving the SDK\n * reports it. LangChain and Vercel AI mark the providers they drive as skipped; pi-ai is detected per\n * request, by its active span.\n */\nexport function shouldSkipAiProviderSpan(integrationName: string): boolean {\n return _INTERNAL_shouldSkipAiProviderWrapping(integrationName) || isInsidePiAiSpan();\n}\n","/**\n * The provider value for the `gen_ai.provider.name` attribute.\n * @see https://developers.cloudflare.com/workers-ai/\n */\nexport const WORKERS_AI_PROVIDER_NAME = 'cloudflare.workers_ai';\n\n/**\n * The Sentry origin for spans created by the Workers AI instrumentation.\n */\nexport const WORKERS_AI_ORIGIN = 'auto.ai.cloudflare.workers_ai';\n\n/**\n * The key used to register this provider in the AI provider skip registry.\n *\n * @see `_INTERNAL_skipAiProviderWrapping`\n */\nexport const WORKERS_AI_INTEGRATION_NAME = 'WorkersAI' as const;\n","/* eslint-disable typescript-eslint/no-deprecated */\nimport {\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_OUTPUT_MESSAGES,\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_PRESENCE_PENALTY,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_REQUEST_TOP_K,\n GEN_AI_REQUEST_TOP_P,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_CHAT, GEN_AI_EMBEDDINGS, GEN_AI_DECIDE, GEN_AI_EXTRACT } from '@sentry/conventions/op';\nimport { isObjectLike, stringify } from '@sentry/core';\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport { GEN_AI_REQUEST_STREAM_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport {\n extractSystemInstructions,\n getEvaluationInputMessages,\n getTokenUsageAttributes,\n setOutputMessagesAttribute,\n} from '../core/utils';\nimport { addResponseAttributes as addDecideResponseAttributes } from '../typesafe';\n// Re-exported so `workers-ai/streaming.ts` keeps importing it from this module.\nexport { setOutputMessagesAttribute };\nimport { WORKERS_AI_ORIGIN, WORKERS_AI_PROVIDER_NAME } from './constants';\nimport type { WorkersAiChoice, WorkersAiInput, WorkersAiOutput } from './types';\n\nexport type WorkersAiOperationName = 'chat' | 'embeddings' | 'decide' | 'extract';\n\nexport const WORKERS_AI_OPERATION_SPAN_OPS: Record<WorkersAiOperationName, string> = {\n chat: GEN_AI_CHAT,\n embeddings: GEN_AI_EMBEDDINGS,\n decide: GEN_AI_DECIDE,\n extract: GEN_AI_EXTRACT,\n};\n\n/**\n * Model ID prefixes of the evaluation models (TypeSafe Jev and Cloudflare Clef), traced as `decide` spans.\n */\nconst DECIDE_MODEL_PREFIXES = ['typesafe/jev', '@cf/cloudflare/clef'];\n\n/**\n * Model ID prefixes of the field extraction models (Cloudflare Clairic), traced as `extract` spans.\n */\nconst EXTRACT_MODEL_PREFIXES = ['@cf/cloudflare/clairic'];\n\nconst BLOB_SUBSTITUTE = '[Blob substitute]';\n\n/**\n * Determine the gen_ai operation name from the model and inputs passed to `AI.run`.\n * Workers AI exposes a single `run` method, so we infer the operation from the model ID and the input shape.\n */\nexport function getOperationName(model: unknown, inputs: unknown): WorkersAiOperationName {\n if (typeof model === 'string' && DECIDE_MODEL_PREFIXES.some(prefix => model.startsWith(prefix))) {\n return 'decide';\n }\n if (typeof model === 'string' && EXTRACT_MODEL_PREFIXES.some(prefix => model.startsWith(prefix))) {\n return 'extract';\n }\n if (inputs && typeof inputs === 'object') {\n if ('messages' in inputs || 'prompt' in inputs) {\n return 'chat';\n }\n if ('text' in inputs) {\n return 'embeddings';\n }\n }\n return 'chat';\n}\n\n/**\n * Extract the request attributes (model, request parameters, system, origin) from a `run` call.\n */\nexport function extractRequestAttributes(\n model: unknown,\n inputs: unknown,\n operationName: string,\n): Record<string, SpanAttributeValue> {\n const attributes: Record<string, SpanAttributeValue> = {\n [GEN_AI_PROVIDER_NAME]: WORKERS_AI_PROVIDER_NAME,\n [GEN_AI_OPERATION_NAME]: operationName,\n [SENTRY_ORIGIN]: WORKERS_AI_ORIGIN,\n [GEN_AI_REQUEST_MODEL]: typeof model === 'string' ? model : 'unknown',\n };\n\n if (inputs && typeof inputs === 'object') {\n const params = inputs as WorkersAiInput;\n\n if (typeof params.temperature === 'number') {\n attributes[GEN_AI_REQUEST_TEMPERATURE] = params.temperature;\n }\n if (typeof params.max_tokens === 'number') {\n attributes[GEN_AI_REQUEST_MAX_TOKENS] = params.max_tokens;\n }\n if (typeof params.top_p === 'number') {\n attributes[GEN_AI_REQUEST_TOP_P] = params.top_p;\n }\n if (typeof params.top_k === 'number') {\n attributes[GEN_AI_REQUEST_TOP_K] = params.top_k;\n }\n if (typeof params.frequency_penalty === 'number') {\n attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY] = params.frequency_penalty;\n }\n if (typeof params.presence_penalty === 'number') {\n attributes[GEN_AI_REQUEST_PRESENCE_PENALTY] = params.presence_penalty;\n }\n if (params.stream === true) {\n attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE] = true;\n }\n }\n\n return attributes;\n}\n\n/**\n * Record the request inputs (messages/prompt/embeddings input) on the span.\n * Only called when `recordInputs` is enabled.\n */\nexport function addRequestAttributes(span: Span, inputs: unknown, operationName: string): void {\n if (!inputs || typeof inputs !== 'object') {\n return;\n }\n const params = inputs as WorkersAiInput;\n\n if (operationName === 'decide') {\n span.setAttribute(GEN_AI_INPUT_MESSAGES, getEvaluationInputMessages(inputs as Record<string, unknown>));\n return;\n }\n\n if (operationName === 'extract') {\n // Record the request body as passed, but never the image data.\n const { model: _model, ...request } = inputs as Record<string, unknown>;\n if (Array.isArray(request.images)) {\n request.images = request.images.map(() => BLOB_SUBSTITUTE);\n }\n span.setAttribute(GEN_AI_INPUT_MESSAGES, stringify([request]));\n return;\n }\n\n // Store embeddings input on a separate attribute\n if (operationName === 'embeddings') {\n const text = params.text;\n\n if (text == null || (typeof text === 'string' && text.length === 0) || (Array.isArray(text) && text.length === 0)) {\n return;\n }\n\n span.setAttribute(GEN_AI_EMBEDDINGS_INPUT, stringify(text, String));\n return;\n }\n\n const src = params.messages ?? params.prompt;\n\n if (src == null || (Array.isArray(src) && src.length === 0)) {\n return;\n }\n\n const { systemInstructions, filteredMessages } = extractSystemInstructions(src);\n\n if (systemInstructions) {\n span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS, systemInstructions);\n }\n\n span.setAttribute(GEN_AI_INPUT_MESSAGES, stringify(filteredMessages));\n}\n\n/**\n * Record the response attributes (token usage, response text, tool calls) on the span.\n */\nexport function addResponseAttributes(\n span: Span,\n result: unknown,\n recordOutputs: boolean,\n operationName?: WorkersAiOperationName,\n): void {\n if (operationName === 'decide') {\n // The binding wraps the TypeSafe response as `{ state, result }`, but the docs show it unwrapped.\n const body = isObjectLike(result) && isObjectLike(result.result) ? result.result : result;\n addDecideResponseAttributes(span, body, recordOutputs);\n return;\n }\n\n if (operationName === 'extract') {\n addExtractResponseAttributes(span, result, recordOutputs);\n return;\n }\n\n if (\n !result ||\n typeof result !== 'object' ||\n // Raw `Response` objects (from `returnRawResponse`/`websocket`) cannot be introspected without consuming them.\n (typeof Response !== 'undefined' && result instanceof Response)\n ) {\n return;\n }\n\n const response = result as WorkersAiOutput;\n\n if (response.usage) {\n span.setAttributes(getTokenUsageAttributes(response.usage.prompt_tokens, response.usage.completion_tokens));\n }\n\n if (Array.isArray(response.choices)) {\n if (typeof response.id === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_ID, response.id);\n }\n if (typeof response.model === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, response.model);\n }\n addChoicesResponseAttributes(span, response.choices, recordOutputs);\n return;\n }\n\n if (recordOutputs) {\n let responseText: string | undefined;\n if (typeof response.response === 'string') {\n responseText = response.response;\n span.setAttribute(GEN_AI_RESPONSE_TEXT, response.response);\n } else if (response.response != null) {\n responseText = JSON.stringify(response.response);\n span.setAttribute(GEN_AI_RESPONSE_TEXT, responseText);\n }\n\n const toolCalls =\n Array.isArray(response.tool_calls) && response.tool_calls.length > 0 ? response.tool_calls : undefined;\n if (toolCalls) {\n span.setAttribute(GEN_AI_RESPONSE_TOOL_CALLS, JSON.stringify(toolCalls));\n }\n\n setOutputMessagesAttribute(span, { responseText, toolCalls });\n }\n}\n\nfunction addChoicesResponseAttributes(span: Span, choices: WorkersAiChoice[], recordOutputs: boolean): void {\n const finishReasons = choices\n .map(choice => choice.finish_reason)\n .filter((reason): reason is string => typeof reason === 'string');\n if (finishReasons.length > 0) {\n span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, JSON.stringify(finishReasons));\n }\n\n if (!recordOutputs) {\n return;\n }\n\n const messages = choices.map(({ message, finish_reason }) => ({\n responseText: typeof message?.content === 'string' ? message.content : undefined,\n toolCalls: message?.tool_calls,\n finishReason: typeof finish_reason === 'string' ? finish_reason : undefined,\n }));\n\n setOutputMessagesAttribute(span, messages);\n}\n\nfunction addExtractResponseAttributes(span: Span, body: unknown, recordOutputs: boolean): void {\n if (!isObjectLike(body)) {\n return;\n }\n\n const { model, usage, ...response } = body;\n\n if (typeof model === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, model);\n }\n\n if (isObjectLike(usage)) {\n span.setAttributes(\n getTokenUsageAttributes(\n typeof usage.input_tokens === 'number' ? usage.input_tokens : undefined,\n typeof usage.output_tokens === 'number' ? usage.output_tokens : undefined,\n ),\n );\n }\n\n if (recordOutputs) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, stringify([response]));\n }\n}\n","import type { Span } from '@sentry/core';\nimport type { GenAiSpanResult } from '../core/span-hooks';\nimport { getToolCallKey } from '../core/streaming-tool-calls';\nimport { endStreamSpan, getErrorStatus, type StreamResponseState } from '../core/utils';\nimport { recordTimeToFirstChunk } from '../core/time-to-first-chunk';\nimport type { WorkersAiUsage } from './types';\nimport { setOutputMessagesAttribute } from './utils';\n\ninterface WorkersAiStreamingToolCall {\n index?: number | null;\n id?: string;\n type?: string;\n function?: { name?: string; arguments?: string };\n // Some Workers AI models stream tool calls with the name/arguments at the top\n // level of the tool-call object instead of nested under `function`.\n name?: string;\n arguments?: string;\n}\n\ninterface WorkersAiStreamChunk {\n // Native Workers AI streaming shape (`env.AI.run` with `stream: true`).\n response?: unknown;\n tool_calls?: unknown[];\n // OpenAI-compatible streaming shape emitted for models routed through the\n // OpenAI-compatible endpoint (e.g. via `workers-ai-provider`).\n id?: unknown;\n model?: unknown;\n choices?: Array<{\n delta?: { content?: unknown; tool_calls?: WorkersAiStreamingToolCall[] };\n finish_reason?: unknown;\n }>;\n usage?: WorkersAiUsage & { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number };\n}\n\n/**\n * Tool calls accumulated from a stream, keyed in the order they were opened (so output order is arrival order).\n */\ninterface ToolCallAccumulator {\n calls: Map<string, WorkersAiStreamingToolCall>;\n /** Key of the latest call, which argument fragments with neither `index`, `id` nor name continue. */\n lastKey?: string;\n /** Key of the call currently open for a reported `index`, when a new `id` reused that index. */\n keyByIndex: Map<number, string>;\n}\n\n/**\n * Accumulate a fragmented OpenAI-compatible tool call (delivered across multiple\n * `choices[].delta.tool_calls` chunks) into the accumulator.\n */\nfunction accumulateStreamingToolCalls(toolCalls: WorkersAiStreamingToolCall[], accumulator: ToolCallAccumulator): void {\n for (const toolCall of toolCalls) {\n // Normalize both shapes: name/arguments nested under `function`, or at the top level.\n const name = toolCall.function?.name ?? toolCall.name;\n const args = toolCall.function?.arguments ?? toolCall.arguments;\n\n // A tool call must carry at least a name or argument fragment to be meaningful.\n if (name == null && args == null) {\n continue;\n }\n\n const key = getToolCallKey(toolCall, name, accumulator);\n const existing = accumulator.calls.get(key);\n\n if (!existing) {\n accumulator.calls.set(key, {\n index: toolCall.index,\n id: toolCall.id,\n type: toolCall.type,\n function: {\n name,\n arguments: args ?? '',\n },\n });\n } else if (existing.function) {\n if (name && !existing.function.name) {\n existing.function.name = name;\n }\n if (args) {\n existing.function.arguments = `${existing.function.arguments ?? ''}${args}`;\n }\n }\n accumulator.lastKey = key;\n }\n}\n\n/**\n * Parse a single SSE line (`data: {...}`) and accumulate its data into the streaming state.\n *\n * Handles both the native Workers AI shape (top-level `response`/`tool_calls`) and the\n * OpenAI-compatible shape (`choices[].delta.content`/`choices[].delta.tool_calls`), because\n * the same `run()` call transparently yields either format depending on the model.\n */\nfunction processLine(\n line: string,\n state: StreamResponseState,\n recordOutputs: boolean,\n toolCallAccumulator: ToolCallAccumulator,\n): void {\n const trimmed = line.trim();\n if (!trimmed.startsWith('data:')) {\n return;\n }\n\n const data = trimmed.slice('data:'.length).trim();\n if (!data || data === '[DONE]') {\n return;\n }\n\n let parsed: WorkersAiStreamChunk;\n try {\n parsed = JSON.parse(data) as WorkersAiStreamChunk;\n } catch {\n return;\n }\n\n if (parsed.usage) {\n if (typeof parsed.usage.prompt_tokens === 'number') {\n state.promptTokens = parsed.usage.prompt_tokens;\n }\n if (typeof parsed.usage.completion_tokens === 'number') {\n state.completionTokens = parsed.usage.completion_tokens;\n }\n if (typeof parsed.usage.total_tokens === 'number') {\n state.totalTokens = parsed.usage.total_tokens;\n }\n }\n\n if (recordOutputs && typeof parsed.response === 'string') {\n state.responseTexts.push(parsed.response);\n }\n\n if (recordOutputs && Array.isArray(parsed.tool_calls) && parsed.tool_calls.length > 0) {\n state.toolCalls.push(...parsed.tool_calls);\n }\n\n if (Array.isArray(parsed.choices)) {\n if (typeof parsed.id === 'string') {\n state.responseId = parsed.id;\n }\n if (typeof parsed.model === 'string') {\n state.responseModel = parsed.model;\n }\n\n for (const choice of parsed.choices) {\n if (recordOutputs && typeof choice.delta?.content === 'string' && choice.delta.content) {\n state.responseTexts.push(choice.delta.content);\n }\n if (recordOutputs && Array.isArray(choice.delta?.tool_calls)) {\n accumulateStreamingToolCalls(choice.delta.tool_calls, toolCallAccumulator);\n }\n if (typeof choice.finish_reason === 'string') {\n state.finishReasons.push(choice.finish_reason);\n }\n }\n }\n}\n\n/**\n * Wrap a Workers AI streaming response (a server-sent-events `ReadableStream`) so we can\n * accumulate the response text and token usage while passing the original bytes through untouched.\n *\n * The span is ended once the consumer finishes reading (or cancels) the stream.\n */\nexport function instrumentWorkersAiStream(\n stream: ReadableStream<Uint8Array>,\n span: Span,\n recordOutputs: boolean,\n abortSignal?: AbortSignal,\n beforeSpanEnd?: (result: GenAiSpanResult<never>) => void,\n): ReadableStream<Uint8Array> {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n\n const state: StreamResponseState = {\n responseId: '',\n responseModel: '',\n finishReasons: [],\n responseTexts: [],\n toolCalls: [],\n promptTokens: undefined,\n completionTokens: undefined,\n totalTokens: undefined,\n };\n\n // OpenAI-compatible tool calls arrive fragmented across chunks and are keyed by index;\n // accumulate them here and flatten into `state.toolCalls` once the stream ends.\n const toolCallAccumulator: ToolCallAccumulator = { calls: new Map(), keyByIndex: new Map() };\n\n let buffer = '';\n let spanEnded = false;\n\n const finish = (result: GenAiSpanResult<never> = {}): void => {\n if (spanEnded) {\n return;\n }\n spanEnded = true;\n\n if (recordOutputs) {\n const accumulatedToolCalls = [...toolCallAccumulator.calls.values()];\n if (accumulatedToolCalls.length > 0) {\n state.toolCalls.push(...accumulatedToolCalls);\n }\n\n // Set the authoritative `gen_ai.output.messages` alongside the deprecated response\n // attributes `endStreamSpan` writes, so tool calls survive Relay's lossy migration.\n setOutputMessagesAttribute(span, {\n responseText: state.responseTexts.join(''),\n toolCalls: state.toolCalls,\n finishReason: state.finishReasons[0],\n });\n }\n\n endStreamSpan(span, state, recordOutputs, () => beforeSpanEnd?.(result));\n };\n\n const flushBuffer = (isDone: boolean): void => {\n const lines = buffer.split('\\n');\n // Keep the last (potentially incomplete) line in the buffer unless the stream is done.\n buffer = isDone ? '' : (lines.pop() ?? '');\n for (const line of lines) {\n processLine(line, state, recordOutputs, toolCallAccumulator);\n }\n };\n\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n\n if (done) {\n buffer += decoder.decode();\n flushBuffer(true);\n finish();\n controller.close();\n return;\n }\n\n recordTimeToFirstChunk(span);\n buffer += decoder.decode(value, { stream: true });\n flushBuffer(false);\n controller.enqueue(value);\n } catch (error) {\n span.setStatus(getErrorStatus(abortSignal));\n finish({ error });\n controller.error(error);\n }\n },\n async cancel(reason) {\n finish();\n await reader.cancel(reason);\n },\n });\n}\n","import { SENTRY_OP } from '@sentry/conventions/attributes';\nimport { getClient, hasSpanStreamingEnabled, startSpan, startSpanManual } from '@sentry/core';\nimport type { Span } from '@sentry/core';\nimport { getErrorStatus, getRequestSignal, isReadableStream, resolveGenAiCallRecording } from '../core/utils';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport { shouldSkipAiProviderSpan } from '../pi-ai/providers';\nimport { WORKERS_AI_INTEGRATION_NAME } from './constants';\nimport { instrumentWorkersAiStream } from './streaming';\nimport type { WorkersAiCallInfo, WorkersAiOptions } from './types';\nimport {\n addRequestAttributes,\n addResponseAttributes,\n extractRequestAttributes,\n getOperationName,\n WORKERS_AI_OPERATION_SPAN_OPS,\n} from './utils';\n\nconst originalClients = new WeakMap<object, object>();\n\n/**\n * Wrap the `run` method of the Workers AI binding with Sentry tracing.\n */\nfunction instrumentRun(\n originalRun: (...args: unknown[]) => Promise<unknown>,\n context: unknown,\n options: WorkersAiOptions,\n): (...args: unknown[]) => Promise<unknown> {\n return function instrumentedRun(...args: unknown[]): Promise<unknown> {\n if (shouldSkipAiProviderSpan(WORKERS_AI_INTEGRATION_NAME)) {\n return originalRun.apply(context, args);\n }\n\n const [model, inputs, runOptions] = args as [unknown, unknown, Record<string, unknown> | undefined];\n\n const operationName = getOperationName(model, inputs);\n const call: WorkersAiCallInfo = { operation: operationName, model, inputs, options: runOptions };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n const requestAttributes = extractRequestAttributes(model, inputs, operationName);\n const modelName = typeof model === 'string' && model ? model : 'unknown';\n const abortSignal = getRequestSignal(runOptions);\n const client = getClient();\n\n const isStreamRequested =\n !!inputs && typeof inputs === 'object' && (inputs as { stream?: unknown }).stream === true;\n const returnsRawResponse =\n !!runOptions &&\n typeof runOptions === 'object' &&\n (runOptions.returnRawResponse === true || runOptions.websocket === true);\n\n const spanConfig = {\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name:\n modelName !== 'unknown' || !(client && hasSpanStreamingEnabled(client))\n ? `${operationName} ${modelName}`\n : operationName,\n attributes: {\n [SENTRY_OP]: WORKERS_AI_OPERATION_SPAN_OPS[operationName],\n ...requestAttributes,\n },\n };\n\n if (isStreamRequested && !returnsRawResponse) {\n return startSpanManual(spanConfig, (span: Span) => {\n // `startSpanManual` does not auto-end the span, so we must end it on every exit path,\n // including a synchronous throw from `run`.\n const handleError = (error: unknown): never => {\n span.setStatus(getErrorStatus(abortSignal));\n runGenAiSpanEnd(options, span, call, { error });\n span.end();\n throw error;\n };\n\n let originalResult: Promise<unknown>;\n\n try {\n originalResult = originalRun.apply(context, args) as Promise<unknown>;\n } catch (error) {\n return handleError(error);\n }\n\n if (recordInputs) {\n addRequestAttributes(span, inputs, operationName);\n }\n runGenAiSpanStart(options, span, call);\n\n return originalResult.then(result => {\n if (isReadableStream<Uint8Array>(result)) {\n return instrumentWorkersAiStream(result, span, recordOutputs, abortSignal, streamResult =>\n runGenAiSpanEnd(options, span, call, streamResult),\n );\n }\n\n // The model did not actually return a stream — finalize the span eagerly.\n addResponseAttributes(span, result, recordOutputs, operationName);\n runGenAiSpanEnd(options, span, call, { response: result });\n span.end();\n return result;\n }, handleError);\n });\n }\n\n return startSpan(spanConfig, (span: Span) => {\n const originalResult = originalRun.apply(context, args) as Promise<unknown>;\n\n if (recordInputs) {\n addRequestAttributes(span, inputs, operationName);\n }\n runGenAiSpanStart(options, span, call);\n\n return originalResult.then(\n result => {\n if (!returnsRawResponse) {\n addResponseAttributes(span, result, recordOutputs, operationName);\n }\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}\n\n/**\n * Instrument a Cloudflare Workers AI binding (`env.AI`) with Sentry tracing.\n *\n * This wraps the binding's `run` method to create `gen_ai` spans following the\n * Sentry AI Agents conventions. All other methods are passed through untouched.\n *\n * In `@sentry/cloudflare`, the `env.AI` binding is instrumented automatically —\n * wrapping manually is only needed to pass custom options.\n *\n * @example\n * ```javascript\n * const ai = Sentry.instrumentWorkersAiClient(env.AI, { recordInputs: true, recordOutputs: true });\n * const result = await ai.run('@cf/meta/llama-3.1-8b-instruct', { prompt: 'Hello' });\n * ```\n */\nexport function instrumentWorkersAiClient<T extends object>(client: T, options?: WorkersAiOptions): T {\n // `@sentry/cloudflare` already wraps `env.AI`. Wrapping that proxy again would nest a second span\n // that ignores these options, so wrap the original binding instead.\n const original = (originalClients.get(client) ?? client) as T;\n\n const instrumented = new Proxy(original, {\n get(target: object, prop: string | symbol, receiver: unknown): unknown {\n const value = Reflect.get(target, prop, receiver);\n\n if (prop === 'run' && typeof value === 'function') {\n return instrumentRun(value as (...args: unknown[]) => Promise<unknown>, target, options ?? {});\n }\n\n // Bind passed-through functions to the original target to preserve `this` (e.g. private fields).\n return typeof value === 'function' ? (value as (...args: unknown[]) => unknown).bind(target) : value;\n },\n }) as T;\n\n originalClients.set(instrumented, original);\n return instrumented;\n}\n","export const LANGCHAIN_INTEGRATION_NAME = 'LangChain' as const;\nexport const LANGCHAIN_ORIGIN = 'auto.ai.langchain';\n// Matches `MAX_TRACKED_FLUE_SPANS`: LangChain skips the end callbacks when a consumer abandons a stream.\nexport const MAX_TRACKED_LANGCHAIN_RUNS = 1000;\n\nexport const ROLE_MAP: Record<string, string> = {\n human: 'user',\n ai: 'assistant',\n assistant: 'assistant',\n system: 'system',\n function: 'function',\n tool: 'tool',\n};\n","/* eslint-disable max-lines */\n/* eslint-disable typescript-eslint/no-deprecated */\nimport { isObjectLike, stringify } from '@sentry/core';\nimport type { SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_AGENT_NAME,\n GEN_AI_CONVERSATION_ID,\n GEN_AI_INPUT_MESSAGES,\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_PRESENCE_PENALTY,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_REQUEST_TOP_P,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_REQUEST_STREAM_ATTRIBUTE, GEN_AI_RESPONSE_STOP_REASON_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport { extractSystemInstructions, getTokenUsageAttributes } from '../core/utils';\nimport type { GenAiOptions } from '../core/utils';\nimport { LANGCHAIN_ORIGIN, ROLE_MAP } from './constants';\nimport type { LangChainLLMResult, LangChainMessage, LangChainSerialized } from './types';\n\n/**\n * Assigns an attribute only when the value is neither `undefined` nor `null`.\n *\n * We keep this tiny helper because call sites are repetitive and easy to miswrite.\n * It also preserves falsy-but-valid values like `0` and `\"\"`.\n */\nconst setIfDefined = (target: Record<string, SpanAttributeValue | undefined>, key: string, value: unknown): void => {\n if (value != null) target[key] = value as SpanAttributeValue;\n};\n\n/**\n * Like `setIfDefined`, but converts the value with `Number()` and skips only when the\n * result is `NaN`. This ensures numeric 0 makes it through (unlike truthy checks).\n */\nconst setNumberIfDefined = (\n target: Record<string, SpanAttributeValue | undefined>,\n key: string,\n value: unknown,\n): void => {\n const n = Number(value);\n if (!Number.isNaN(n)) target[key] = n;\n};\n\n/**\n * Normalizes a single role token to our canonical set.\n *\n * @param role Incoming role value (free-form, any casing)\n * @returns Canonical role: 'user' | 'assistant' | 'system' | 'function' | 'tool' | <passthrough>\n */\nfunction normalizeMessageRole(role: string): string {\n const normalized = role.toLowerCase();\n return ROLE_MAP[normalized] ?? normalized;\n}\n\n/**\n * Infers a role from a LangChain message constructor name.\n *\n * Checks for substrings like \"System\", \"Human\", \"AI\", etc.\n */\nfunction normalizeRoleNameFromCtor(name: string): string {\n if (name.includes('System')) return 'system';\n if (name.includes('Human')) return 'user';\n if (name.includes('AI') || name.includes('Assistant')) return 'assistant';\n if (name.includes('Function')) return 'function';\n if (name.includes('Tool')) return 'tool';\n return 'user';\n}\n\n/**\n * Returns invocation params from a LangChain `tags` object.\n *\n * LangChain often passes runtime parameters (model, temperature, etc.) via the\n * `tags.invocation_params` bag. If `tags` is an array (LangChain sometimes uses\n * string tags), we return `undefined`.\n *\n * @param tags LangChain tags (string[] or record)\n * @returns The `invocation_params` object, if present\n */\nexport function getInvocationParams(tags?: string[] | Record<string, unknown>): Record<string, unknown> | undefined {\n if (!tags || Array.isArray(tags)) return undefined;\n return tags.invocation_params as Record<string, unknown> | undefined;\n}\n\n/**\n * Normalizes a heterogeneous set of LangChain messages to `{ role, content }`.\n *\n * Why so many branches? LangChain messages can arrive in several shapes:\n * - Message classes with `_getType()` (most reliable)\n * - Classes with meaningful constructor names (e.g. `SystemMessage`)\n * - Plain objects with `type`, or `{ role, content }`\n * - Serialized format with `{ lc: 1, id: [...], kwargs: { content } }`\n * We preserve the prioritization to minimize behavioral drift.\n *\n * @param messages Mixed LangChain messages\n * @returns Array of normalized `{ role, content }`\n */\nexport function normalizeLangChainMessages(\n messages: LangChainMessage[],\n): Array<{ role: string; content: string | undefined }> {\n return messages.map(message => {\n // 1) Prefer _getType() when present\n const maybeGetType = (message as { _getType?: () => string })._getType;\n if (typeof maybeGetType === 'function') {\n const messageType = maybeGetType.call(message);\n return {\n role: normalizeMessageRole(messageType),\n content: stringify(message.content, String),\n };\n }\n\n // 2) Serialized LangChain format (lc: 1) - check before constructor name\n // This is more reliable than constructor.name which can be lost during serialization\n if (message.lc === 1 && message.kwargs) {\n const id = message.id;\n const messageType = Array.isArray(id) && id.length > 0 ? id[id.length - 1] : '';\n const role = typeof messageType === 'string' ? normalizeRoleNameFromCtor(messageType) : 'user';\n\n return {\n role: normalizeMessageRole(role),\n content: stringify(message.kwargs?.content, String),\n };\n }\n\n // 3) Then objects with `type`\n if (message.type) {\n const role = String(message.type).toLowerCase();\n return {\n role: normalizeMessageRole(role),\n content: stringify(message.content, String),\n };\n }\n\n // 4) Then objects with `{ role, content }` - check before constructor name\n // Plain objects have constructor.name=\"Object\" which would incorrectly default to \"user\"\n if (message.role) {\n return {\n role: normalizeMessageRole(String(message.role)),\n content: stringify(message.content, String),\n };\n }\n\n // 5) Then try constructor name (SystemMessage / HumanMessage / ...)\n // Only use this if we haven't matched a more specific case\n const ctor = (message as { constructor?: { name?: string } }).constructor?.name;\n if (ctor && ctor !== 'Object') {\n return {\n role: normalizeMessageRole(normalizeRoleNameFromCtor(ctor)),\n content: stringify(message.content, String),\n };\n }\n\n // 6) Fallback: treat as user text\n return {\n role: 'user',\n content: stringify(message.content, String),\n };\n });\n}\n\n/**\n * Extracts request attributes common to both LLM and ChatModel invocations.\n *\n * Source precedence:\n * 1) `invocationParams` (highest)\n * 2) `langSmithMetadata`\n *\n * Numeric values are set even when 0 (e.g. `temperature: 0`), but skipped if `NaN`.\n */\nfunction extractCommonRequestAttributes(\n serialized: LangChainSerialized,\n invocationParams?: Record<string, unknown>,\n langSmithMetadata?: Record<string, unknown>,\n): Record<string, SpanAttributeValue> {\n const attrs: Record<string, SpanAttributeValue> = {};\n\n // Get kwargs if available (from constructor type)\n const kwargs = 'kwargs' in serialized ? serialized.kwargs : undefined;\n\n const temperature = invocationParams?.temperature ?? langSmithMetadata?.ls_temperature ?? kwargs?.temperature;\n setNumberIfDefined(attrs, GEN_AI_REQUEST_TEMPERATURE, temperature);\n\n const maxTokens = invocationParams?.max_tokens ?? langSmithMetadata?.ls_max_tokens ?? kwargs?.max_tokens;\n setNumberIfDefined(attrs, GEN_AI_REQUEST_MAX_TOKENS, maxTokens);\n\n const topP = invocationParams?.top_p ?? kwargs?.top_p;\n setNumberIfDefined(attrs, GEN_AI_REQUEST_TOP_P, topP);\n\n const frequencyPenalty = invocationParams?.frequency_penalty;\n setNumberIfDefined(attrs, GEN_AI_REQUEST_FREQUENCY_PENALTY, frequencyPenalty);\n\n const presencePenalty = invocationParams?.presence_penalty;\n setNumberIfDefined(attrs, GEN_AI_REQUEST_PRESENCE_PENALTY, presencePenalty);\n\n // LangChain uses `stream`. We only set the attribute if the key actually exists\n // (some callbacks report `false` even on streamed requests, this stems from LangChain's callback handler).\n if (invocationParams && 'stream' in invocationParams) {\n setIfDefined(attrs, GEN_AI_REQUEST_STREAM_ATTRIBUTE, Boolean(invocationParams.stream));\n }\n\n return attrs;\n}\n\n/**\n * Small helper to assemble boilerplate attributes shared by both request extractors.\n * Always uses 'chat' as the operation type for all LLM and chat model operations.\n */\nfunction baseRequestAttributes(\n system: unknown,\n modelName: unknown,\n serialized: LangChainSerialized,\n invocationParams?: Record<string, unknown>,\n langSmithMetadata?: Record<string, unknown>,\n): Record<string, SpanAttributeValue | undefined> {\n return {\n [GEN_AI_PROVIDER_NAME]: stringify(system ?? 'langchain', String),\n [GEN_AI_OPERATION_NAME]: 'chat',\n [GEN_AI_REQUEST_MODEL]: stringify(modelName, String),\n [SENTRY_ORIGIN]: LANGCHAIN_ORIGIN,\n ...extractCommonRequestAttributes(serialized, invocationParams, langSmithMetadata),\n };\n}\n\n/**\n * Extracts attributes for plain LLM invocations (string prompts).\n *\n * - Operation is tagged as `chat` following OpenTelemetry semantic conventions.\n * LangChain LLM operations are treated as chat operations.\n * - When `recordInputs` is true, string prompts are wrapped into `{role:\"user\"}`\n * messages to align with the chat schema used elsewhere.\n */\nexport function extractLLMRequestAttributes(\n llm: LangChainSerialized,\n prompts: string[],\n recordInputs: boolean,\n invocationParams?: Record<string, unknown>,\n langSmithMetadata?: Record<string, unknown>,\n): Record<string, SpanAttributeValue | undefined> {\n const system = langSmithMetadata?.ls_provider;\n const modelName = invocationParams?.model ?? langSmithMetadata?.ls_model_name ?? 'unknown';\n\n const attrs = baseRequestAttributes(system, modelName, llm, invocationParams, langSmithMetadata);\n\n if (recordInputs && Array.isArray(prompts) && prompts.length > 0) {\n const messages = prompts.map(p => ({ role: 'user', content: p }));\n setIfDefined(attrs, GEN_AI_INPUT_MESSAGES, stringify(messages));\n }\n\n return attrs;\n}\n\n/**\n * Extracts attributes for ChatModel invocations (array-of-arrays of messages).\n *\n * - Operation is tagged as `chat` following OpenTelemetry semantic conventions.\n * LangChain chat model operations are chat operations.\n * - We flatten LangChain's `LangChainMessage[][]` and normalize shapes into a\n * consistent `{ role, content }` array when `recordInputs` is true.\n * - Provider system value falls back to `serialized.id?.[2]`.\n */\nexport function extractChatModelRequestAttributes(\n llm: LangChainSerialized,\n langChainMessages: LangChainMessage[][],\n recordInputs: boolean,\n invocationParams?: Record<string, unknown>,\n langSmithMetadata?: Record<string, unknown>,\n): Record<string, SpanAttributeValue | undefined> {\n const system = langSmithMetadata?.ls_provider ?? llm.id?.[2];\n const modelName = invocationParams?.model ?? langSmithMetadata?.ls_model_name ?? 'unknown';\n\n const attrs = baseRequestAttributes(system, modelName, llm, invocationParams, langSmithMetadata);\n\n if (recordInputs && Array.isArray(langChainMessages) && langChainMessages.length > 0) {\n const normalized = normalizeLangChainMessages(langChainMessages.flat());\n\n const { systemInstructions, filteredMessages } = extractSystemInstructions(normalized);\n\n if (systemInstructions) {\n setIfDefined(attrs, GEN_AI_SYSTEM_INSTRUCTIONS, systemInstructions);\n }\n\n setIfDefined(attrs, GEN_AI_INPUT_MESSAGES, stringify(filteredMessages));\n }\n\n return attrs;\n}\n\n/**\n * Extracts tool calls from generations and records them on the span attributes.\n * Prefers message.tool_calls (LangChain's normalized format). Falls back to\n * scanning message.content for Anthropic-style tool_use items in older versions\n * where tool_calls may not be populated.\n */\nfunction addToolCallsAttributes(generations: LangChainMessage[][], attrs: Record<string, SpanAttributeValue>): void {\n const toolCalls: unknown[] = [];\n const flatGenerations = generations.flat();\n\n for (const gen of flatGenerations) {\n const msg = gen.message as Record<string, unknown> | undefined;\n const msgToolCalls = msg?.tool_calls as unknown[] | undefined;\n if (Array.isArray(msgToolCalls) && msgToolCalls.length > 0) {\n toolCalls.push(...msgToolCalls);\n } else {\n // Fallback for older LangChain versions: scan message.content for Anthropic-style tool_use\n const content = gen.message?.content;\n if (Array.isArray(content)) {\n for (const item of content) {\n const t = item as Record<string, unknown>;\n if (t.type === 'tool_use') toolCalls.push(t);\n }\n }\n }\n }\n\n if (toolCalls.length > 0) {\n setIfDefined(attrs, GEN_AI_RESPONSE_TOOL_CALLS, stringify(toolCalls, String));\n }\n}\n\nexport function extractMessageTokenUsageAttributes(message: LangChainMessage): Record<string, number> {\n const usage = message.usage_metadata;\n if (isObjectLike(usage)) {\n const details = isObjectLike(usage.input_token_details) ? usage.input_token_details : undefined;\n return getTokenUsageAttributes(\n usage.input_tokens,\n usage.output_tokens,\n details?.cache_creation,\n details?.cache_read,\n usage.total_tokens,\n );\n }\n\n const metadata = message.response_metadata;\n const tokenUsage = isObjectLike(metadata) && isObjectLike(metadata.tokenUsage) ? metadata.tokenUsage : undefined;\n return getTokenUsageAttributes(\n tokenUsage?.promptTokens,\n tokenUsage?.completionTokens,\n undefined,\n undefined,\n tokenUsage?.totalTokens,\n );\n}\n\nfunction addTokenUsageAttributes(llmResult: LangChainLLMResult, attrs: Record<string, SpanAttributeValue>): void {\n const normalizedUsage: Record<string, number> = {};\n const legacyMessageUsage: Record<string, number> = {};\n for (const generations of llmResult.generations ?? []) {\n // Candidate messages share the usage totals for their prompt.\n const message = generations[0]?.message;\n if (message) {\n const usage = isObjectLike(message.usage_metadata) ? normalizedUsage : legacyMessageUsage;\n for (const [key, value] of Object.entries(extractMessageTokenUsageAttributes(message))) {\n usage[key] = (usage[key] ?? 0) + value;\n }\n }\n }\n Object.assign(attrs, Object.keys(normalizedUsage).length > 0 ? normalizedUsage : legacyMessageUsage);\n\n const llmOutput = llmResult.llmOutput;\n if (!llmOutput) return;\n\n const tokenUsage = llmOutput.tokenUsage;\n const anthropicUsage = llmOutput.usage as\n | {\n input_tokens?: number;\n output_tokens?: number;\n cache_creation_input_tokens?: number;\n cache_read_input_tokens?: number;\n }\n | undefined;\n\n // llmOutput.tokenUsage can contain only the final stream chunk's counters.\n if (anthropicUsage && Object.keys(normalizedUsage).length === 0 && Object.keys(legacyMessageUsage).length === 0) {\n const { input_tokens, output_tokens, cache_creation_input_tokens, cache_read_input_tokens } = anthropicUsage;\n const hasInput =\n input_tokens !== undefined || cache_creation_input_tokens !== undefined || cache_read_input_tokens !== undefined;\n Object.assign(\n attrs,\n getTokenUsageAttributes(\n hasInput\n ? (input_tokens ?? 0) + (cache_creation_input_tokens ?? 0) + (cache_read_input_tokens ?? 0)\n : undefined,\n output_tokens,\n cache_creation_input_tokens,\n cache_read_input_tokens,\n ),\n );\n } else if (tokenUsage && Object.keys(normalizedUsage).length === 0 && Object.keys(legacyMessageUsage).length === 0) {\n Object.assign(\n attrs,\n getTokenUsageAttributes(\n tokenUsage.promptTokens,\n tokenUsage.completionTokens,\n undefined,\n undefined,\n tokenUsage.totalTokens,\n ),\n );\n }\n if (anthropicUsage) {\n if (\n typeof anthropicUsage.cache_creation_input_tokens === 'number' &&\n !(GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS in attrs)\n ) {\n attrs[GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS] = anthropicUsage.cache_creation_input_tokens;\n }\n if (\n typeof anthropicUsage.cache_read_input_tokens === 'number' &&\n !(GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS in attrs)\n ) {\n attrs[GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS] = anthropicUsage.cache_read_input_tokens;\n }\n }\n}\n\n/**\n * Extracts response-related attributes based on a `LangChainLLMResult`.\n *\n * - Records finish reasons when present on generations (e.g., OpenAI)\n * - When `recordOutputs` is true, captures textual response content and any\n * tool calls.\n * - Also propagates model name (`model_name` or `model`), response `id`, and\n * `stop_reason` (for providers that use it).\n */\nexport function extractLlmResponseAttributes(\n llmResult: LangChainLLMResult,\n recordOutputs: boolean,\n): Record<string, SpanAttributeValue> | undefined {\n if (!llmResult) return;\n\n const attrs: Record<string, SpanAttributeValue> = {};\n\n if (Array.isArray(llmResult.generations)) {\n const finishReasons = llmResult.generations\n .flat()\n .map(g => {\n // v1 uses generationInfo.finish_reason\n if (g.generationInfo?.finish_reason) {\n return g.generationInfo.finish_reason;\n }\n // v0.3+ uses generation_info.finish_reason\n if (g.generation_info?.finish_reason) {\n return g.generation_info.finish_reason;\n }\n return null;\n })\n .filter((r): r is string => typeof r === 'string');\n\n if (finishReasons.length > 0) {\n setIfDefined(attrs, GEN_AI_RESPONSE_FINISH_REASONS, stringify(finishReasons, String));\n }\n\n // Tool calls metadata (names, IDs) are not PII, so capture them regardless of recordOutputs\n addToolCallsAttributes(llmResult.generations as LangChainMessage[][], attrs);\n\n if (recordOutputs) {\n const texts = llmResult.generations\n .flat()\n .map(gen => gen.text ?? gen.message?.content)\n .filter(t => typeof t === 'string');\n\n if (texts.length > 0) {\n setIfDefined(attrs, GEN_AI_RESPONSE_TEXT, stringify(texts, String));\n }\n }\n }\n\n addTokenUsageAttributes(llmResult, attrs);\n\n const llmOutput = llmResult.llmOutput;\n\n // Extract from v1 generations structure if available\n const firstGeneration = llmResult.generations?.[0]?.[0];\n const v1Message = firstGeneration?.message;\n\n // Provider model identifier: `model_name` (OpenAI-style) or `model` (others)\n // v1 stores this in message.response_metadata.model_name\n const modelName = llmOutput?.model_name ?? llmOutput?.model ?? v1Message?.response_metadata?.model_name;\n if (modelName) setIfDefined(attrs, GEN_AI_RESPONSE_MODEL, modelName);\n\n // Response ID: v1 stores this in message.id\n const responseId = llmOutput?.id ?? v1Message?.id;\n if (responseId) {\n setIfDefined(attrs, GEN_AI_RESPONSE_ID, responseId);\n }\n\n // Stop reason: v1 stores this in message.response_metadata.finish_reason\n const stopReason = llmOutput?.stop_reason ?? v1Message?.response_metadata?.finish_reason;\n if (stopReason) {\n setIfDefined(attrs, GEN_AI_RESPONSE_STOP_REASON_ATTRIBUTE, stringify(stopReason, String));\n }\n\n return attrs;\n}\n\nexport function getAgentNameFromMetadata(metadata?: Record<string, unknown>): Record<string, SpanAttributeValue> {\n const attrs: Record<string, SpanAttributeValue> = {};\n // lc_agent_name is injected by the langgraph invoke()/stream() wrappers (`prepareAgentSpan`)\n const agentName = metadata?.lc_agent_name;\n if (typeof agentName === 'string') {\n attrs[GEN_AI_AGENT_NAME] = agentName;\n }\n return attrs;\n}\n\n/**\n * Metadata keys under which LangChain apps carry a conversation id, in order of precedence.\n * `thread_id` is the LangGraph checkpointer key and one of the two keys LangSmith groups threads by,\n * `session_id` is the other, and `sessionId` is what `RunnableWithMessageHistory` requires in JS.\n */\nconst CONVERSATION_ID_METADATA_KEYS = ['thread_id', 'session_id', 'sessionId'] as const;\n\nfunction findConversationIdEntry(source?: Record<string, unknown>): [string, string | number] | undefined {\n for (const key of CONVERSATION_ID_METADATA_KEYS) {\n const value = source?.[key];\n if ((typeof value === 'string' && value) || (typeof value === 'number' && Number.isFinite(value))) {\n return [key, value];\n }\n }\n return undefined;\n}\n\n/**\n * The recording decision of the LangGraph graph run that `metadata` belongs to. The graph's `invoke()`/`stream()`\n * call decides once, and child runs inherit the decision through their metadata.\n */\nexport function getLangGraphRunRecording(metadata?: Record<string, unknown>): Required<GenAiOptions> | undefined {\n const recording = metadata?.__sentry_langgraph__;\n return isObjectLike(recording) ? (recording as Required<GenAiOptions>) : undefined;\n}\n\n/**\n * Derive `gen_ai.conversation.id` from run metadata, which child runs inherit from their parent.\n * An id from `Sentry.setConversationId()` still wins, since `conversationIdIntegration` applies it on `spanStart`.\n */\nexport function getConversationIdFromMetadata(metadata?: Record<string, unknown>): Record<string, SpanAttributeValue> {\n const entry = findConversationIdEntry(metadata);\n return entry ? { [GEN_AI_CONVERSATION_ID]: String(entry[1]) } : {};\n}\n\n/**\n * The conversation id entry from `config.configurable`, to spread under the run metadata.\n * `@langchain/core` >= 1.1.40 only copies `configurable` into metadata for LangSmith tracers, not for our handler.\n */\nexport function getConversationIdMetadataFromConfig(config: Record<string, unknown>): Record<string, unknown> {\n const entry = findConversationIdEntry(config.configurable as Record<string, unknown> | undefined);\n return entry ? { [entry[0]]: entry[1] } : {};\n}\n\nexport function extractToolDefinitions(extraParams?: Record<string, unknown>): string | undefined {\n const tools =\n (extraParams?.invocation_params as Record<string, unknown>)?.tools ??\n (extraParams?.options as Record<string, unknown>)?.tools;\n if (!Array.isArray(tools) || tools.length === 0) return undefined;\n const toolDefs = tools.map((tool: Record<string, unknown>) => {\n const fn = tool.function as Record<string, unknown> | undefined;\n return {\n type: 'function',\n name: tool.name ?? fn?.name ?? '',\n description: tool.description ?? fn?.description,\n };\n });\n return JSON.stringify(toolDefs);\n}\n\n// A run started without config inherits the parent run's config, which LangChain keeps in a global\n// AsyncLocalStorage. `ensureConfig` lets an explicit `callbacks` key replace the inherited one.\nconst LANGCHAIN_ALS_KEY = Symbol.for('ls:tracing_async_local_storage');\nconst LANGCHAIN_CHILD_CONFIG_KEY = Symbol.for('lc:child_config');\n\n/** The callbacks LangChain gives a run started without config: the ones of the parent run, if any. */\nexport function getInheritedLangChainCallbacks(): unknown {\n const storage = (globalThis as Record<symbol, unknown>)[LANGCHAIN_ALS_KEY] as\n | { getStore?: () => unknown }\n | undefined;\n const store = typeof storage?.getStore === 'function' ? storage.getStore() : undefined;\n const extra = isObjectLike(store) ? (store.extra as Record<symbol, unknown> | undefined) : undefined;\n const config = isObjectLike(extra) ? extra[LANGCHAIN_CHILD_CONFIG_KEY] : undefined;\n return isObjectLike(config) ? config.callbacks : undefined;\n}\n\n/** Duck-types a LangChain `CallbackManager` (avoids coupling to a specific `@langchain/core` resolution). */\nfunction isCallbackManager(value: unknown): value is {\n addHandler: (handler: unknown, inherit?: boolean) => void;\n copy: () => unknown;\n handlers?: unknown[];\n} {\n if (!value || typeof value !== 'object') {\n return false;\n }\n const candidate = value as { addHandler?: unknown; copy?: unknown };\n return typeof candidate.addHandler === 'function' && typeof candidate.copy === 'function';\n}\n\nfunction isSentryHandler(handler: unknown): boolean {\n return typeof handler === 'object' && (handler as Record<string, unknown>)?.name === 'SentryCallbackHandler';\n}\n\nfunction containsSentryHandler(handlers: unknown[]): boolean {\n return handlers.some(isSentryHandler);\n}\n\n/**\n * Merge `sentryHandler` into a given set of LangChain callbacks or callback manager.\n * @internal Exported for cross-package instrumentation.\n */\nexport function _INTERNAL_mergeLangChainCallbackHandler(existing: unknown, sentryHandler: unknown): unknown {\n const handlers = isCallbackManager(existing) ? (existing.handlers ?? []) : toHandlerArray(existing);\n return containsSentryHandler(handlers) ? existing : _INTERNAL_addLangChainCallbackHandler(existing, sentryHandler);\n}\n\n/**\n * Add `handler` to a given set of LangChain callbacks or callback manager, without deduplicating it.\n * A callback manager is copied rather than mutated.\n * @internal Exported for cross-package instrumentation.\n */\nexport function _INTERNAL_addLangChainCallbackHandler(existing: unknown, handler: unknown): unknown {\n if (!existing) {\n return [handler];\n }\n\n if (isCallbackManager(existing)) {\n const copied = existing.copy() as { addHandler: (handler: unknown, inherit?: boolean) => void };\n copied.addHandler(handler, true);\n return copied;\n }\n\n return [...toHandlerArray(existing), handler];\n}\n\nfunction toHandlerArray(existing: unknown): unknown[] {\n return Array.isArray(existing) ? existing : existing ? [existing] : [];\n}\n","import { SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport type { Span } from '@sentry/core';\nimport { isObjectLike } from '@sentry/core';\nimport { addResponseAttributes, startDecideSpan } from '../typesafe';\nimport { LANGCHAIN_ORIGIN } from './constants';\nimport { getAgentNameFromMetadata, getConversationIdFromMetadata } from './utils';\n\n// `TypeSafeClassifier` from `@langchain/typesafe` calls Jev with `fetch`, not through `@typesafe-ai/sdk`,\n// so the TypeSafe integration does not see it. Its serialized id is `[...lc_namespace, lc_name()]`; only\n// the class name is matched, as the namespace is the part that changes between versions.\nconst TYPESAFE_CLASSIFIER_NAME = 'TypeSafeClassifier';\n\n/** The package's default, used when the classifier is constructed without a `model`. */\nconst DEFAULT_TYPESAFE_CLASSIFIER_MODEL = 'jev-latest';\n\n// The `state` the classifier sends to Jev (messages rendered as transcript lines), keyed by the input\n// passed to `invoke()`. LangChain hands that same object to `handleChainStart`, so the span records what\n// Jev received rather than LangChain's serialized messages.\nconst wireStates = new WeakMap<object, unknown>();\n\n/** Record the `state` a `TypeSafeClassifier` sends for `input`, using the classifier's own serializer. */\nexport function recordTypeSafeClassifierState(classifier: unknown, input: unknown): void {\n // A string state is sent as is, so there is nothing to record.\n if (!isObjectLike(input) || !isObjectLike(classifier) || typeof classifier.payload !== 'function') {\n return;\n }\n\n try {\n const body: unknown = JSON.parse(classifier.payload(input));\n if (isObjectLike(body)) {\n wireStates.set(input, body.state);\n }\n } catch {\n // The classifier rejects the same input itself; the span keeps LangChain's form of it.\n }\n}\n\n// Typed loosely: LangChain's `Serialized` union does not match our handler's chain type.\nexport function isTypeSafeClassifier(chain: unknown): boolean {\n return isObjectLike(chain) && Array.isArray(chain.id) && chain.id[chain.id.length - 1] === TYPESAFE_CLASSIFIER_NAME;\n}\n\n/** Start a `decide` span for a `TypeSafeClassifier` run, from its serialized constructor arguments. */\nexport function startTypeSafeClassifierSpan(\n chain: unknown,\n inputs: Record<string, unknown>,\n metadata: Record<string, unknown> | undefined,\n recordInputs: boolean,\n): Span {\n const kwargs = isObjectLike(chain) && isObjectLike(chain.kwargs) ? chain.kwargs : {};\n const model = typeof kwargs.model === 'string' ? kwargs.model : DEFAULT_TYPESAFE_CLASSIFIER_MODEL;\n\n return startDecideSpan({ model, state: getState(inputs), questions: kwargs.questions }, undefined, recordInputs, {\n [SENTRY_ORIGIN]: LANGCHAIN_ORIGIN,\n ...getAgentNameFromMetadata(metadata),\n ...getConversationIdFromMetadata(metadata),\n });\n}\n\n/** The classifier result reports usage in camelCase, the TypeSafe helpers read the API's snake_case. */\nexport function addTypeSafeClassifierResponseAttributes(span: Span, outputs: unknown, recordOutputs: boolean): void {\n if (!isObjectLike(outputs)) {\n return;\n }\n\n const usage = isObjectLike(outputs.usage) ? outputs.usage : {};\n addResponseAttributes(\n span,\n {\n model: outputs.model,\n answers: outputs.answers,\n usage: { input_tokens: usage.inputTokens, output_tokens: usage.outputTokens },\n },\n recordOutputs,\n );\n}\n\nfunction getState(inputs: Record<string, unknown>): unknown {\n // LangChain hands a string or array input to callbacks wrapped as `{ input }`.\n const keys = Object.keys(inputs);\n const input = inputs.input;\n const state =\n keys.length === 1 && keys[0] === 'input' && (typeof input === 'string' || Array.isArray(input)) ? input : inputs;\n\n return isObjectLike(state) && wireStates.has(state) ? wireStates.get(state) : state;\n}\n","import { getClient, hasSpanStreamingEnabled, SPAN_STATUS_ERROR, startSpan, stringify } from '@sentry/core';\nimport type { SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_OPERATION_NAME,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_MODEL,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_EMBEDDINGS } from '@sentry/conventions/op';\nimport {\n GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE,\n GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE,\n} from '../core/gen-ai-attributes';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport { resolveGenAiCallRecording } from '../core/utils';\nimport { LANGCHAIN_ORIGIN } from './constants';\nimport type { LangChainEmbeddingsCallInfo, LangChainOptions } from './types';\n\n/**\n * Infers the AI provider system name from the embedding class instance.\n */\nfunction inferSystemFromInstance(instance: Record<string, unknown>): string {\n const name = (instance.constructor as { name?: string })?.name ?? '';\n if (name.includes('OpenAI')) return 'openai';\n if (name.includes('Google')) return 'google_genai';\n if (name.includes('Mistral')) return 'mistralai';\n if (name.includes('Vertex')) return 'google_vertexai';\n if (name.includes('Bedrock')) return 'aws_bedrock';\n if (name.includes('Ollama')) return 'ollama';\n if (name.includes('Cloudflare')) return 'cloudflare';\n if (name.includes('Cohere')) return 'cohere';\n return 'langchain';\n}\n\n/**\n * Extracts span attributes from a LangChain embedding class instance.\n */\nfunction extractEmbeddingAttributes(instance: unknown): Record<string, unknown> {\n const embeddingsInstance = (instance ?? {}) as Record<string, unknown>;\n\n const attributes: Record<string, unknown> = {\n [SENTRY_ORIGIN]: LANGCHAIN_ORIGIN,\n [SENTRY_OP]: GEN_AI_EMBEDDINGS,\n [GEN_AI_OPERATION_NAME]: 'embeddings',\n [GEN_AI_REQUEST_MODEL]: embeddingsInstance.model ?? 'unknown',\n };\n\n attributes[GEN_AI_PROVIDER_NAME] = inferSystemFromInstance(embeddingsInstance);\n if ('dimensions' in embeddingsInstance) {\n attributes[GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE] = embeddingsInstance.dimensions;\n }\n if ('encodingFormat' in embeddingsInstance) {\n attributes[GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE] = embeddingsInstance.encodingFormat;\n }\n\n return attributes;\n}\n\n/**\n * Builds the span options for a LangChain embedding call from the embeddings instance and input.\n *\n * @internal Exported so the diagnostics-channel (orchestrion) instrumentation can build the same\n * span as the prototype-patching path below.\n */\nexport function _INTERNAL_getLangChainEmbeddingsSpanOptions(\n instance: unknown,\n call: LangChainEmbeddingsCallInfo,\n options: LangChainOptions = {},\n): { name: string; attributes: Record<string, SpanAttributeValue> } {\n const { input } = call;\n const { recordInputs } = resolveGenAiCallRecording(options, call);\n const attributes = extractEmbeddingAttributes(instance);\n const modelName = attributes[GEN_AI_REQUEST_MODEL] || 'unknown';\n const client = getClient();\n\n if (recordInputs && input != null) {\n attributes[GEN_AI_EMBEDDINGS_INPUT] = stringify(input, String);\n }\n\n return {\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name:\n (typeof modelName === 'string' && modelName !== 'unknown') || !(client && hasSpanStreamingEnabled(client))\n ? `embeddings ${modelName}`\n : 'embeddings',\n attributes: attributes as Record<string, SpanAttributeValue>,\n };\n}\n\n/**\n * Wraps a LangChain embedding method (embedQuery or embedDocuments) to create Sentry spans.\n *\n * Used internally by the Node.js auto-instrumentation to patch embedding class prototypes.\n */\nexport function instrumentEmbeddingMethod(\n originalMethod: (...args: unknown[]) => Promise<unknown>,\n options: LangChainOptions = {},\n): (...args: unknown[]) => Promise<unknown> {\n return new Proxy(originalMethod, {\n apply(target, thisArg, args: unknown[]): Promise<unknown> {\n const call: LangChainEmbeddingsCallInfo = { operation: 'embeddings', input: args[0] };\n return startSpan(_INTERNAL_getLangChainEmbeddingsSpanOptions(thisArg, call, options), async span => {\n runGenAiSpanStart(options, span, call);\n try {\n const response = await Reflect.apply(target, thisArg, args);\n runGenAiSpanEnd(options, span, call, { response });\n return response;\n } catch (error) {\n // The error is rethrown to the caller, so we only mark the span failed and do not record it.\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n runGenAiSpanEnd(options, span, call, { error });\n throw error;\n }\n });\n },\n });\n}\n\n/**\n * Wraps a LangChain embeddings instance to create Sentry spans for `embedQuery` and `embedDocuments` calls.\n *\n * Use this in non-Node runtimes (Cloudflare, browser, etc.) where auto-instrumentation is not available.\n *\n * @example\n * ```javascript\n * import * as Sentry from '@sentry/cloudflare';\n * import { OpenAIEmbeddings } from '@langchain/openai';\n *\n * const embeddings = Sentry.instrumentLangChainEmbeddings(\n * new OpenAIEmbeddings({ model: 'text-embedding-3-small' })\n * );\n *\n * await embeddings.embedQuery('Hello world');\n * await embeddings.embedDocuments(['doc1', 'doc2']);\n * ```\n */\nexport function instrumentLangChainEmbeddings<T extends object>(instance: T, options?: LangChainOptions): T {\n const embeddingsInstance = instance as Record<string, unknown>;\n\n if (typeof embeddingsInstance.embedQuery === 'function') {\n embeddingsInstance.embedQuery = instrumentEmbeddingMethod(\n embeddingsInstance.embedQuery as (...args: unknown[]) => Promise<unknown>,\n options,\n );\n }\n\n if (typeof embeddingsInstance.embedDocuments === 'function') {\n embeddingsInstance.embedDocuments = instrumentEmbeddingMethod(\n embeddingsInstance.embedDocuments as (...args: unknown[]) => Promise<unknown>,\n options,\n );\n }\n\n return instance;\n}\n","/* eslint-disable max-lines */\nimport {\n debug,\n getActiveSpan,\n getClient,\n getRootSpan,\n hasSpanStreamingEnabled,\n LRUMap,\n SPAN_STATUS_ERROR,\n spanIsIgnored,\n spanToJSON,\n startInactiveSpan,\n stringify,\n withActiveSpan,\n} from '@sentry/core';\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_OPERATION_NAME,\n GEN_AI_PIPELINE_NAME,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DEFINITIONS,\n GEN_AI_TOOL_NAME,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_CHAT, GEN_AI_EXECUTE_TOOL, GEN_AI_INVOKE_AGENT } from '@sentry/conventions/op';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { GenAiSpanResult } from '../core/span-hooks';\nimport { resolveGenAiCallRecording } from '../core/utils';\nimport type { GenAiOptions } from '../core/utils';\nimport { recordTimeToFirstChunk } from '../core/time-to-first-chunk';\nimport { LANGCHAIN_ORIGIN, MAX_TRACKED_LANGCHAIN_RUNS } from './constants';\nimport {\n addTypeSafeClassifierResponseAttributes,\n isTypeSafeClassifier,\n startTypeSafeClassifierSpan,\n} from './typesafe-classifier';\nimport type {\n LangChainCallbackHandler,\n LangChainCallInfo,\n LangChainLLMResult,\n LangChainMessage,\n LangChainOptions,\n LangChainSerialized,\n} from './types';\nimport {\n extractChatModelRequestAttributes,\n extractLLMRequestAttributes,\n extractLlmResponseAttributes,\n extractToolDefinitions,\n getAgentNameFromMetadata,\n getConversationIdFromMetadata,\n getInvocationParams,\n getLangGraphRunRecording,\n} from './utils';\n\ntype LangChainRunCallInfo = Exclude<LangChainCallInfo, { operation: 'embeddings' }>;\n\ninterface LangChainRun {\n span: Span;\n call: LangChainRunCallInfo;\n // The span active when the run started, to tell whether a span was opened inside the run since.\n activeSpan?: Span;\n conversationId?: string;\n decide?: boolean;\n recordOutputs: boolean;\n}\n\n/**\n * Creates a Sentry callback handler for LangChain\n * Returns a plain object that LangChain will call via duck-typing\n *\n * This is a stateful handler that tracks spans across multiple LangChain executions.\n */\nexport function createLangChainCallbackHandler(options: LangChainOptions = {}): LangChainCallbackHandler {\n const resolveRecording = (call: LangChainRunCallInfo): Required<GenAiOptions> =>\n getLangGraphRunRecording(call.metadata) ?? resolveGenAiCallRecording(options, call);\n\n // Internal state - single instance tracks all spans\n const runs = new LRUMap<string, LangChainRun>(MAX_TRACKED_LANGCHAIN_RUNS);\n const getRun = (runId: string | undefined): LangChainRun | undefined => (runId ? runs.get(runId) : undefined);\n\n /**\n * Exit a span and clean up\n */\n const exitSpan = (runId: string, result: GenAiSpanResult<unknown> = {}): void => {\n const run = runs.remove(runId);\n if (run?.span.isRecording()) {\n runGenAiSpanEnd(options, run.span, run.call, result);\n run.span.end();\n }\n };\n\n // `LRUMap.set` would drop the oldest run without ending its span, so it is ended first, like Flue and Mastra.\n let warnedFull = false;\n const trackRun = (runId: string, run: LangChainRun): void => {\n if (runs.size >= MAX_TRACKED_LANGCHAIN_RUNS) {\n if (!warnedFull) {\n warnedFull = true;\n DEBUG_BUILD &&\n debug.warn(\n `[LangChain] More than ${MAX_TRACKED_LANGCHAIN_RUNS} runs are open, ending the oldest. Its span may be cut short.`,\n );\n }\n const oldestRunId = runs.keys()[0];\n if (oldestRunId !== undefined) {\n exitSpan(oldestRunId);\n }\n }\n runs.set(runId, run);\n };\n\n // Nearest first. `LRUMap.get()` marks each run recently used, so a long-running root run is not evicted while\n // its subtree is busy.\n const getAncestors = (parentRunId: string | undefined): LangChainRun[] => {\n const ancestors: LangChainRun[] = [];\n for (let run = getRun(parentRunId); run; run = getRun(run.call.parentRunId)) {\n ancestors.push(run);\n }\n return ancestors;\n };\n\n // LangChain never makes our run spans active, so a run starts under its nearest ancestor run span. Like core,\n // an ignored span only parents when it is a root, which drops its subtree. The active span stays the parent\n // if the ancestor run has no span, or if another span was opened since that run started.\n const getParentRunSpan = (ancestors: LangChainRun[], activeSpan: Span | undefined): Span | undefined => {\n for (const run of ancestors) {\n if (run.activeSpan !== activeSpan) {\n return undefined;\n }\n if (!spanIsIgnored(run.span) || getRootSpan(run.span) === run.span) {\n return run.span;\n }\n }\n return undefined;\n };\n\n const startRunSpan = (call: LangChainRunCallInfo, recordOutputs: boolean, start: () => Span): LangChainRun => {\n const { runId, parentRunId } = call;\n const ancestors = getAncestors(parentRunId);\n const activeSpan = getActiveSpan();\n const parentSpan = getParentRunSpan(ancestors, activeSpan);\n const span = parentSpan ? withActiveSpan(parentSpan, start) : start();\n\n // `@langchain/core` >= 1.1.40 keeps `configurable` out of run metadata, so often only the chat span knows\n // the conversation id. The own id is read off the span, since one from `Sentry.setConversationId()` is\n // only set there.\n const ownId = spanToJSON(span).attributes[GEN_AI_CONVERSATION_ID];\n const conversationId = typeof ownId === 'string' ? ownId : ancestors[0]?.conversationId;\n if (conversationId && conversationId !== ownId) {\n span.setAttribute(GEN_AI_CONVERSATION_ID, conversationId);\n }\n\n const run: LangChainRun = { span, call, activeSpan, conversationId, recordOutputs };\n trackRun(runId, run);\n if (conversationId) {\n for (const ancestor of ancestors) {\n if (ancestor.conversationId) {\n break;\n }\n ancestor.conversationId = conversationId;\n ancestor.span.setAttribute(GEN_AI_CONVERSATION_ID, conversationId);\n }\n }\n runGenAiSpanStart(options, span, call);\n return run;\n };\n\n /**\n * Handler for LLM Start\n * This handler will be called by LangChain's callback handler when an LLM event is detected.\n */\n const handler: LangChainCallbackHandler = {\n // Required LangChain BaseCallbackHandler properties\n lc_serializable: false,\n lc_namespace: ['langchain_core', 'callbacks', 'sentry'],\n lc_secrets: undefined,\n lc_attributes: undefined,\n lc_aliases: undefined,\n lc_serializable_keys: undefined,\n lc_id: ['langchain_core', 'callbacks', 'sentry'],\n lc_kwargs: {},\n name: 'SentryCallbackHandler',\n\n // BaseCallbackHandlerInput boolean flags\n ignoreLLM: false,\n ignoreChain: false,\n ignoreAgent: false,\n ignoreRetriever: false,\n ignoreCustomEvent: false,\n raiseError: false,\n awaitHandlers: true,\n\n handleLLMStart(\n llm: unknown,\n prompts: string[],\n runId: string,\n parentRunId?: string,\n extraParams?: Record<string, unknown>,\n tags?: string[],\n metadata?: Record<string, unknown>,\n _runName?: string,\n ) {\n const serialized = llm as LangChainSerialized;\n const call: LangChainRunCallInfo = {\n operation: 'chat',\n serialized,\n prompts,\n runId,\n parentRunId,\n extraParams,\n tags,\n metadata,\n };\n const { recordInputs, recordOutputs } = resolveRecording(call);\n const invocationParams = getInvocationParams(tags);\n const attributes = extractLLMRequestAttributes(serialized, prompts, recordInputs, invocationParams, metadata);\n const modelName = attributes[GEN_AI_REQUEST_MODEL] || 'unknown';\n const operationName =\n typeof attributes[GEN_AI_OPERATION_NAME] === 'string' ? attributes[GEN_AI_OPERATION_NAME] : 'unknown';\n const client = getClient();\n\n startRunSpan(call, recordOutputs, () =>\n startInactiveSpan({\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name:\n (typeof modelName === 'string' && modelName !== 'unknown') || !(client && hasSpanStreamingEnabled(client))\n ? `${operationName} ${modelName}`\n : operationName,\n attributes: {\n ...getAgentNameFromMetadata(metadata),\n ...getConversationIdFromMetadata(metadata),\n ...attributes,\n [SENTRY_OP]: GEN_AI_CHAT,\n },\n }),\n );\n },\n\n // Chat Model Start Handler\n handleChatModelStart(\n llm: unknown,\n messages: unknown,\n runId: string,\n parentRunId?: string,\n extraParams?: Record<string, unknown>,\n tags?: string[],\n metadata?: Record<string, unknown>,\n _runName?: string,\n ) {\n const serialized = llm as LangChainSerialized;\n const chatMessages = messages as LangChainMessage[][];\n const call: LangChainRunCallInfo = {\n operation: 'chat',\n serialized,\n messages: chatMessages,\n runId,\n parentRunId,\n extraParams,\n tags,\n metadata,\n };\n const { recordInputs, recordOutputs } = resolveRecording(call);\n const invocationParams = getInvocationParams(tags);\n const attributes = extractChatModelRequestAttributes(\n serialized,\n chatMessages,\n recordInputs,\n invocationParams,\n metadata,\n );\n\n const toolDefsJson = recordInputs ? extractToolDefinitions(extraParams) : undefined;\n if (toolDefsJson) {\n attributes[GEN_AI_TOOL_DEFINITIONS] = toolDefsJson;\n }\n\n const modelName = attributes[GEN_AI_REQUEST_MODEL] || 'unknown';\n const operationName =\n typeof attributes[GEN_AI_OPERATION_NAME] === 'string' ? attributes[GEN_AI_OPERATION_NAME] : 'unknown';\n const client = getClient();\n\n startRunSpan(call, recordOutputs, () =>\n startInactiveSpan({\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name:\n (typeof modelName === 'string' && modelName !== 'unknown') || !(client && hasSpanStreamingEnabled(client))\n ? `${operationName} ${modelName}`\n : operationName,\n attributes: {\n ...getAgentNameFromMetadata(metadata),\n ...getConversationIdFromMetadata(metadata),\n ...attributes,\n [SENTRY_OP]: GEN_AI_CHAT,\n },\n }),\n );\n },\n\n // Called for each streamed chunk.\n handleLLMNewToken(_token: string, _idx: unknown, runId: string) {\n const span = runs.get(runId)?.span;\n if (span) {\n recordTimeToFirstChunk(span);\n }\n },\n\n // LLM End Handler - note: handleLLMEnd with capital LLM (used by both LLMs and chat models!)\n handleLLMEnd(\n output: unknown,\n runId: string,\n _parentRunId?: string,\n _tags?: string[],\n _extraParams?: Record<string, unknown>,\n ) {\n const run = runs.get(runId);\n const span = run?.span;\n if (run && span?.isRecording()) {\n const attributes = extractLlmResponseAttributes(output as LangChainLLMResult, run.recordOutputs);\n if (attributes) {\n span.setAttributes(attributes);\n }\n }\n exitSpan(runId, { response: output });\n },\n\n // LLM Error Handler - note: handleLLMError with capital LLM\n handleLLMError(error: Error, runId: string) {\n // The error is surfaced to the caller (invoke() rejects), so we only mark the span failed and\n // do not record it.\n const span = runs.get(runId)?.span;\n if (span?.isRecording()) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n exitSpan(runId, { error });\n },\n\n // Chain Start Handler\n handleChainStart(\n chain: { name?: string },\n inputs: Record<string, unknown>,\n runId: string,\n parentRunId?: string,\n tags?: string[],\n metadata?: Record<string, unknown>,\n _runType?: string,\n runName?: string,\n ) {\n // A Jev call is a real model call, so it is recorded inside an agent too.\n if (isTypeSafeClassifier(chain)) {\n const call: LangChainRunCallInfo = {\n operation: 'decide',\n serialized: chain,\n inputs,\n runId,\n parentRunId,\n tags,\n metadata,\n };\n const { recordInputs, recordOutputs } = resolveRecording(call);\n startRunSpan(call, recordOutputs, () =>\n startTypeSafeClassifierSpan(chain, inputs, metadata, recordInputs),\n ).decide = true;\n return;\n }\n\n // Skip chain spans when inside an agent context (createReactAgent).\n // The agent already creates an invoke_agent span; internal chain steps\n // (ChannelWrite, Branch, prompt, etc.) are noise.\n if (metadata?.__sentry_langgraph__) {\n return;\n }\n\n const call: LangChainRunCallInfo = {\n operation: 'invoke_agent',\n serialized: chain,\n inputs,\n runId,\n parentRunId,\n tags,\n metadata,\n };\n const { recordInputs, recordOutputs } = resolveRecording(call);\n const chainName = runName || chain.name;\n const attributes: Record<string, SpanAttributeValue> = {\n ...getConversationIdFromMetadata(metadata),\n [SENTRY_ORIGIN]: 'auto.ai.langchain',\n [GEN_AI_OPERATION_NAME]: 'invoke_agent',\n };\n\n if (chainName) {\n attributes[GEN_AI_PIPELINE_NAME] = chainName;\n }\n\n if (recordInputs) {\n attributes['langchain.chain.inputs'] = JSON.stringify(inputs);\n }\n\n const client = getClient();\n\n startRunSpan(call, recordOutputs, () =>\n startInactiveSpan({\n // With span streaming, the name leads with the operation per the agent templates. The\n // chain name is bounded, so it stays; the `'unknown_chain'` sentinel is dropped instead.\n name: !(client && hasSpanStreamingEnabled(client))\n ? `chain ${chainName || 'unknown_chain'}`\n : chainName\n ? `invoke_agent ${chainName}`\n : 'invoke_agent',\n attributes: {\n ...attributes,\n [SENTRY_OP]: GEN_AI_INVOKE_AGENT,\n },\n }),\n );\n },\n\n // Chain End Handler\n handleChainEnd(outputs: unknown, runId: string) {\n const run = runs.get(runId);\n const span = run?.span;\n if (run && span?.isRecording()) {\n if (run.decide) {\n addTypeSafeClassifierResponseAttributes(span, outputs, run.recordOutputs);\n } else if (run.recordOutputs) {\n span.setAttributes({\n 'langchain.chain.outputs': JSON.stringify(outputs),\n });\n }\n }\n exitSpan(runId, { response: outputs });\n },\n\n // Chain Error Handler\n handleChainError(error: Error, runId: string) {\n // The error is surfaced to the caller (invoke() rejects), so we only mark the span failed and\n // do not record it.\n const span = runs.get(runId)?.span;\n if (span?.isRecording()) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n exitSpan(runId, { error });\n },\n\n // Tool Start Handler\n handleToolStart(\n tool: { name?: string },\n input: string,\n runId: string,\n parentRunId?: string,\n tags?: string[],\n metadata?: Record<string, unknown>,\n runName?: string,\n ) {\n // Skip tool spans when inside an agent context (createReactAgent).\n // Tool spans are created by wrapToolsWithSpans with richer attributes.\n if (metadata?.__sentry_langgraph__) {\n return;\n }\n\n const call: LangChainRunCallInfo = {\n operation: 'execute_tool',\n serialized: tool,\n input,\n runId,\n parentRunId,\n tags,\n metadata,\n };\n const { recordInputs, recordOutputs } = resolveRecording(call);\n // runName is set to tool.name by LangChain's StructuredTool.call()\n const toolName = runName || tool.name || 'unknown_tool';\n const attributes: Record<string, SpanAttributeValue> = {\n ...getAgentNameFromMetadata(metadata),\n ...getConversationIdFromMetadata(metadata),\n [SENTRY_ORIGIN]: LANGCHAIN_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'execute_tool',\n [GEN_AI_TOOL_NAME]: toolName,\n };\n\n if (recordInputs) {\n attributes[GEN_AI_TOOL_CALL_ARGUMENTS] = input;\n }\n\n startRunSpan(call, recordOutputs, () =>\n startInactiveSpan({\n name: `execute_tool ${toolName}`,\n attributes: {\n ...attributes,\n [SENTRY_OP]: GEN_AI_EXECUTE_TOOL,\n },\n }),\n );\n },\n\n // Tool End Handler\n handleToolEnd(output: unknown, runId: string) {\n const run = runs.get(runId);\n const span = run?.span;\n if (run && span?.isRecording()) {\n if (run.recordOutputs) {\n // LangChain tools may return ToolMessage objects — extract the content\n const outputObj = output as Record<string, unknown> | undefined;\n const content =\n outputObj && typeof outputObj === 'object' && 'content' in outputObj ? outputObj.content : output;\n span.setAttributes({\n [GEN_AI_TOOL_CALL_RESULT]: stringify(content, String),\n });\n }\n }\n exitSpan(runId, { response: output });\n },\n\n // Tool Error Handler\n handleToolError(error: Error, runId: string) {\n // The error is surfaced to the caller (invoke() rejects), so we only mark the span failed and\n // do not record it.\n const span = runs.get(runId)?.span;\n if (span?.isRecording()) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n exitSpan(runId, { error });\n },\n\n // LangChain BaseCallbackHandler required methods\n copy() {\n return handler;\n },\n\n toJSON() {\n return {\n lc: 1,\n type: 'not_implemented',\n id: handler.lc_id,\n };\n },\n\n toJSONNotImplemented() {\n return {\n lc: 1,\n type: 'not_implemented',\n id: handler.lc_id,\n };\n },\n };\n\n return handler;\n}\n\nexport { instrumentLangChainEmbeddings } from './embeddings';\n","export const LANGGRAPH_INTEGRATION_NAME = 'LangGraph' as const;\nexport const LANGGRAPH_ORIGIN = 'auto.ai.langgraph';\n","/* eslint-disable typescript-eslint/no-deprecated */\nimport { SPAN_STATUS_ERROR, startSpan, stringify } from '@sentry/core';\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport {\n GEN_AI_AGENT_NAME,\n GEN_AI_OPERATION_NAME,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DESCRIPTION,\n GEN_AI_TOOL_NAME,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_EXECUTE_TOOL } from '@sentry/conventions/op';\nimport { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport { resolveAIRecordingOptions, setOutputMessagesAttribute } from '../core/utils';\nimport type { GenAiOptions } from '../core/utils';\nimport type { BaseChatModel, LangChainMessage } from '../langchain/types';\nimport {\n extractMessageTokenUsageAttributes,\n getConversationIdFromMetadata,\n getLangGraphRunRecording,\n normalizeLangChainMessages,\n} from '../langchain/utils';\nimport { LANGGRAPH_ORIGIN } from './constants';\nimport type { CompiledGraph, LangGraphOptions, LangGraphTool } from './types';\n\n/**\n * Extract LLM model object from createReactAgent params\n */\nexport function extractLLMFromParams(args: unknown[]): BaseChatModel | null {\n const arg = args[0];\n if (typeof arg !== 'object' || !arg || !('llm' in arg) || !arg.llm || typeof arg.llm !== 'object') {\n return null;\n }\n const llm = arg.llm as BaseChatModel;\n if (typeof llm.modelName !== 'string' && typeof llm.model !== 'string') {\n return null;\n }\n return llm;\n}\n\n/**\n * Extract agent name from createReactAgent params\n */\nexport function extractAgentNameFromParams(args: unknown[]): string | null {\n const arg = args[0];\n if (typeof arg === 'object' && !!arg && 'name' in arg && typeof arg.name === 'string') {\n return arg.name;\n }\n return null;\n}\n\n/** The options that hold outside a graph run, where no `invoke()`/`stream()` call decided: a function needs the graph input. */\nexport function getBooleanRecordingOptions(options: LangGraphOptions): GenAiOptions {\n const { recordInputs, recordOutputs } = options;\n return {\n recordInputs: typeof recordInputs === 'boolean' ? recordInputs : undefined,\n recordOutputs: typeof recordOutputs === 'boolean' ? recordOutputs : undefined,\n };\n}\n\n/**\n * Wraps an array of LangChain tools so each invocation creates a gen_ai.execute_tool span.\n *\n * Wraps each tool's invoke() method in place. A marker prevents double-wrapping.\n */\nexport function wrapToolsWithSpans(tools: unknown[], options: LangGraphOptions, agentName?: string): unknown[] {\n const SENTRY_WRAPPED = '__sentry_tool_wrapped__';\n\n for (const tool of tools) {\n if (!tool || typeof tool !== 'object') {\n continue;\n }\n\n const t = tool as Record<string, unknown>;\n const originalInvoke = t.invoke;\n if (typeof originalInvoke !== 'function' || Object.prototype.hasOwnProperty.call(t, SENTRY_WRAPPED)) {\n continue;\n }\n\n const toolName = typeof t.name === 'string' ? t.name : 'unknown_tool';\n const toolDescription = typeof t.description === 'string' ? t.description : undefined;\n\n const wrappedInvoke = new Proxy(originalInvoke as (...args: unknown[]) => unknown, {\n apply(target, thisArg, args: unknown[]): unknown {\n const spanAttributes: SpanAttributes = {\n [SENTRY_ORIGIN]: LANGGRAPH_ORIGIN,\n [SENTRY_OP]: GEN_AI_EXECUTE_TOOL,\n [GEN_AI_OPERATION_NAME]: 'execute_tool',\n [GEN_AI_TOOL_NAME]: toolName,\n };\n\n // Read agent name from LangChain's propagated config metadata at call time,\n // so shared tools get the correct agent name for each invocation\n const callConfig = args[1] as Record<string, unknown> | undefined;\n const metadata = callConfig?.metadata as Record<string, unknown> | undefined;\n const { recordInputs, recordOutputs } =\n getLangGraphRunRecording(metadata) ?? resolveAIRecordingOptions(getBooleanRecordingOptions(options));\n const callAgentName = metadata?.lc_agent_name ?? agentName;\n if (typeof callAgentName === 'string') {\n spanAttributes[GEN_AI_AGENT_NAME] = callAgentName;\n }\n Object.assign(spanAttributes, getConversationIdFromMetadata(metadata));\n\n if (toolDescription) {\n spanAttributes[GEN_AI_TOOL_DESCRIPTION] = toolDescription;\n }\n\n // LangGraph ToolNode passes { name, args, id, type: \"tool_call\" }\n const input = args[0] as Record<string, unknown> | undefined;\n if (typeof input === 'object' && !!input) {\n if ('id' in input && typeof input.id === 'string') {\n spanAttributes[GEN_AI_TOOL_CALL_ID_ATTRIBUTE] = input.id;\n }\n\n if (recordInputs) {\n const toolArgs = 'args' in input && typeof input.args === 'object' ? input.args : input;\n try {\n spanAttributes[GEN_AI_TOOL_CALL_ARGUMENTS] = JSON.stringify(toolArgs);\n } catch {\n // skip if not serializable\n }\n }\n }\n\n return startSpan(\n {\n name: `execute_tool ${toolName}`,\n attributes: spanAttributes,\n },\n async span => {\n try {\n const result = await Reflect.apply(target, thisArg, args);\n\n if (recordOutputs) {\n try {\n // ToolMessage objects wrap the result in .content\n const resultObj = result as Record<string, unknown> | undefined;\n const content =\n resultObj && typeof resultObj === 'object' && 'content' in resultObj ? resultObj.content : result;\n span.setAttribute(\n GEN_AI_TOOL_CALL_RESULT,\n typeof content === 'string' ? content : JSON.stringify(content),\n );\n } catch {\n // skip if not serializable\n }\n }\n\n return result;\n } catch (error) {\n // The error is rethrown to the caller (invoke() rejects), so we only mark the span\n // failed and do not record it.\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n throw error;\n }\n },\n );\n },\n });\n\n t.invoke = wrappedInvoke;\n Object.defineProperty(t, SENTRY_WRAPPED, { value: true, enumerable: false });\n }\n\n return tools;\n}\n\n/**\n * Extract tool calls from messages\n */\nexport function extractToolCalls(messages: Array<Record<string, unknown>> | null): unknown[] | null {\n if (!messages || messages.length === 0) {\n return null;\n }\n\n const toolCalls: unknown[] = [];\n\n for (const message of messages) {\n if (message && typeof message === 'object') {\n const msgToolCalls = message.tool_calls;\n if (msgToolCalls && Array.isArray(msgToolCalls)) {\n toolCalls.push(...msgToolCalls);\n }\n }\n }\n\n return toolCalls.length > 0 ? toolCalls : null;\n}\n\n/**\n * Extract token usage from a message's usage_metadata or response_metadata\n * Returns token counts without setting span attributes\n */\nexport function extractTokenUsageFromMessage(message: LangChainMessage): {\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n cacheCreationInputTokens?: number;\n cacheReadInputTokens?: number;\n} {\n const attributes = extractMessageTokenUsageAttributes(message);\n return {\n inputTokens: attributes[GEN_AI_USAGE_INPUT_TOKENS] ?? 0,\n outputTokens: attributes[GEN_AI_USAGE_OUTPUT_TOKENS] ?? 0,\n totalTokens: attributes[GEN_AI_USAGE_TOTAL_TOKENS] ?? 0,\n cacheCreationInputTokens: attributes[GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS],\n cacheReadInputTokens: attributes[GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS],\n };\n}\n\n/**\n * Extract model and finish reason from a message's response_metadata\n */\nexport function extractModelMetadata(span: Span, message: LangChainMessage): void {\n const msg = message as Record<string, unknown>;\n\n if (msg.response_metadata && typeof msg.response_metadata === 'object') {\n const metadata = msg.response_metadata as Record<string, unknown>;\n\n if (metadata.model_name && typeof metadata.model_name === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, metadata.model_name);\n }\n\n if (metadata.finish_reason && typeof metadata.finish_reason === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, JSON.stringify([metadata.finish_reason]));\n }\n }\n}\n\n/**\n * Extract tools from compiled graph structure\n *\n * Tools are stored in: compiledGraph.builder.nodes.tools.runnable.tools\n */\nexport function extractToolsFromCompiledGraph(compiledGraph: CompiledGraph): unknown[] | null {\n if (!compiledGraph.builder?.nodes?.tools?.runnable?.tools) {\n return null;\n }\n\n const tools = compiledGraph.builder?.nodes?.tools?.runnable?.tools;\n\n if (!tools || !Array.isArray(tools) || tools.length === 0) {\n return null;\n }\n\n // Extract name, description, and schema from each tool's lc_kwargs\n return tools.map((tool: LangGraphTool) => ({\n name: tool.lc_kwargs?.name,\n description: tool.lc_kwargs?.description,\n schema: tool.lc_kwargs?.schema,\n }));\n}\n\n/**\n * Set response attributes on the span\n */\nexport function setResponseAttributes(span: Span, inputMessages: LangChainMessage[] | null, result: unknown): void {\n // Extract messages from result\n const resultObj = result as { messages?: LangChainMessage[] } | undefined;\n const outputMessages = resultObj?.messages;\n\n if (!outputMessages || !Array.isArray(outputMessages)) {\n // Custom state annotations have no `messages` array, the whole state is recorded instead.\n if (result && typeof result === 'object') {\n const serializedState = stringify(result);\n // `gen_ai.output.messages` is what the product reads first; `gen_ai.response.text` is kept for\n // back-compat (Relay still migrates it).\n setOutputMessagesAttribute(span, { responseText: serializedState });\n span.setAttribute(GEN_AI_RESPONSE_TEXT, stringify([{ role: 'assistant', content: serializedState }]));\n }\n return;\n }\n\n // Get new messages (delta between input and output)\n const inputCount = inputMessages?.length ?? 0;\n const newMessages = outputMessages.length > inputCount ? outputMessages.slice(inputCount) : [];\n\n if (newMessages.length === 0) {\n return;\n }\n\n // Extract and set tool calls from new messages BEFORE normalization\n // (normalization strips tool_calls, so we need to extract them first)\n const toolCalls = extractToolCalls(newMessages);\n if (toolCalls) {\n span.setAttribute(GEN_AI_RESPONSE_TOOL_CALLS, JSON.stringify(toolCalls));\n }\n\n // Normalize the new messages\n const normalizedNewMessages = normalizeLangChainMessages(newMessages);\n span.setAttribute(GEN_AI_RESPONSE_TEXT, JSON.stringify(normalizedNewMessages));\n\n // Accumulate token usage across all messages\n let totalInputTokens = 0;\n let totalOutputTokens = 0;\n let totalTokens = 0;\n let cacheCreationInputTokens: number | undefined;\n let cacheReadInputTokens: number | undefined;\n\n // Extract metadata from messages\n for (const message of newMessages) {\n // Accumulate token usage\n const tokens = extractTokenUsageFromMessage(message);\n totalInputTokens += tokens.inputTokens;\n totalOutputTokens += tokens.outputTokens;\n totalTokens += tokens.totalTokens;\n if (tokens.cacheCreationInputTokens !== undefined) {\n cacheCreationInputTokens = (cacheCreationInputTokens ?? 0) + tokens.cacheCreationInputTokens;\n }\n if (tokens.cacheReadInputTokens !== undefined) {\n cacheReadInputTokens = (cacheReadInputTokens ?? 0) + tokens.cacheReadInputTokens;\n }\n\n // Extract model metadata (last message's metadata wins for model/finish_reason)\n extractModelMetadata(span, message);\n }\n\n // Set accumulated token usage on span\n if (totalInputTokens > 0) {\n span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, totalInputTokens);\n }\n if (totalOutputTokens > 0) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, totalOutputTokens);\n }\n if (totalTokens > 0) {\n span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, totalTokens);\n }\n if (cacheCreationInputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cacheCreationInputTokens);\n }\n if (cacheReadInputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cacheReadInputTokens);\n }\n}\n","import { stringify } from '@sentry/core';\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport {\n GEN_AI_AGENT_NAME,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_PIPELINE_NAME,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_TOOL_DEFINITIONS,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_INVOKE_AGENT } from '@sentry/conventions/op';\nimport { extractSystemInstructions, resolveGenAiCallRecording } from '../core/utils';\nimport type { GenAiOptions } from '../core/utils';\nimport type { BaseChatModel, LangChainMessage } from '../langchain/types';\nimport {\n _INTERNAL_mergeLangChainCallbackHandler,\n getConversationIdFromMetadata,\n getConversationIdMetadataFromConfig,\n getInheritedLangChainCallbacks,\n normalizeLangChainMessages,\n} from '../langchain/utils';\nimport { LANGGRAPH_ORIGIN } from './constants';\nimport type { CompiledGraph, LangGraphCallInfo, LangGraphOptions } from './types';\nimport { extractToolsFromCompiledGraph } from './utils';\n\n// LangGraph's invoke() calls this.stream() before its first await, so a graph set only for that synchronous\n// stretch marks exactly invoke's own stream() call. A stream() started later in the run gets its own span.\nlet invokingGraph: object | undefined;\n\n/** Runs the original invoke() of `graph`, so its internal stream() call can be recognised. */\nexport function callInvoke<T>(graph: object, invoke: () => T): T {\n const previous = invokingGraph;\n invokingGraph = graph;\n try {\n return invoke();\n } finally {\n invokingGraph = previous;\n }\n}\n\n/** Whether this stream() call on `graph` is the one its invoke() makes internally. */\nexport function isInvokeInternalStream(graph: object): boolean {\n return invokingGraph === graph;\n}\n\n/** Name and initial attributes of an agent span, from the call's config. */\nexport function getAgentSpanOptions(\n args: unknown[],\n extraAttributes?: SpanAttributes,\n): { name: string; attributes: SpanAttributes } {\n const config = args.length > 1 ? (args[1] as Record<string, unknown> | undefined) : undefined;\n return {\n name: 'invoke_agent',\n attributes: {\n // Set before `spanStart`, so an id from `Sentry.setConversationId()` wins, as on the child spans\n ...getConversationIdFromMetadata(config?.configurable as Record<string, unknown> | undefined),\n [SENTRY_ORIGIN]: LANGGRAPH_ORIGIN,\n [SENTRY_OP]: GEN_AI_INVOKE_AGENT,\n [GEN_AI_OPERATION_NAME]: 'invoke_agent',\n ...extraAttributes,\n },\n };\n}\n\n/** Decides for one `invoke()`/`stream()` call, from its arguments as passed. */\nexport function resolveGraphCallRecording(\n options: LangGraphOptions,\n args: unknown[],\n): { call: LangGraphCallInfo; recording: Required<GenAiOptions> } {\n const call: LangGraphCallInfo = {\n operation: 'invoke_agent',\n input: args[0],\n config: args[1] as Record<string, unknown> | undefined,\n };\n return { call, recording: resolveGenAiCallRecording(options, call) };\n}\n\n/** Sets the request attributes on an agent span and injects the callback handler into the call's config. */\nexport function prepareAgentSpan(\n span: Span,\n args: unknown[],\n graphInstance: CompiledGraph,\n compileOptions: Record<string, unknown>,\n recording: Required<GenAiOptions>,\n llm: BaseChatModel | null | undefined,\n sentryCallbackHandler: unknown,\n): LangChainMessage[] | null {\n const graphName = compileOptions?.name;\n\n if (graphName && typeof graphName === 'string') {\n span.setAttribute(GEN_AI_PIPELINE_NAME, graphName);\n span.setAttribute(GEN_AI_AGENT_NAME, graphName);\n span.updateName(`invoke_agent ${graphName}`);\n }\n\n const modelName = llm?.modelName ?? llm?.model;\n if (modelName) {\n span.setAttribute(GEN_AI_REQUEST_MODEL, modelName);\n }\n\n // A copy, so nothing is written back to a config object the caller reuses for other calls.\n const config: Record<string, unknown> = { ...(args[1] as Record<string, unknown> | undefined) };\n args[1] = config;\n // Explicit callbacks replace the parent run's, which LangChain would otherwise inherit.\n const callbacks = config.callbacks ?? getInheritedLangChainCallbacks();\n if (callbacks) {\n config.callbacks = callbacks;\n }\n\n if (sentryCallbackHandler) {\n const existingMetadata = (config.metadata ?? {}) as Record<string, unknown>;\n config.metadata = {\n ...getConversationIdMetadataFromConfig(config),\n ...existingMetadata,\n // Child runs inherit the metadata, so their spans follow this call's decision.\n __sentry_langgraph__: recording,\n ...(typeof graphName === 'string' ? { lc_agent_name: graphName } : {}),\n };\n\n config.callbacks = _INTERNAL_mergeLangChainCallbackHandler(config.callbacks, sentryCallbackHandler);\n }\n\n const { recordInputs } = recording;\n\n const tools = recordInputs ? extractToolsFromCompiledGraph(graphInstance) : null;\n if (tools) {\n span.setAttribute(GEN_AI_TOOL_DEFINITIONS, JSON.stringify(tools));\n }\n\n // Custom state annotations have no `messages` array, the whole state is recorded instead.\n const inputState = args[0] as { messages?: LangChainMessage[]; lg_name?: string } | null | undefined;\n const inputMessages = Array.isArray(inputState?.messages) ? inputState.messages : null;\n // `new Command({ resume })` resumes an interrupted run and carries no user turn (LangGraph\n // tags it `lg_name: 'Command'`), so skip it like a `null` resume rather than recording the\n // control object as a message nobody wrote.\n const isResumeCommand = inputState?.lg_name === 'Command';\n\n if (recordInputs) {\n if (inputMessages) {\n const normalizedMessages = normalizeLangChainMessages(inputMessages);\n const { systemInstructions, filteredMessages } = extractSystemInstructions(normalizedMessages);\n\n if (systemInstructions) {\n span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS, systemInstructions);\n }\n\n span.setAttributes({\n [GEN_AI_INPUT_MESSAGES]: stringify(filteredMessages),\n });\n } else if (inputState && typeof inputState === 'object' && !isResumeCommand) {\n span.setAttribute(GEN_AI_INPUT_MESSAGES, stringify([{ role: 'user', content: stringify(inputState) }]));\n }\n }\n\n return inputMessages;\n}\n","import { SPAN_STATUS_ERROR, startSpanManual } from '@sentry/core';\nimport { GEN_AI_RESPONSE_STREAMING } from '@sentry/conventions/attributes';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { BaseChatModel, LangChainMessage } from '../langchain/types';\nimport { _INTERNAL_addLangChainCallbackHandler } from '../langchain/utils';\nimport { getAgentSpanOptions, isInvokeInternalStream, prepareAgentSpan, resolveGraphCallRecording } from './agent-span';\nimport type { CompiledGraph, LangGraphOptions } from './types';\nimport { setResponseAttributes } from './utils';\n\n/**\n * Instruments CompiledGraph's stream method with a `gen_ai.invoke_agent` span that lasts for the graph run.\n *\n * LangGraph runs the graph as soon as `stream()` is called, whether or not the stream is read, so the span\n * ends on the run's own end or error callback rather than when the stream is consumed.\n */\nexport function instrumentCompiledGraphStream(\n originalStream: (...args: unknown[]) => Promise<unknown>,\n graphInstance: CompiledGraph,\n compileOptions: Record<string, unknown>,\n options: LangGraphOptions,\n llm?: BaseChatModel | null,\n sentryCallbackHandler?: unknown,\n): (...args: unknown[]) => Promise<unknown> {\n return new Proxy(originalStream, {\n apply(target, thisArg, args: unknown[]): Promise<unknown> {\n if (isInvokeInternalStream(graphInstance)) {\n return Reflect.apply(target, thisArg, args);\n }\n\n const { call, recording } = resolveGraphCallRecording(options, args);\n return startSpanManual(getAgentSpanOptions(args, { [GEN_AI_RESPONSE_STREAMING]: true }), async span => {\n let inputMessages: LangChainMessage[] | null = null;\n let stream: { signal?: AbortSignal } | undefined;\n let ended = false;\n const finish = (outcome?: { outputs: unknown } | { error: unknown }): void => {\n if (ended) {\n return;\n }\n ended = true;\n try {\n if (outcome && 'error' in outcome) {\n // A cancel or abort by the caller is not a failed run. LangGraph reports both, and step\n // timeouts too, as `Error('Abort')`, so only the signals tell them apart.\n if (!stream?.signal?.aborted && !(args[1] as { signal?: AbortSignal } | undefined)?.signal?.aborted) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n } else if (outcome && recording.recordOutputs) {\n setResponseAttributes(span, inputMessages, outcome.outputs);\n }\n } catch {\n // Recording must never change the outcome of the run.\n }\n runGenAiSpanEnd(\n options,\n span,\n call,\n outcome && 'error' in outcome ? { error: outcome.error } : { response: outcome?.outputs },\n );\n span.end();\n inputMessages = null;\n };\n\n // The root run starts before any of its children, so it is the first run this per-call listener sees.\n let rootRunId: string | undefined;\n const listener = {\n name: 'SentryLangGraphStreamListener',\n awaitHandlers: true,\n handleChainStart(_chain: unknown, _inputs: unknown, runId: string): void {\n rootRunId ??= runId;\n },\n handleChainEnd(outputs: unknown, runId: string): void {\n if (runId === rootRunId) {\n finish({ outputs });\n }\n },\n handleChainError(error: unknown, runId: string): void {\n if (runId === rootRunId) {\n finish({ error });\n }\n },\n copy() {\n return listener;\n },\n };\n\n try {\n inputMessages = prepareAgentSpan(\n span,\n args,\n graphInstance,\n compileOptions,\n recording,\n llm,\n sentryCallbackHandler,\n );\n runGenAiSpanStart(options, span, call);\n // `prepareAgentSpan` gave the call its own copy of the config, so the listener stays on this call.\n const config = args[1] as Record<string, unknown>;\n config.callbacks = _INTERNAL_addLangChainCallbackHandler(config.callbacks, listener);\n stream = (await Reflect.apply(target, thisArg, args)) as typeof stream;\n } catch (error) {\n finish({ error });\n throw error;\n }\n\n if (rootRunId === undefined) {\n // Not a LangGraph run we can follow, so don't leave the span open.\n finish();\n } else {\n endOnEarlyExit(stream, finish);\n }\n return stream;\n });\n },\n });\n}\n\n// After a `break`, LangGraph keeps running the graph but never reports the run's end, so the span ends when\n// the caller stops. Nodes still running at that point start spans after the agent span ended.\nfunction endOnEarlyExit(stream: unknown, finish: () => void): void {\n if (!stream || typeof stream !== 'object') {\n return;\n }\n const target = stream as { return?: (...args: unknown[]) => unknown; cancel?: (...args: unknown[]) => unknown };\n const { return: originalReturn, cancel: originalCancel } = target;\n try {\n if (typeof originalReturn === 'function') {\n target.return = function (this: unknown, ...args: unknown[]): unknown {\n try {\n return originalReturn.apply(this, args);\n } finally {\n finish();\n }\n };\n }\n if (typeof originalCancel === 'function') {\n target.cancel = function (this: unknown, ...args: unknown[]): unknown {\n const result = originalCancel.apply(this, args);\n Promise.resolve(result).then(\n () => finish(),\n () => undefined,\n );\n return result;\n };\n }\n } catch {\n finish();\n }\n}\n","import { SPAN_STATUS_ERROR, startSpan } from '@sentry/core';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport { createLangChainCallbackHandler } from '../langchain';\nimport type { BaseChatModel } from '../langchain/types';\nimport { callInvoke, getAgentSpanOptions, prepareAgentSpan, resolveGraphCallRecording } from './agent-span';\nimport { instrumentCompiledGraphStream } from './stream';\nimport type { CompiledGraph, LangGraphOptions } from './types';\nimport {\n extractAgentNameFromParams,\n extractLLMFromParams,\n getBooleanRecordingOptions,\n setResponseAttributes,\n wrapToolsWithSpans,\n} from './utils';\n\n// Set while a manual wrapper runs the original `compile`/`createReactAgent`. The integration's channel hooks\n// fire synchronously inside that call, and skip the graph so the options passed explicitly win.\nlet _insideManualInstrumentation = false;\n\nconst SENTRY_PATCHED = '__sentry_patched__';\nconst INSTRUMENTED_GRAPHS = new WeakSet<object>();\n\n/** Whether manual `instrumentStateGraph()`/`instrumentCreateReactAgent()` is creating a graph right now. */\nexport function isInsideManualLangGraphInstrumentation(): boolean {\n return _insideManualInstrumentation;\n}\n\nfunction runManually<T>(callback: () => T): T {\n const previous = _insideManualInstrumentation;\n _insideManualInstrumentation = true;\n try {\n return callback();\n } finally {\n _insideManualInstrumentation = previous;\n }\n}\n\n/**\n * Instruments StateGraph's compile method to wrap the returned compiled graph's invoke() and stream() with a\n * `gen_ai.invoke_agent` span.\n */\nexport function instrumentStateGraphCompile(\n originalCompile: (...args: unknown[]) => CompiledGraph,\n options: LangGraphOptions,\n): (...args: unknown[]) => CompiledGraph {\n if (Object.prototype.hasOwnProperty.call(originalCompile, SENTRY_PATCHED)) {\n return originalCompile;\n }\n\n const sentryHandler = createLangChainCallbackHandler(getBooleanRecordingOptions(options));\n\n const wrapped = new Proxy(originalCompile, {\n apply(target, thisArg, args: unknown[]): CompiledGraph {\n // The createReactAgent wrapper instruments the graph it compiles internally, with the agent's name and model.\n if (_insideManualInstrumentation) {\n return Reflect.apply(target, thisArg, args);\n }\n\n const compiledGraph = runManually(() => Reflect.apply(target, thisArg, args));\n const compileOptions = args.length > 0 ? (args[0] as Record<string, unknown>) : {};\n instrumentCompiledGraph(compiledGraph, compileOptions, options, undefined, sentryHandler);\n\n return compiledGraph;\n },\n });\n\n Object.defineProperty(wrapped, SENTRY_PATCHED, { value: true, enumerable: false });\n return wrapped;\n}\n\n/**\n * Wraps a compiled graph's `invoke()` and `stream()` with `gen_ai.invoke_agent` spans, once per graph.\n */\nexport function instrumentCompiledGraph(\n graph: unknown,\n compileOptions: Record<string, unknown>,\n options: LangGraphOptions,\n llm: BaseChatModel | null | undefined,\n sentryCallbackHandler: unknown,\n): void {\n if (!graph || typeof graph !== 'object' || INSTRUMENTED_GRAPHS.has(graph)) {\n return;\n }\n INSTRUMENTED_GRAPHS.add(graph);\n\n const compiledGraph = graph as CompiledGraph;\n const { invoke, stream } = compiledGraph;\n if (typeof invoke === 'function') {\n compiledGraph.invoke = instrumentCompiledGraphInvoke(\n invoke.bind(compiledGraph),\n compiledGraph,\n compileOptions,\n options,\n llm,\n sentryCallbackHandler,\n );\n }\n if (typeof stream === 'function') {\n compiledGraph.stream = instrumentCompiledGraphStream(\n stream.bind(compiledGraph),\n compiledGraph,\n compileOptions,\n options,\n llm,\n sentryCallbackHandler,\n );\n }\n}\n\n/**\n * Instruments CompiledGraph's invoke method to create spans for agent invocation\n *\n * Creates a `gen_ai.invoke_agent` span when invoke() is called\n */\nexport function instrumentCompiledGraphInvoke(\n originalInvoke: (...args: unknown[]) => Promise<unknown>,\n graphInstance: CompiledGraph,\n compileOptions: Record<string, unknown>,\n options: LangGraphOptions,\n llm?: BaseChatModel | null,\n sentryCallbackHandler?: unknown,\n): (...args: unknown[]) => Promise<unknown> {\n return new Proxy(originalInvoke, {\n apply(target, thisArg, args: unknown[]): Promise<unknown> {\n const { call, recording } = resolveGraphCallRecording(options, args);\n return startSpan(getAgentSpanOptions(args), async span => {\n try {\n const inputMessages = prepareAgentSpan(\n span,\n args,\n graphInstance,\n compileOptions,\n recording,\n llm,\n sentryCallbackHandler,\n );\n runGenAiSpanStart(options, span, call);\n const result = await callInvoke(graphInstance, () => Reflect.apply(target, thisArg, args));\n\n if (recording.recordOutputs) {\n setResponseAttributes(span, inputMessages, result);\n }\n runGenAiSpanEnd(options, span, call, { response: result });\n\n return result;\n } catch (error) {\n // The error is rethrown to the caller (invoke() rejects), so we only mark the span failed\n // and do not record it.\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n runGenAiSpanEnd(options, span, call, { error });\n throw error;\n }\n });\n },\n });\n}\n\n/**\n * Instruments createReactAgent to create invoke_agent and execute_tool spans.\n */\nexport function instrumentCreateReactAgent(\n originalCreateReactAgent: (...args: unknown[]) => CompiledGraph,\n options: LangGraphOptions = {},\n): (...args: unknown[]) => CompiledGraph {\n if (Object.prototype.hasOwnProperty.call(originalCreateReactAgent, SENTRY_PATCHED)) {\n return originalCreateReactAgent;\n }\n\n const sentryHandler = createLangChainCallbackHandler(getBooleanRecordingOptions(options));\n\n const wrapped = new Proxy(originalCreateReactAgent, {\n apply(target, thisArg, args: unknown[]): CompiledGraph {\n const llm = extractLLMFromParams(args);\n const agentName = extractAgentNameFromParams(args);\n\n // Wrap tools with execute_tool spans (direct access gives us name, type, description)\n const params = args[0] as Record<string, unknown> | undefined;\n if (params && Array.isArray(params.tools) && params.tools.length > 0) {\n wrapToolsWithSpans(params.tools, options, agentName ?? undefined);\n }\n\n const compiledGraph = runManually(() => Reflect.apply(target, thisArg, args));\n\n const compileOptions: Record<string, unknown> = agentName ? { name: agentName } : {};\n instrumentCompiledGraph(compiledGraph, compileOptions, options, llm, sentryHandler);\n\n return compiledGraph;\n },\n });\n\n Object.defineProperty(wrapped, SENTRY_PATCHED, { value: true, enumerable: false });\n return wrapped;\n}\n\n/**\n * Directly instruments a StateGraph instance to add tracing spans\n *\n * This function can be used to manually instrument LangGraph StateGraph instances\n * in environments where automatic instrumentation is not available or desired.\n *\n * @param stateGraph - The StateGraph instance to instrument\n * @param options - Optional configuration for recording inputs/outputs\n *\n * @example\n * ```typescript\n * import { instrumentStateGraph } from '@sentry/cloudflare';\n * import { StateGraph } from '@langchain/langgraph';\n *\n * const graph = new StateGraph(MessagesAnnotation)\n * .addNode('agent', mockLlm)\n * .addEdge(START, 'agent')\n * .addEdge('agent', END);\n *\n * instrumentStateGraph(graph, { recordInputs: true, recordOutputs: true });\n * const compiled = graph.compile({ name: 'my_agent' });\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function instrumentStateGraph<T extends { compile: (...args: any[]) => any }>(\n stateGraph: T,\n options: LangGraphOptions = {},\n): T {\n stateGraph.compile = instrumentStateGraphCompile(stateGraph.compile, options);\n\n return stateGraph;\n}\n","import {\n GEN_AI_CHAT,\n GEN_AI_DECIDE,\n GEN_AI_EMBEDDINGS,\n GEN_AI_EXECUTE_TOOL,\n GEN_AI_INVOKE_AGENT,\n} from '@sentry/conventions/op';\nimport type { MastraSpanType } from './types';\n\nexport const MASTRA_INTEGRATION_NAME = 'Mastra' as const;\n\n/** Cap on tracked spans, matching `MAX_TRACKED_PRISMA_SPANS`. Spans that never end would otherwise leak. */\nexport const MAX_TRACKED_MASTRA_SPANS = 1000;\n\nexport const MASTRA_ORIGIN = 'auto.ai.mastra';\n\n/** Not `sentry` — that is the community `@mastra/sentry` exporter name. */\nexport const MASTRA_EXPORTER_NAME = 'sentry-sdk';\n\n/** Name used by the community `@mastra/sentry` package. */\nexport const COMMUNITY_MASTRA_SENTRY_EXPORTER_NAME = 'sentry';\n\n/**\n * Distinguishes our exporter from the community one. `Symbol.for` so the check still matches if\n * two copies of `@sentry/server-utils` are loaded (`instanceof` would not).\n */\nexport const MASTRA_EXPORTER_BRAND = Symbol.for('sentry.mastra.exporter');\n\n/**\n * Only conventional `gen_ai` ops. Unmapped Mastra types (workflow steps, processors, scorers, …)\n * are dropped; their children re-parent onto the nearest mapped ancestor.\n *\n * `op` comes from `@sentry/conventions/op`. `operationName` is a `gen_ai.operation.name` literal —\n * the conventions package has no constants for those.\n */\nexport const SPAN_TYPE_OPS: Readonly<Record<string, { op: string; operationName: string }>> = {\n agent_run: { op: GEN_AI_INVOKE_AGENT, operationName: 'invoke_agent' },\n workflow_run: { op: GEN_AI_INVOKE_AGENT, operationName: 'invoke_agent' },\n model_generation: { op: GEN_AI_CHAT, operationName: 'chat' },\n tool_call: { op: GEN_AI_EXECUTE_TOOL, operationName: 'execute_tool' },\n mcp_tool_call: { op: GEN_AI_EXECUTE_TOOL, operationName: 'execute_tool' },\n provider_tool_call: { op: GEN_AI_EXECUTE_TOOL, operationName: 'execute_tool' },\n client_tool_call: { op: GEN_AI_EXECUTE_TOOL, operationName: 'execute_tool' },\n rag_embedding: { op: GEN_AI_EMBEDDINGS, operationName: 'embeddings' },\n classifier_evaluation: { op: GEN_AI_DECIDE, operationName: 'decide' },\n};\n\nexport const TOOL_SPAN_TYPES: ReadonlySet<string> = new Set<MastraSpanType>([\n 'tool_call',\n 'mcp_tool_call',\n 'provider_tool_call',\n 'client_tool_call',\n]);\n\n/**\n * `model_inference` is omitted: Mastra nests `model_generation > model_step > model_inference`,\n * and the inference span repeats the generation — mapping both to `gen_ai.chat` duplicates it.\n */\nexport const MODEL_SPAN_TYPES: ReadonlySet<string> = new Set<MastraSpanType>(['model_generation']);\n\nexport const AGENT_SPAN_TYPES: ReadonlySet<string> = new Set<MastraSpanType>(['agent_run', 'workflow_run']);\n","import type { SpanAttributeValue } from '@sentry/core';\nimport { stringify } from '@sentry/core';\nimport {\n ERROR_TYPE,\n GEN_AI_AGENT_NAME,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_OUTPUT_MESSAGES,\n GEN_AI_PIPELINE_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_PRESENCE_PENALTY,\n GEN_AI_REQUEST_SEED,\n GEN_AI_REQUEST_STOP_SEQUENCES,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_REQUEST_TOP_K,\n GEN_AI_REQUEST_TOP_P,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_STREAMING,\n GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DEFINITIONS,\n GEN_AI_TOOL_DESCRIPTION,\n GEN_AI_TOOL_NAME,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n} from '@sentry/conventions/attributes';\nimport { AGENT_SPAN_TYPES, MODEL_SPAN_TYPES, SPAN_TYPE_OPS, TOOL_SPAN_TYPES } from './constants';\nimport type { MastraExportedSpan, MastraSpanType, MastraUsageStats } from './types';\n\nexport interface AttributeRecordingOptions {\n recordInputs: boolean;\n recordOutputs: boolean;\n}\n\nexport type SpanAttributes = Record<string, SpanAttributeValue | undefined>;\n\nexport function isExportedSpanType(spanType: MastraSpanType): boolean {\n // `in` would also match inherited keys like `constructor` or `toString`.\n return Object.prototype.hasOwnProperty.call(SPAN_TYPE_OPS, spanType);\n}\n\nexport function getOperation(spanType: MastraSpanType): { op: string; operationName: string } | undefined {\n return SPAN_TYPE_OPS[spanType];\n}\n\n/**\n * `{operation} {identifier}` per the gen_ai name templates. Mastra's own span name is never used.\n * https://conventions.sentry.dev/names/\n */\nexport function getSpanName(span: MastraExportedSpan): string {\n const operationName = getOperation(span.type)?.operationName ?? span.type;\n const identifier = getSpanIdentifier(span);\n\n return identifier ? `${operationName} ${identifier}` : operationName;\n}\n\nfunction getSpanIdentifier(span: MastraExportedSpan): string | undefined {\n if (span.type === 'classifier_evaluation') {\n return span.attributes?.modelId;\n }\n if (MODEL_SPAN_TYPES.has(span.type) || span.type === 'rag_embedding') {\n return span.attributes?.model;\n }\n return span.entityName ?? span.entityId;\n}\n\nfunction serialize(value: unknown): string | undefined {\n if (value === undefined || value === null) {\n return undefined;\n }\n return typeof value === 'string' ? value : stringify(value);\n}\n\nfunction positive(value: number | undefined): number | undefined {\n return value !== undefined && value > 0 ? value : undefined;\n}\n\nexport function getUsageAttributes(usage: MastraUsageStats | undefined): SpanAttributes {\n if (!usage) {\n return {};\n }\n\n const inputTokens = usage.inputTokens;\n const outputTokens = usage.outputTokens;\n // Mastra only reports `totalTokens` for some providers, so derive it when both halves are known.\n const totalTokens =\n usage.totalTokens ??\n (inputTokens !== undefined || outputTokens !== undefined ? (inputTokens ?? 0) + (outputTokens ?? 0) : undefined);\n\n return {\n [GEN_AI_USAGE_INPUT_TOKENS]: inputTokens,\n [GEN_AI_USAGE_OUTPUT_TOKENS]: outputTokens,\n [GEN_AI_USAGE_TOTAL_TOKENS]: totalTokens,\n // Mastra reports these as 0 for providers that don't cache or reason.\n [GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]: positive(usage.inputDetails?.cacheRead),\n [GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]: positive(usage.inputDetails?.cacheWrite),\n [GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]: positive(usage.outputDetails?.reasoning),\n };\n}\n\nconst USAGE_ATTRIBUTE_KEYS = [\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n] as const;\n\nfunction addTokenCounts(\n left: SpanAttributeValue | undefined,\n right: SpanAttributeValue | undefined,\n): number | undefined {\n const a = typeof left === 'number' ? left : undefined;\n const b = typeof right === 'number' ? right : undefined;\n if (a === undefined && b === undefined) {\n return undefined;\n }\n return (a ?? 0) + (b ?? 0);\n}\n\n/** Sum usage across generations. `setAttributes(undefined)` would drop the previous total. */\nexport function mergeUsageAttributes(existing: SpanAttributes, incoming: SpanAttributes): SpanAttributes {\n const merged: SpanAttributes = {};\n for (const key of USAGE_ATTRIBUTE_KEYS) {\n const value = addTokenCounts(existing[key], incoming[key]);\n if (value !== undefined) {\n merged[key] = value;\n }\n }\n return merged;\n}\n\n/** Convention attributes only. Called on start and end — Mastra fills fields progressively. */\nexport function getSpanAttributes(span: MastraExportedSpan, options: AttributeRecordingOptions): SpanAttributes {\n const operationName = getOperation(span.type)?.operationName;\n\n const attributes: SpanAttributes = {\n [GEN_AI_OPERATION_NAME]: operationName,\n };\n\n if (AGENT_SPAN_TYPES.has(span.type)) {\n addAgentAttributes(attributes, span, options);\n }\n\n if (MODEL_SPAN_TYPES.has(span.type) || span.type === 'rag_embedding') {\n addModelAttributes(attributes, span, options);\n }\n\n if (TOOL_SPAN_TYPES.has(span.type)) {\n addToolAttributes(attributes, span, options);\n }\n\n if (span.type === 'classifier_evaluation') {\n addEvaluationAttributes(attributes, span);\n }\n\n if (span.errorInfo) {\n attributes[ERROR_TYPE] = span.errorInfo.name ?? span.errorInfo.id;\n }\n\n return attributes;\n}\n\nfunction addAgentAttributes(\n attributes: SpanAttributes,\n span: MastraExportedSpan,\n options: AttributeRecordingOptions,\n): void {\n const attrs = span.attributes ?? {};\n const name = span.entityName ?? span.entityId;\n\n attributes[GEN_AI_AGENT_NAME] = name;\n attributes[GEN_AI_PIPELINE_NAME] = name;\n attributes[GEN_AI_TOOL_DEFINITIONS] = serialize(attrs.availableTools);\n\n if (options.recordInputs) {\n // `prompt` is Mastra's legacy alias for the system prompt.\n attributes[GEN_AI_SYSTEM_INSTRUCTIONS] = attrs.instructions ?? attrs.prompt;\n attributes[GEN_AI_INPUT_MESSAGES] = serialize(span.input);\n }\n if (options.recordOutputs) {\n attributes[GEN_AI_OUTPUT_MESSAGES] = serialize(span.output);\n // oxlint-disable-next-line typescript/no-deprecated -- still emitted by the other AI integrations\n attributes[GEN_AI_RESPONSE_TEXT] = responseText(span.output);\n }\n}\n\nfunction addModelAttributes(\n attributes: SpanAttributes,\n span: MastraExportedSpan,\n options: AttributeRecordingOptions,\n): void {\n const attrs = span.attributes ?? {};\n const parameters = attrs.parameters ?? {};\n\n attributes[GEN_AI_REQUEST_MODEL] = attrs.model;\n attributes[GEN_AI_PROVIDER_NAME] = attrs.provider;\n attributes[GEN_AI_RESPONSE_MODEL] = attrs.responseModel;\n attributes[GEN_AI_RESPONSE_ID] = attrs.responseId;\n attributes[GEN_AI_RESPONSE_STREAMING] = attrs.streaming;\n attributes[GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK] = attrs.completionStartTime\n ? (attrs.completionStartTime.getTime() - span.startTime.getTime()) / 1000\n : undefined;\n attributes[GEN_AI_RESPONSE_FINISH_REASONS] = attrs.finishReason ? JSON.stringify([attrs.finishReason]) : undefined;\n attributes[GEN_AI_AGENT_NAME] = span.entityName;\n\n attributes[GEN_AI_REQUEST_TEMPERATURE] = parameters.temperature;\n attributes[GEN_AI_REQUEST_MAX_TOKENS] = parameters.maxOutputTokens;\n attributes[GEN_AI_REQUEST_TOP_P] = parameters.topP;\n attributes[GEN_AI_REQUEST_TOP_K] = parameters.topK;\n attributes[GEN_AI_REQUEST_PRESENCE_PENALTY] = parameters.presencePenalty;\n attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY] = parameters.frequencyPenalty;\n attributes[GEN_AI_REQUEST_SEED] = parameters.seed;\n attributes[GEN_AI_REQUEST_STOP_SEQUENCES] = parameters.stopSequences;\n\n Object.assign(attributes, getUsageAttributes(attrs.usage));\n\n if (options.recordInputs) {\n attributes[GEN_AI_INPUT_MESSAGES] = serialize(span.input);\n }\n if (options.recordOutputs) {\n attributes[GEN_AI_OUTPUT_MESSAGES] = serialize(span.output);\n // oxlint-disable-next-line typescript/no-deprecated -- still emitted by the other AI integrations\n attributes[GEN_AI_RESPONSE_TEXT] = responseText(span.output);\n }\n}\n\nfunction addToolAttributes(\n attributes: SpanAttributes,\n span: MastraExportedSpan,\n options: AttributeRecordingOptions,\n): void {\n const attrs = span.attributes ?? {};\n\n attributes[GEN_AI_TOOL_NAME] = span.entityName ?? span.entityId;\n attributes[GEN_AI_TOOL_DESCRIPTION] = attrs.toolDescription;\n\n if (options.recordInputs) {\n attributes[GEN_AI_TOOL_CALL_ARGUMENTS] = serialize(span.input);\n }\n if (options.recordOutputs) {\n attributes[GEN_AI_TOOL_CALL_RESULT] = serialize(span.output);\n }\n}\n\n/** Mastra's `Classifier` sets no input or output on this span, so only the model and usage are known. */\nfunction addEvaluationAttributes(attributes: SpanAttributes, span: MastraExportedSpan): void {\n const attrs = span.attributes ?? {};\n\n attributes[GEN_AI_REQUEST_MODEL] = attrs.modelId;\n attributes[GEN_AI_PROVIDER_NAME] = attrs.provider;\n Object.assign(attributes, getUsageAttributes(attrs.usage));\n}\n\nfunction responseText(output: unknown): string | undefined {\n if (typeof output === 'string') {\n return output;\n }\n if (output && typeof output === 'object' && 'text' in output && typeof output.text === 'string') {\n return output.text;\n }\n return undefined;\n}\n","import type { Span } from '@sentry/core';\nimport type { MastraExportedSpan, MastraSpanOutputProcessor } from './types';\n\n/**\n * Links a `Classifier.evaluate()` call to the Sentry span the exporter opens for its\n * `classifier_evaluation` span. Mastra's span carries no input or output, so the integration adds\n * them from the call. Mastra ends its span before `evaluate()` returns the answers, so the exporter\n * leaves the Sentry span open and the integration ends it once the call settles.\n */\nexport interface ClassifierEvaluationCall {\n span?: Span;\n /** Mastra's span and the processors of its observability instance, to filter the call's data. */\n mastraSpan?: MastraExportedSpan;\n spanOutputProcessors?: MastraSpanOutputProcessor[];\n /** The recording options of the exporter that opened the span, so the call's data follows them. */\n recordInputs?: boolean;\n recordOutputs?: boolean;\n /** Ends the span at Mastra's end time, set when Mastra ended its span before the call settled. */\n end?: () => void;\n settled?: boolean;\n}\n\n// Mastra emits `span_started` synchronously inside `evaluate()`, before its first `await`, so at\n// most one call is ever in this window.\nlet startingCall: ClassifierEvaluationCall | undefined;\n\nexport function setStartingClassifierEvaluation(call: ClassifierEvaluationCall | undefined): void {\n startingCall = call;\n}\n\nexport function takeStartingClassifierEvaluation(): ClassifierEvaluationCall | undefined {\n const call = startingCall;\n startingCall = undefined;\n return call;\n}\n\n/**\n * Run the call's data through Mastra's span output processors (for example its default\n * `SensitiveDataFilter`), as Mastra does for the input and output of its own spans. Returns `undefined`\n * when a processor drops the span or throws, so unfiltered data is never recorded.\n */\nexport function processClassifierEvaluationData(\n call: ClassifierEvaluationCall,\n data: { input?: unknown; output?: unknown },\n): { input?: unknown; output?: unknown } | undefined {\n let span: MastraExportedSpan | undefined = { ...call.mastraSpan, ...data } as MastraExportedSpan;\n for (const processor of call.spanOutputProcessors ?? []) {\n try {\n span = processor.process(span);\n } catch {\n return undefined;\n }\n if (!span) {\n return undefined;\n }\n }\n return span;\n}\n","import type { Span } from '@sentry/core';\nimport { LRUMap } from '@sentry/core';\nimport { MAX_TRACKED_MASTRA_SPANS } from './constants';\n\n/**\n * Maps a Mastra span id to the Sentry span the exporter opened for it, so the `executeWithContext`\n * channel subscriber can make that span active for the operation's work (see `integrations/mastra.ts`).\n *\n * Keyed by Mastra span id (globally unique), so it works across multiple `Mastra` instances / exporters\n * — each registers and unregisters its own spans. It's an `LRUMap` rather than a plain `Map` so the\n * process-wide table stays bounded even if an `unregister` is ever missed (a dropped entry only means a\n * nested span won't reparent — it degrades, it can't leak).\n */\nconst spansByMastraId = new LRUMap<string, Span>(MAX_TRACKED_MASTRA_SPANS);\n\nexport function registerMastraSpan(mastraId: string, span: Span): void {\n spansByMastraId.set(mastraId, span);\n}\n\nexport function unregisterMastraSpan(mastraId: string): void {\n spansByMastraId.remove(mastraId);\n}\n\nexport function getSentrySpanForMastraId(mastraId: string): Span | undefined {\n return spansByMastraId.get(mastraId);\n}\n","import type { Span, SpanTimeInput } from '@sentry/core';\nimport {\n debug,\n flush as sentryFlush,\n getActiveSpan,\n getClient,\n LRUMap,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n timestampInSeconds,\n} from '@sentry/core';\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_RESPONSE_MODEL,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type { GenAiSpanHooks, GenAiSpanResult } from '../core/span-hooks';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { GenAiCallOptions } from '../core/utils';\nimport { resolveGenAiCallRecording } from '../core/utils';\nimport {\n getOperation,\n getSpanAttributes,\n getSpanName,\n getUsageAttributes,\n isExportedSpanType,\n mergeUsageAttributes,\n type AttributeRecordingOptions,\n type SpanAttributes,\n} from './utils';\nimport {\n AGENT_SPAN_TYPES,\n MASTRA_EXPORTER_BRAND,\n MASTRA_EXPORTER_NAME,\n MASTRA_ORIGIN,\n MAX_TRACKED_MASTRA_SPANS,\n MODEL_SPAN_TYPES,\n} from './constants';\nimport type { ClassifierEvaluationCall } from './classifier-evaluation';\nimport { takeStartingClassifierEvaluation } from './classifier-evaluation';\nimport { registerMastraSpan, unregisterMastraSpan } from './span-registry';\nimport type {\n MastraExportedSpan,\n MastraExporterInitOptions,\n MastraObservabilityExporter,\n MastraSpanOutputProcessor,\n MastraSpanType,\n MastraTracingEvent,\n} from './types';\n\n/** The span that `recordInputs`/`recordOutputs` decide on, and that the span hooks get. */\nexport interface MastraCallInfo {\n /** The Mastra span as exported, when it starts. */\n span: MastraExportedSpan;\n}\n\n/**\n * `recordInputs`/`recordOutputs` and `onSpanStart` run when the exporter receives the start of a Mastra\n * span, and `onSpanEnd` when it receives its end, not in the async context of the code that started it.\n * `onSpanEnd` gets the Mastra span as exported when it ends, with its output, unless it failed or the\n * exporter ended it early, on shutdown or when too many spans are open at once.\n */\nexport type MastraExporterOptions = GenAiCallOptions<MastraCallInfo> &\n GenAiSpanHooks<MastraCallInfo, MastraExportedSpan>;\n\ninterface TrackedSpan {\n span: Span;\n call: MastraCallInfo;\n spanType: MastraSpanType;\n usage: SpanAttributes;\n recordingOptions: AttributeRecordingOptions;\n evaluation?: ClassifierEvaluationCall;\n}\n\nconst FLUSH_TIMEOUT_MS = 2000;\n\n/** Bound on the skipped-span parent walk; a cyclic chain from Mastra would otherwise hang the process. */\nconst MAX_PARENT_WALK_DEPTH = 100;\n\n/**\n * Mastra `ObservabilityExporter` that turns tracing events into Sentry spans.\n *\n * Never calls `Sentry.init()` / `Sentry.close()` — the community `@mastra/sentry` package does both\n * and replaces the app's client. No `@mastra/*` or `node:` imports.\n */\nexport class SentryMastraExporter implements MastraObservabilityExporter {\n public name = MASTRA_EXPORTER_NAME;\n\n public readonly [MASTRA_EXPORTER_BRAND] = true;\n\n private readonly _spans = new LRUMap<string, TrackedSpan>(MAX_TRACKED_MASTRA_SPANS);\n /**\n * Dropped span id -> parent id, for re-parenting descendants. A dropped span with no parent maps to\n * its own id: `LRUMap.remove` only deletes truthy values, so an empty-string sentinel would never be\n * evicted and would eventually fill the map, while a self-reference can never be a real parent id.\n */\n private readonly _skipped = new LRUMap<string, string>(MAX_TRACKED_MASTRA_SPANS);\n private readonly _options: MastraExporterOptions;\n private _spanOutputProcessors: MastraSpanOutputProcessor[] = [];\n\n public constructor(options: MastraExporterOptions = {}) {\n this._options = options;\n }\n\n /** Called by Mastra with the config of the observability instance this exporter belongs to. */\n public init(options: MastraExporterInitOptions): void {\n this._spanOutputProcessors = options.config?.spanOutputProcessors ?? [];\n }\n\n /** Mastra's interface is async; the work is synchronous. */\n public async exportTracingEvent(event: MastraTracingEvent): Promise<void> {\n if (!getClient()) {\n return;\n }\n\n try {\n this._handleEvent(event);\n } catch (error) {\n DEBUG_BUILD && debug.error('[Mastra] failed to export tracing event', error);\n }\n }\n\n /** Flush without closing the client — the app still owns it. */\n public async flush(): Promise<void> {\n await sentryFlush(FLUSH_TIMEOUT_MS);\n }\n\n /** End open spans, then flush. Does not close the Sentry client. */\n public async shutdown(): Promise<void> {\n for (const id of this._spans.keys()) {\n unregisterMastraSpan(id);\n }\n for (const tracked of this._spans.values()) {\n this._endSpan(tracked, {});\n }\n this._spans.clear();\n this._skipped.clear();\n await this.flush();\n }\n\n private _handleEvent(event: MastraTracingEvent): void {\n const span = event.exportedSpan;\n\n if (span.isEvent) {\n return;\n }\n\n // Unmapped types are recorded so children re-parent onto a surviving ancestor.\n if (!isExportedSpanType(span.type)) {\n if (event.type === 'span_started') {\n this._skipped.set(span.id, span.parentSpanId ?? span.id);\n } else if (event.type === 'span_ended') {\n this._skipped.remove(span.id);\n }\n return;\n }\n\n switch (event.type) {\n case 'span_started':\n this._onSpanStarted(span);\n break;\n case 'span_updated':\n this._onSpanUpdated(span);\n break;\n case 'span_ended':\n this._onSpanEnded(span);\n break;\n }\n }\n\n private _onSpanStarted(span: MastraExportedSpan): void {\n // Per span, not in the constructor: the exporter can be constructed before `Sentry.init()`, when\n // `dataCollection.genAI` does not exist yet.\n const call: MastraCallInfo = { span };\n const recordingOptions = resolveGenAiCallRecording(this._options, call);\n const parentId = this._resolveParentId(span.parentSpanId);\n const parentSpan = parentId ? this._spans.get(parentId)?.span : undefined;\n const activeSpan = getActiveSpan();\n\n const sentrySpan = startInactiveSpan({\n name: getSpanName(span),\n startTime: span.startTime,\n // Prefer the Mastra parent so the tree stays together; else the active request span.\n parentSpan: parentSpan ?? activeSpan,\n attributes: {\n ...getSpanAttributes(span, recordingOptions),\n // Only on start, so the id from `Sentry.setConversationId()`, applied on `spanStart`, is kept.\n [GEN_AI_CONVERSATION_ID]: span.attributes?.conversationId ?? span.metadata?.threadId,\n [SENTRY_OP]: getOperation(span.type)?.op,\n [SENTRY_ORIGIN]: MASTRA_ORIGIN,\n },\n });\n runGenAiSpanStart(this._options, sentrySpan, call);\n\n const evaluation = span.type === 'classifier_evaluation' ? takeStartingClassifierEvaluation() : undefined;\n if (evaluation) {\n Object.assign(evaluation, {\n span: sentrySpan,\n mastraSpan: span,\n spanOutputProcessors: this._spanOutputProcessors,\n recordInputs: recordingOptions.recordInputs,\n recordOutputs: recordingOptions.recordOutputs,\n });\n }\n\n this._trackSpan(span.id, { span: sentrySpan, call, spanType: span.type, usage: {}, recordingOptions, evaluation });\n }\n\n /** Track a started span, ending any Sentry span that would otherwise be dropped without `end()`. */\n private _trackSpan(id: string, tracked: TrackedSpan): void {\n // A duplicate `span_started` would otherwise overwrite the entry and leak its Sentry span.\n this._endTracked(id);\n\n // `LRUMap.set` evicts the oldest entry once the map is full, dropping that span without ending it.\n if (this._spans.size >= MAX_TRACKED_MASTRA_SPANS) {\n const oldestId = this._spans.keys()[0];\n if (oldestId !== undefined) {\n this._endTracked(oldestId);\n }\n }\n\n this._spans.set(id, tracked);\n // Let the `executeWithContext` channel subscriber find this Sentry span by Mastra span id.\n registerMastraSpan(id, tracked.span);\n }\n\n private _endTracked(id: string): void {\n const tracked = this._removeTracked(id);\n if (tracked) {\n this._endSpan(tracked, {});\n }\n }\n\n private _endSpan(tracked: TrackedSpan, result: GenAiSpanResult<MastraExportedSpan>, endTime?: SpanTimeInput): void {\n runGenAiSpanEnd(this._options, tracked.span, tracked.call, result);\n tracked.span.end(endTime);\n }\n\n /** Remove a tracked span and keep the id→span registry in lockstep. */\n private _removeTracked(id: string): TrackedSpan | undefined {\n unregisterMastraSpan(id);\n return this._spans.remove(id);\n }\n\n private _onSpanUpdated(span: MastraExportedSpan): void {\n const tracked = this._spans.get(span.id);\n if (tracked) {\n tracked.span.setAttributes(getSpanAttributes(span, tracked.recordingOptions));\n }\n }\n\n private _onSpanEnded(span: MastraExportedSpan): void {\n const tracked = this._spans.get(span.id);\n if (!tracked) {\n DEBUG_BUILD && debug.warn(`[Mastra] no Sentry span open for ended span ${span.id} (${span.name})`);\n return;\n }\n\n const { span: sentrySpan, recordingOptions } = tracked;\n sentrySpan.setAttributes(getSpanAttributes(span, recordingOptions));\n sentrySpan.updateName(getSpanName(span));\n\n if (MODEL_SPAN_TYPES.has(span.type)) {\n this._rollUpToParentAgent(span);\n }\n\n if (span.errorInfo) {\n // Status only — capturing here would duplicate the app's own report with a worse stack.\n sentrySpan.setStatus({ code: SPAN_STATUS_ERROR, message: span.errorInfo.message });\n }\n\n const result = span.errorInfo ? { error: span.errorInfo } : { response: span };\n const { evaluation } = tracked;\n if (evaluation && !evaluation.settled) {\n // The integration adds the call's input and answers once `evaluate()` settles, then ends the span.\n const endTime = span.endTime ?? timestampInSeconds();\n evaluation.end = () => this._endSpan(tracked, result, endTime);\n } else {\n this._endSpan(tracked, result, span.endTime);\n }\n this._removeTracked(span.id);\n }\n\n /** Copy model/usage onto the parent agent so the AI Agents view shows totals. */\n private _rollUpToParentAgent(span: MastraExportedSpan): void {\n const parentId = this._resolveParentId(span.parentSpanId);\n const parent = parentId ? this._spans.get(parentId) : undefined;\n if (!parent || !AGENT_SPAN_TYPES.has(parent.spanType)) {\n return;\n }\n\n const attrs = span.attributes ?? {};\n const rolled = mergeUsageAttributes(parent.usage, getUsageAttributes(attrs.usage));\n parent.usage = rolled;\n const model = attrs.responseModel ?? attrs.model;\n if (model !== undefined) {\n rolled[GEN_AI_RESPONSE_MODEL] = model;\n }\n parent.span.setAttributes(rolled);\n }\n\n /** Nearest exported ancestor of a dropped span. */\n private _resolveParentId(parentSpanId: string | undefined): string | undefined {\n let current = parentSpanId;\n for (let depth = 0; current; depth++) {\n const parentOfSkipped = this._skipped.get(current);\n if (parentOfSkipped === undefined) {\n return current;\n }\n if (depth >= MAX_PARENT_WALK_DEPTH) {\n DEBUG_BUILD && debug.warn('[Mastra] gave up walking a parent chain that is too deep or cyclic');\n return undefined;\n }\n // Self-reference marks a dropped span with no parent; stop and fall back to the active span.\n current = parentOfSkipped === current ? undefined : parentOfSkipped;\n }\n return undefined;\n }\n}\n","import { GLOBAL_OBJ } from '@sentry/core';\n\ntype GlobalWithRuntimes = typeof GLOBAL_OBJ & { Bun?: unknown; Deno?: unknown };\n\n/** Whether the SDK runs in Bun. */\nexport function isBun(): boolean {\n return typeof (GLOBAL_OBJ as GlobalWithRuntimes).Bun !== 'undefined';\n}\n\n/** Whether the SDK runs in Deno. */\nexport function isDeno(): boolean {\n return typeof (GLOBAL_OBJ as GlobalWithRuntimes).Deno !== 'undefined';\n}\n\n/** Whether the SDK runs in Cloudflare Workers. */\nexport function isCloudflareWorkers(): boolean {\n return GLOBAL_OBJ.navigator?.userAgent === 'Cloudflare-Workers';\n}\n","import { consoleSandbox, debug, GLOBAL_OBJ } from '@sentry/core';\nimport { isBun } from '../utils/runtime';\n\n/**\n * The module names (e.g. `mysql`, `@hapi/hapi`) orchestrion has already injected\n * into this process — from the runtime `--import` hook (`runtime`) and/or the\n * snippets a bundler transform spliced into each transformed module (`bundler`).\n * Channel-based integrations use it to decide whether to subscribe now (their\n * module is already loaded) or wait for the module-injected event.\n *\n * The `instanceof Set` guard is runtime safety, not typing: a banner from\n * another SDK copy or version may have written a non-Set flag here.\n */\nexport function getOrchestrionInjectedModules(): string[] {\n const { runtime, bundler } = GLOBAL_OBJ.__SENTRY_ORCHESTRION__ ?? {};\n return [...(runtime ?? []), ...(bundler instanceof Set ? bundler : [])];\n}\n\n/**\n * Verifies that the diagnostics channels have been injected either by the\n * runtime `--import` hook (or init-time registration), a bundler plugin, or\n * both, and warns if not. When at least one injector is active, logs for each\n * mechanism whether it hooked (a defined list, even empty, means it did) and\n * which libraries it injected. For the bundler path, the entry banner ensures\n * an empty `Set` at boot; module names arrive as each transformed module is\n * evaluated, so an empty set can also just mean none has loaded yet.\n *\n * Both injectors being active at once is fine: they operate on disjoint module\n * sets (a module is either loaded through Node's loader and transformed by the\n * runtime hook, or inlined by the bundler and transformed by the plugin), so\n * a single module can't be double-wrapped. A hybrid setup, with some deps\n * external and runtime-instrumented, others bundled and plugin-instrumented,\n * is fine.\n */\nexport function detectOrchestrionSetup(): void {\n const marker = GLOBAL_OBJ.__SENTRY_ORCHESTRION__ ?? {};\n const { runtime, bundler, channelIntegrations } = marker;\n\n if (!runtime && !bundler) {\n if (channelIntegrations && isBun()) {\n if (!marker.warnedBunRunNotInjected) {\n marker.warnedBunRunNotInjected = true;\n consoleSandbox(() => {\n // oxlint-disable-next-line no-console\n console.warn(\n '[Sentry] No diagnostics-channel injection detected. Channel-based integrations will not record ' +\n 'spans or capture errors. On Bun 1.4.6 or later, run your app with `bun --preload @sentry/bun/import`. ' +\n 'Or build your app with `@sentry/bun/plugin`.',\n );\n });\n }\n return;\n }\n\n debug.warn(\n '[Sentry] No diagnostics-channel injection detected. Channel-based integrations ' +\n 'will not record spans. Make sure the diagnostics channels are injected ' +\n 'via the runtime `--import` hook or a bundler plugin before the instrumented modules load.',\n );\n return;\n }\n\n debug.log(\n runtime\n ? `[Sentry] Runtime hook registered, injected libraries=${JSON.stringify(runtime)}`\n : '[Sentry] Runtime hook not registered',\n );\n debug.log(\n bundler\n ? `[Sentry] Bundler plugin ran, injected libraries=${JSON.stringify(\n bundler instanceof Set ? [...bundler] : bundler,\n )}`\n : '[Sentry] Bundler plugin did not run',\n );\n}\n","import type { Scope, Span } from '@sentry/core';\nimport { getCurrentScope } from '@sentry/core';\nimport type { GenAiSpanHooks, GenAiSpanResult } from '../core/span-hooks';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { GenAiCallOptions, GenAiOptions } from '../core/utils';\nimport { resolveGenAiCallRecording, resolveRecordingOption } from '../core/utils';\nimport type { PiAiCallInfo, PiAssistantMessage } from './types';\n\nconst DRIVER_KEY = 'piAiDriver';\n\n/** The options of the integration driving pi-ai, bound to its call info. */\nexport interface PiAiDriver {\n recording: () => GenAiOptions;\n onSpanStart: (span: Span) => void;\n onSpanEnd: (span: Span, result: GenAiSpanResult<PiAssistantMessage>) => void;\n}\n\n/**\n * Apply the recording options and span hooks of an integration that sends its model calls through\n * pi-ai, such as Flue, to the `gen_ai.chat` spans of the requests sent under `scope`. Options and\n * hooks that are functions get `call`.\n */\nexport function setPiAiDriverOptions<TCall>(\n scope: Scope,\n options: GenAiCallOptions<TCall> & GenAiSpanHooks<TCall, PiAssistantMessage>,\n call: TCall,\n): void {\n const driver: PiAiDriver = {\n recording: () => ({\n recordInputs: resolveRecordingOption(options.recordInputs, call),\n recordOutputs: resolveRecordingOption(options.recordOutputs, call),\n }),\n onSpanStart: span => runGenAiSpanStart(options, span, call),\n onSpanEnd: (span, result) => runGenAiSpanEnd(options, span, call, result),\n };\n scope.setSDKProcessingMetadata({ [DRIVER_KEY]: driver });\n}\n\n/** The integration driving the pi-ai requests sent from the current scope, if any. */\nexport function getPiAiDriver(): PiAiDriver | undefined {\n return getCurrentScope().getScopeData().sdkProcessingMetadata[DRIVER_KEY] as PiAiDriver | undefined;\n}\n\n/**\n * The recording options of a pi-ai request, read when it starts: its response can settle outside the\n * scope it was sent from. An explicit `false` on either integration, or from either one's function,\n * keeps the content out, since an opt-out must not depend on which integration it was set on.\n * Otherwise the integration driving pi-ai comes first, then `piAiIntegration`, then\n * `dataCollection.genAI`.\n */\nexport function resolvePiAiRecordingOptions(\n options: GenAiCallOptions<PiAiCallInfo>,\n call: PiAiCallInfo,\n driver = getPiAiDriver(),\n): Required<GenAiOptions> {\n const driverRecording = driver?.recording();\n const own = {\n recordInputs: resolveRecordingOption(options.recordInputs, call),\n recordOutputs: resolveRecordingOption(options.recordOutputs, call),\n };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(own, call);\n return {\n recordInputs: own.recordInputs !== false && (driverRecording?.recordInputs ?? recordInputs),\n recordOutputs: own.recordOutputs !== false && (driverRecording?.recordOutputs ?? recordOutputs),\n };\n}\n","export const FLUE_INTEGRATION_NAME = 'Flue' as const;\n\nexport const FLUE_MODULE_NAME = '@flue/runtime';\n\nexport const FLUE_ORIGIN = 'auto.ai.flue';\n\n/**\n * Identifies our registration in Flue's keyed instrumentation registry.\n *\n * `key` is optional, but without one there is no protection against registering twice: Flue\n * deduplicates on object identity, and `createFlueInstrumentation()` returns a new object each\n * call, so a second `instrument()` would silently add a second observer and interceptor and\n * duplicate every span.\n *\n * With a key, Flue handles the repeat itself — it throws `InstrumentationAlreadyInstalledError` in\n * production, and in dev disposes the previous registration and swaps in the new one, which is what\n * stops `vite dev` from stacking observers across reloads.\n */\nexport const FLUE_INSTRUMENTATION_KEY = Symbol.for('sentry.flue.instrumentation');\n\n/**\n * The Flue execution operations we act on.\n *\n * Only `AGENT` is spanned from the interceptor, and only at the outermost depth: its operation nests\n * inside itself once per submission. `TOOL` is intercepted to make the tool span `observe` opened\n * active, and `MODEL` to hand the conversation to the pi-ai integration, which spans the model call.\n */\nexport const FLUE_OPERATION = {\n AGENT: 'agent',\n MODEL: 'model',\n TOOL: 'tool',\n} as const;\n\n/**\n * Cap on tracked tool spans and admissions, matching `MAX_TRACKED_MASTRA_SPANS`. Both maps are keyed\n * off an id that is only removed when the matching end observation arrives; a run that is abandoned\n * mid-turn never emits one, so without a cap the map grows for the lifetime of the process.\n */\nexport const MAX_TRACKED_FLUE_SPANS = 1000;\n","import { isObjectLike, stringify } from '@sentry/core';\nimport type { GenAiMessage, GenAiMessagePart } from '../types';\n\n/**\n * Map pi-ai messages (`@earendil-works/pi-ai`, which Flue and pi-durable send) to the gen_ai\n * conventions. Sentry renders neither pi-ai's `toolResult` role nor its `toolCall` parts.\n *\n * System messages are left out: their prompt belongs in `gen_ai.system_instructions`. Messages with\n * a role the conventions do not have are left out too.\n */\nexport function piAiMessagesToGenAiMessages(messages: unknown): GenAiMessage[] {\n if (!Array.isArray(messages)) {\n return [];\n }\n\n const mapped: GenAiMessage[] = [];\n for (const message of messages) {\n if (\n !isObjectLike(message) ||\n (message.role !== 'user' && message.role !== 'assistant' && message.role !== 'toolResult')\n ) {\n continue;\n }\n\n if (message.role === 'toolResult') {\n mapped.push({\n role: 'tool',\n parts: [\n {\n type: 'tool_call_response',\n id: message.toolCallId,\n name: message.toolName,\n result: piAiContentToString(message.content),\n },\n ],\n });\n continue;\n }\n\n const parts = piAiContentToParts(message.content);\n if (parts.length) {\n mapped.push({ role: message.role, parts });\n }\n }\n return mapped;\n}\n\n/** The `gen_ai.output.messages` entry of a pi-ai assistant message, or `undefined` when it has no content. */\nexport function piAiAssistantMessageToGenAiMessage(message: unknown, finishReason?: string): GenAiMessage | undefined {\n const parts = isObjectLike(message) ? piAiContentToParts(message.content) : [];\n if (!parts.length) {\n return undefined;\n }\n return { role: 'assistant', parts, ...(finishReason ? { finish_reason: finishReason } : {}) };\n}\n\n/** pi-ai names a tool-calling stop `toolUse`; the conventions call it `tool_call`. */\nexport function piAiFinishReason(stopReason: unknown): string | undefined {\n if (typeof stopReason !== 'string' || !stopReason) {\n return undefined;\n }\n return stopReason === 'toolUse' ? 'tool_call' : stopReason;\n}\n\n/** The request fields of a pi-ai `Context` that carry the system prompt and the tools. */\nexport interface PiAiContext {\n systemPrompt?: string;\n messages?: unknown;\n tools?: unknown;\n}\n\n/**\n * The system prompt a pi-ai request sends. pi-durable sends it as positional system messages with\n * `sections` instead of `systemPrompt`, so the messages are replayed like pi-ai's own\n * `getCurrentSystemPrompt` does: `content` is appended, `sections` are patched by name.\n */\nexport function piAiSystemInstructions(context: PiAiContext): string | undefined {\n const content: string[] = [];\n const sections = new Map<string, string>();\n for (const message of piAiSystemMessages(context)) {\n const text = piAiContentText(message.content);\n if (text) {\n content.push(text);\n }\n if (isObjectLike(message.sections)) {\n for (const [name, value] of Object.entries(message.sections)) {\n if (value === null) {\n sections.delete(name);\n } else if (typeof value === 'string') {\n sections.set(name, value);\n }\n }\n }\n }\n return [content.join('\\n\\n'), ...sections.values()].filter(Boolean).join('\\n\\n') || undefined;\n}\n\n/** The tools a pi-ai request offers, with `toolsAdded` and `toolsRemoved` replayed like pi-ai's `getCurrentTools`. */\nexport function piAiToolDefinitions(context: PiAiContext): unknown[] {\n const tools = new Map<string, unknown>();\n for (const message of piAiSystemMessages(context)) {\n for (const tool of Array.isArray(message.toolsRemoved) ? message.toolsRemoved : []) {\n if (isObjectLike(tool) && typeof tool.name === 'string') {\n tools.delete(tool.name);\n }\n }\n for (const tool of Array.isArray(message.toolsAdded) ? message.toolsAdded : []) {\n if (isObjectLike(tool) && typeof tool.name === 'string') {\n tools.set(tool.name, tool);\n }\n }\n }\n return [...tools.values()];\n}\n\n/** The system messages pi-ai sends, led by the one it builds from `systemPrompt` and `tools`. */\nfunction piAiSystemMessages(context: PiAiContext): Record<string, unknown>[] {\n const hasTools = Array.isArray(context.tools) && context.tools.length > 0;\n const leading =\n context.systemPrompt || hasTools\n ? [{ role: 'system', content: context.systemPrompt ?? '', toolsAdded: context.tools }]\n : [];\n const messages = Array.isArray(context.messages) ? context.messages : [];\n return [...leading, ...messages].filter(\n (message): message is Record<string, unknown> => isObjectLike(message) && message.role === 'system',\n );\n}\n\nfunction piAiContentText(content: unknown): string {\n if (typeof content === 'string') {\n return content;\n }\n return piAiContentToParts(content)\n .filter(part => part.type === 'text')\n .map(part => part.content)\n .join('\\n');\n}\n\n/** Text-only content as its text, joined the way pi-ai joins it; anything else as its mapped parts. */\nexport function piAiContentToString(content: unknown): string | undefined {\n const parts = piAiContentToParts(content);\n return parts.every(part => part.type === 'text') ? parts.map(part => part.content).join('\\n') : stringify(parts);\n}\n\nfunction piAiContentToParts(content: unknown): GenAiMessagePart[] {\n if (typeof content === 'string') {\n return content ? [{ type: 'text', content }] : [];\n }\n if (!Array.isArray(content)) {\n return [];\n }\n return content.map(piAiPartToGenAiPart).filter((part): part is GenAiMessagePart => part !== undefined);\n}\n\n/** An image is reported by its media type only: its `data` is base64, which the conventions require to be dropped. */\nfunction piAiPartToGenAiPart(part: unknown): GenAiMessagePart | undefined {\n if (!isObjectLike(part)) {\n return undefined;\n }\n\n switch (part.type) {\n case 'text':\n // An empty text block makes Sentry render the message as \"(no value)\" instead of its tool calls.\n return typeof part.text === 'string' && part.text.trim() ? { type: 'text', content: part.text } : undefined;\n case 'thinking':\n // A redacted thinking block carries an encrypted payload, not text.\n return typeof part.thinking === 'string' && part.thinking && !part.redacted\n ? { type: 'reasoning', content: part.thinking }\n : undefined;\n case 'toolCall':\n return { type: 'tool_call', id: part.id, name: part.name, arguments: stringify(part.arguments ?? {}, String) };\n case 'image':\n return { type: 'blob', mime_type: part.mimeType };\n default:\n // Part kinds we don't know yet render as JSON rather than disappearing.\n return { type: 'object', content: part };\n }\n}\n","import type { LRUMap, Span } from '@sentry/core';\nimport {\n captureException,\n isObjectLike,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n stringify,\n withActiveSpan,\n} from '@sentry/core';\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_OPERATION_NAME,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_NAME,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport type { GenAiSpanHooks } from '../core/span-hooks';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { GenAiCallOptions } from '../core/utils';\nimport { getGenAiSpanOp, resolveGenAiCallRecording } from '../core/utils';\nimport { piAiContentToString } from '../pi-ai/messages';\nimport { FLUE_ORIGIN, MAX_TRACKED_FLUE_SPANS } from './constants';\nimport type { FlueCallInfo, FlueErrorInfo, FlueEventContext, FlueObservation } from './types';\n\n/**\n * Turn and tool spans, keyed by the id of the work they cover. Bounded, because the key is only\n * removed when the matching end observation arrives and an abandoned stream never emits one.\n */\nexport type SpanTracker = LRUMap<string, Span>;\n\nconst TOOL_SPANS_RECORDING_OUTPUTS = new WeakSet<Span>();\nconst TOOL_SPAN_END_HOOKS = new WeakMap<Span, (observation: FlueObservation) => void>();\n\n/**\n * Store a span under `key`. Callers only reach this with a key the tracker does not hold, so the\n * one span at risk of being dropped without `end()` is the oldest entry, which `LRUMap.set` silently\n * evicts once the tracker is full.\n */\nfunction trackSpan(tracker: SpanTracker, key: string, span: Span): void {\n if (tracker.size >= MAX_TRACKED_FLUE_SPANS) {\n const oldestKey = tracker.keys()[0];\n if (oldestKey !== undefined) {\n tracker.remove(oldestKey)?.end();\n }\n }\n\n tracker.set(key, span);\n}\n\n/**\n * Report a failed tool as an error event.\n *\n * Flue catches whatever the tool threw and hands it back to the model as a tool result, so nothing\n * propagates for the SDK's global handlers to see: without this a throwing tool produces an errored\n * span and no issue at all. `errorInfo` carries the original name, message and stack, so rebuild an\n * `Error` from it rather than capturing the serialized shape.\n *\n * Tools only. A failed turn carries no `errorInfo` — a provider auth failure produces an errored\n * `chat` span and nothing to rebuild from — so there is no turn equivalent to capture.\n */\nfunction captureToolError(span: Span, errorInfo: FlueErrorInfo | undefined): void {\n if (!errorInfo) {\n return;\n }\n\n const error = new Error(errorInfo.message ?? 'Flue tool failed');\n error.name = errorInfo.name ?? errorInfo.type ?? 'Error';\n if (errorInfo.stack) {\n error.stack = errorInfo.stack;\n }\n\n // Captured under the operation's own span so the issue lands on the right trace, matching how the\n // Mastra integration attaches its captures.\n withActiveSpan(span, () => {\n // Handled: this is not a rejection observed on a tracing channel, where the handled state is\n // unknowable. Flue caught the throw and returned it to the model as a tool result, so it is\n // definitively handled and no global hook will ever see it.\n captureException(error, { mechanism: { handled: true, type: FLUE_ORIGIN } });\n });\n}\n\n/**\n * Tool spans hang off the agent invocation rather than the turn, matching how Flue's own\n * OpenTelemetry adapter projects them: siblings of `chat`, correlated to model output by tool call\n * id. Keyed by `toolCallId` so concurrent tool calls in one turn cannot cross-attribute.\n */\nexport function startToolSpan(\n observation: FlueObservation,\n context: FlueEventContext,\n toolSpans: SpanTracker,\n options: GenAiCallOptions<FlueCallInfo> & GenAiSpanHooks<FlueCallInfo, FlueObservation>,\n): void {\n const { toolCallId, toolName } = observation;\n if (!toolCallId || toolSpans.get(toolCallId)) {\n return;\n }\n\n const call: FlueCallInfo = { operation: 'execute_tool', observation, context };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n const span = startInactiveSpan({\n name: `execute_tool ${toolName ?? 'unknown'}`,\n op: getGenAiSpanOp('execute_tool'),\n attributes: {\n [SENTRY_ORIGIN]: FLUE_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'execute_tool',\n [GEN_AI_TOOL_NAME]: toolName,\n [GEN_AI_CONVERSATION_ID]: observation.conversationId,\n ...(recordInputs && observation.args !== undefined\n ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(observation.args) }\n : {}),\n },\n });\n // Again after start, so the Flue id wins over one from `Sentry.setConversationId()`, as on the agent and chat spans.\n if (observation.conversationId) {\n span.setAttribute(GEN_AI_CONVERSATION_ID, observation.conversationId);\n }\n if (recordOutputs) {\n TOOL_SPANS_RECORDING_OUTPUTS.add(span);\n }\n runGenAiSpanStart(options, span, call);\n TOOL_SPAN_END_HOOKS.set(span, end =>\n runGenAiSpanEnd(options, span, call, end.isError ? { response: end, error: end.errorInfo } : { response: end }),\n );\n trackSpan(toolSpans, toolCallId, span);\n}\n\nexport function endToolSpan(observation: FlueObservation, toolSpans: SpanTracker): void {\n const { toolCallId } = observation;\n const span = toolCallId ? toolSpans.get(toolCallId) : undefined;\n if (!span || !toolCallId) {\n return;\n }\n toolSpans.remove(toolCallId);\n\n if (TOOL_SPANS_RECORDING_OUTPUTS.has(span)) {\n const result = toolResultForModel(observation);\n if (result !== undefined) {\n span.setAttribute(GEN_AI_TOOL_CALL_RESULT, result);\n }\n }\n\n if (observation.isError) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n captureToolError(span, observation.errorInfo);\n }\n TOOL_SPAN_END_HOOKS.get(span)?.(observation);\n span.end();\n}\n\n/**\n * The result the model receives: Flue's `effectiveResult` when it has one, else the content blocks\n * of its harness-level `result` (`{ content, details }`, whose `details` payload is tool-specific).\n */\nfunction toolResultForModel(observation: FlueObservation): string | undefined {\n const { effectiveResult } = observation;\n if (effectiveResult !== undefined) {\n if (typeof effectiveResult === 'string') {\n return effectiveResult;\n }\n return Array.isArray(effectiveResult) ? piAiContentToString(effectiveResult) : stringify(effectiveResult);\n }\n const { result } = observation;\n if (isObjectLike(result) && Array.isArray(result.content)) {\n return piAiContentToString(result.content);\n }\n return result === undefined ? undefined : stringify(result);\n}\n","import type { Scope, Span } from '@sentry/core';\nimport {\n consoleSandbox,\n continueTrace,\n getActiveSpan,\n getDefaultIsolationScope,\n getIsolationScope,\n LRUMap,\n sentryTraceFromTraceparent,\n startNewTrace,\n startSpan,\n withActiveSpan,\n withScope,\n} from '@sentry/core';\nimport {\n GEN_AI_AGENT_NAME,\n GEN_AI_CONVERSATION_ID,\n GEN_AI_OPERATION_NAME,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport type { GenAiSpanHooks } from '../core/span-hooks';\nimport type { GenAiCallOptions } from '../core/utils';\nimport { getGenAiSpanOp } from '../core/utils';\nimport { getOrchestrionInjectedModules } from '../../orchestrion/detect';\nimport { piAiModuleNames } from '../../orchestrion/config/pi-ai';\nimport { setPiAiDriverOptions } from '../pi-ai/recording';\nimport type { PiAssistantMessage } from '../pi-ai/types';\nimport { isBun, isCloudflareWorkers, isDeno } from '../../utils/runtime';\nimport { withCleanScopes } from '../../utils/withCleanScopes';\nimport { FLUE_INSTRUMENTATION_KEY, FLUE_OPERATION, FLUE_ORIGIN, MAX_TRACKED_FLUE_SPANS } from './constants';\nimport type { SpanTracker } from './utils';\nimport { endToolSpan, startToolSpan } from './utils';\nimport type { FlueCallInfo, FlueInstrumentation, FlueObservation } from './types';\n\n/**\n * The span hooks run for the `gen_ai.chat` spans of the model calls, which pi-ai reports, and for the\n * tool spans. `onSpanEnd` gets the `AssistantMessage` of a model call, and the `tool` observation of a\n * tool call, whose `errorInfo` is also the `error` of a failed tool. A tool call that never ends, whose\n * span is ended when the tracker evicts it or Flue disposes the instrumentation, does not run `onSpanEnd`.\n */\nexport type FlueOptions = GenAiCallOptions<FlueCallInfo> &\n GenAiSpanHooks<FlueCallInfo, PiAssistantMessage | FlueObservation>;\n\ninterface Admission {\n isolationScope: Scope;\n span: Span | undefined;\n}\n\nlet checkedPiAiInstrumentation = false;\n\n/**\n * `instrument()` works without Sentry's module hook or bundler plugin, but the pi-ai integration that\n * spans Flue's model calls doesn't. Checked on the first model call, once pi-ai has loaded.\n */\nfunction warnIfPiAiNotInstrumented(): void {\n if (checkedPiAiInstrumentation) {\n return;\n }\n checkedPiAiInstrumentation = true;\n\n const injected = getOrchestrionInjectedModules();\n if (piAiModuleNames.some(name => injected.includes(name))) {\n return;\n }\n\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn(\n '[Sentry] Flue model calls are not being traced: `@earendil-works/pi-ai` was not instrumented, so ' +\n `Flue agents record agent and tool spans but no \\`gen_ai.chat\\` spans. ${getPiAiInstrumentationHint()}`,\n );\n });\n}\n\nfunction getPiAiInstrumentationHint(): string {\n if (isBun()) {\n return 'On Bun 1.4.6 or later, run your app with `bun --preload @sentry/bun/import app.ts`. Or build it with `sentryBunPlugin()` from `@sentry/bun/plugin`.';\n }\n if (isDeno()) {\n return 'Run your app with `deno run --preload=npm:@sentry/deno/import app.ts`.';\n }\n if (isCloudflareWorkers()) {\n return 'Add `sentryCloudflareVitePlugin()` from `@sentry/cloudflare/vite` to your Vite config.';\n }\n return 'Load Sentry with `--import`, for example `node --import ./instrument.mjs app.mjs`.';\n}\n\n/**\n * Flue's Node coordinator runs every submission from one long-lived claim loop, started by the\n * first admission and keeping that call's async context for the life of the process. Left alone,\n * every agent run lands in the trace of whichever request admitted the first one\n * (https://github.com/withastro/flue/issues/813).\n */\nfunction runInAdmissionContext<T>(admission: Admission | undefined, next: () => T): T {\n // Cloudflare runs each turn from a Durable Object alarm, which already starts a trace of its own,\n // so there is no leaked context to undo there.\n if (isCloudflareWorkers()) {\n return next();\n }\n if (!admission) {\n // Admitted by another process, replayed by idempotency key, or evicted: there is nothing to\n // restore, but the loop's context still belongs to an unrelated request.\n return withCleanScopes(getDefaultIsolationScope().clone(), () => startNewTrace(next));\n }\n return withCleanScopes(admission.isolationScope, () =>\n admission.span ? withActiveSpan(admission.span, next) : startNewTrace(next),\n );\n}\n\n/**\n * Build the object to hand to `instrument()` from `@flue/runtime`.\n *\n * The two callbacks own different halves of the result:\n *\n * - `interceptor` wraps agent execution, so the agent span is *active* for its duration and every\n * span opened underneath parents correctly.\n * - `observe` opens and closes the tool spans, and names the agent span.\n *\n * Model calls get no span here: Flue sends them through pi-ai, whose integration reports each one\n * as a `gen_ai.chat` span under the agent span.\n *\n * Tool arguments and results are gated on `recordInputs`/`recordOutputs`, which fall back to the\n * current client's `dataCollection.genAI` settings and are decided when each tool span starts. The\n * same options apply to the message content of the `gen_ai.chat` spans.\n */\nexport function createFlueInstrumentation(options: FlueOptions = {}): FlueInstrumentation {\n // Keyed by the agent operation's own id, which is what the observations carry. That keeps\n // concurrent runs apart and gives a delegated subagent its own span: Flue nests a second `agent`\n // operation inside the parent's for `task` delegation, and the nesting is not bounded at two.\n // A plain map: the entry is removed in a `finally`, so it is bounded by concurrent agent runs.\n const agentSpans = new Map<string, Span>();\n // Capped, unlike the above: these are keyed off ids that only a matching end observation removes.\n const toolSpans: SpanTracker = new LRUMap(MAX_TRACKED_FLUE_SPANS);\n // Capped: a submission admitted here but run by another process never settles here.\n const admissions = new LRUMap<string, Admission>(MAX_TRACKED_FLUE_SPANS);\n\n return {\n key: FLUE_INSTRUMENTATION_KEY,\n\n interceptor: async (operation, ctx, next) => {\n // `observe` has already opened the tool span; make it active for the duration so whatever the\n // tool does lands inside it rather than beside it.\n if (operation?.type === FLUE_OPERATION.TOOL) {\n const toolSpan = operation.toolCallId ? toolSpans.get(operation.toolCallId) : undefined;\n return toolSpan ? withActiveSpan(toolSpan, next) : next();\n }\n // The `gen_ai.chat` span of the model call comes from the pi-ai integration, which reads the\n // conversation and the recording options from the scope.\n if (operation?.type === FLUE_OPERATION.MODEL) {\n warnIfPiAiNotInstrumented();\n const { conversationId } = ctx;\n return withScope(scope => {\n if (conversationId) {\n scope.setConversationId(conversationId);\n }\n setPiAiDriverOptions(scope, options, { operation: 'chat', execution: operation, context: ctx });\n return next();\n });\n }\n\n if (operation?.type !== FLUE_OPERATION.AGENT) {\n return next();\n }\n\n // A submission opens with a wrapper operation whose id *is* the submission id; the run it\n // wraps gets its own operation id, and that is the one the observations reference. Spanning\n // the wrapper too would double-count every agent invocation, but it is the outermost point of\n // every attempt, so it is where the admitting context goes back in.\n const operationId = operation.operationId;\n if (operationId && operationId === ctx.submissionId) {\n return runInAdmissionContext(admissions.get(operationId), next);\n }\n if (!operationId || agentSpans.has(operationId)) {\n return next();\n }\n\n const openAgentSpan = () =>\n startSpan(\n {\n name: `invoke_agent ${ctx.agentName ?? 'agent'}`,\n op: getGenAiSpanOp('invoke_agent'),\n attributes: {\n [SENTRY_ORIGIN]: FLUE_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'invoke_agent',\n [GEN_AI_AGENT_NAME]: ctx.agentName,\n [GEN_AI_CONVERSATION_ID]: ctx.conversationId,\n },\n },\n async (span: Span) => {\n agentSpans.set(operationId, span);\n try {\n return await next();\n } finally {\n agentSpans.delete(operationId);\n }\n },\n );\n\n // A durable or dispatched submission is run later by the coordinator, possibly in another\n // isolate or process, where nothing links it back to the request that enqueued it. Flue\n // replays that request's `traceparent` here, so continue from it — but only when no trace is\n // already active, so an in-process dispatch keeps the trace it is genuinely part of.\n const sentryTrace = ctx.traceCarrier?.traceparent\n ? sentryTraceFromTraceparent(ctx.traceCarrier.traceparent)\n : undefined;\n\n return sentryTrace && !getActiveSpan()\n ? continueTrace({ sentryTrace, baggage: undefined }, openAgentSpan)\n : openAgentSpan();\n },\n\n observe: (observation, ctx) => {\n // Observations are emitted synchronously from inside the agent operation, so the active span\n // here is the agent span the interceptor opened — tool spans parent off it without any\n // bookkeeping.\n //\n // The agent operation that gets the span is the one the observations reference, and it knows\n // neither the agent's name nor the conversation: the submission wrapper carries the name, the\n // re-entry carries the conversation, and neither opens a span. Both arrive here instead.\n const agentSpan = observation.operationId ? agentSpans.get(observation.operationId) : undefined;\n if (agentSpan) {\n if (observation.conversationId) {\n agentSpan.setAttribute(GEN_AI_CONVERSATION_ID, observation.conversationId);\n }\n if (observation.agentName) {\n agentSpan.setAttribute(GEN_AI_AGENT_NAME, observation.agentName);\n agentSpan.updateName(`invoke_agent ${observation.agentName}`);\n }\n }\n\n switch (observation.type) {\n // Emitted synchronously from inside the admitting call, so the active context is its own.\n case 'submission_queued':\n if (observation.submissionId && !isCloudflareWorkers()) {\n admissions.set(observation.submissionId, {\n isolationScope: getIsolationScope(),\n span: getActiveSpan(),\n });\n }\n return;\n case 'submission_settled':\n if (observation.submissionId) {\n admissions.remove(observation.submissionId);\n }\n return;\n case 'tool_start':\n startToolSpan(observation, ctx, toolSpans, options);\n return;\n case 'tool':\n endToolSpan(observation, toolSpans);\n return;\n default:\n return;\n }\n },\n\n // Only the tool spans are ended here. They come from `startInactiveSpan`, so nothing else will.\n // The agent spans come from `startSpan`, which ends them when its callback settles — ending them\n // here would stamp an early end time on work that is still running, and the later `end()` would\n // be ignored.\n dispose: () => {\n for (const span of toolSpans.values()) {\n span.end();\n }\n agentSpans.clear();\n admissions.clear();\n toolSpans.clear();\n },\n };\n}\n","/* eslint-disable max-lines */\nimport {\n DB_NAMESPACE,\n DB_OPERATION_NAME,\n DB_QUERY_SUMMARY,\n DB_QUERY_TEXT,\n DB_SYSTEM_NAME,\n} from '@sentry/conventions/attributes';\nimport type { SpanAttributes } from '@sentry/core';\nimport { getClient, hasSpanStreamingEnabled } from '@sentry/core';\n\nconst MAX_SUMMARY_LENGTH = 255;\n\n// A single identifier: quoted (`\"...\"`, `'...'`, or MySQL backticks) or bare. The quoted forms have\n// to be matched as a unit, otherwise an identifier containing a space or a dot is cut in half.\nconst IDENTIFIER = '(?:\"[^\"]*\"|\\'[^\\']*\\'|`[^`]*`|[^\\\\s(,;).\\'\"`]+)';\n\n// A table reference can be schema-qualified (`\"public\".\"User\"`, `db.schema.table`), with each part\n// quoted independently. The whole qualified name is the summary target, since the schema is what\n// distinguishes two same-named tables.\nconst TABLE_NAME = `${IDENTIFIER}(?:\\\\.${IDENTIFIER})*`;\n\nconst DDL_RE = new RegExp(\n `^\\\\s*(?<operation>(?:CREATE|DROP)\\\\s+(?:TABLE|INDEX)|ALTER\\\\s+TABLE)(?:\\\\s+IF\\\\s+(?:NOT\\\\s+)?EXISTS)?\\\\s+(?<table>${TABLE_NAME})`,\n 'i',\n);\n\n// SQLite upserts insert an optional conflict clause between operation and INTO\n// (`INSERT OR REPLACE INTO`, https://sqlite.org/lang_insert.html), with `REPLACE INTO` as the\n// standalone shorthand. The clause is filler like INTO — stripping it keeps upserts on the same\n// low-cardinality summary as plain inserts.\nconst INSERT_RE = new RegExp(\n `^\\\\s*(?<operation>INSERT|REPLACE)(?:\\\\s+OR\\\\s+(?:ROLLBACK|ABORT|FAIL|IGNORE|REPLACE))?\\\\s+INTO(?:\\\\s+TABLE)?\\\\s+(?<table>${TABLE_NAME})`,\n 'i',\n);\nconst UPDATE_RE = new RegExp(\n `^\\\\s*(?<operation>UPDATE)(?:\\\\s+OR\\\\s+(?:ROLLBACK|ABORT|FAIL|IGNORE|REPLACE))?\\\\s+(?<table>${TABLE_NAME})`,\n 'i',\n);\nconst DELETE_RE = new RegExp(`^\\\\s*(?<operation>DELETE)\\\\s+FROM\\\\s+(?<table>${TABLE_NAME})`, 'i');\n\nconst SELECT_RE = /^\\s*(?:\\(\\s*)?(?<operation>SELECT)\\b/i;\n\nconst PRAGMA_RE = /^\\s*(?<operation>PRAGMA)\\s+(?<command>\\S+)/i;\n\nconst TOKEN_RE = /\\b(?:FROM|JOIN)\\s+|\\(\\s*(SELECT)\\b|\\b(?:UNION|INTERSECT|EXCEPT|MINUS)\\s+(?:ALL\\s+)?(SELECT)\\b/gi;\nconst TABLE_REF_RE = new RegExp(`^${TABLE_NAME}`);\nconst COMMA_TABLE_RE = new RegExp(`^\\\\s*,\\\\s*(${TABLE_NAME})`);\nconst SUBQUERY_SELECT_RE = /^\\(\\s*(SELECT)\\b/i;\n\n/**\n * Derives a low-cardinality summary from a SQL query for use as `db.query.summary`.\n *\n * Conforms to the OTEL semantic convention for generating query summaries:\n * - Preserves original case of operations and identifiers (no normalization)\n * - Uses format: `{operation} {target1} {target2} ...`\n * - Strips filler words (INTO, FROM) from the operation\n * - Captures multiple table targets (JOINs)\n * - Handles INSERT...SELECT with both targets\n * - Truncates to 255 characters without splitting mid-value\n *\n * @see https://opentelemetry.io/docs/specs/semconv/database/database-spans/#generating-a-summary-of-the-query\n */\nexport function getSqlQuerySummary(query: string | undefined): string | undefined {\n if (!query) {\n return undefined;\n }\n\n const pragmaMatch = PRAGMA_RE.exec(query);\n if (pragmaMatch?.groups?.['operation'] && pragmaMatch.groups['command']) {\n const operation = pragmaMatch.groups['operation'];\n const command = pragmaMatch.groups['command'];\n const parenIdx = command.indexOf('(');\n return truncate(`${operation} ${parenIdx >= 0 ? command.substring(0, parenIdx) : command}`);\n }\n\n const ddlMatch = DDL_RE.exec(query);\n if (ddlMatch?.groups?.['operation'] && ddlMatch.groups['table']) {\n return truncate(`${ddlMatch.groups['operation']} ${ddlMatch.groups['table']}`);\n }\n\n const insertMatch = INSERT_RE.exec(query);\n if (insertMatch?.groups?.['operation'] && insertMatch.groups['table']) {\n const parts = [insertMatch.groups['operation'], insertMatch.groups['table']];\n const rest = query.slice(insertMatch[0].length);\n const subSelect = /\\b(SELECT)\\b/i.exec(rest);\n if (subSelect?.[1]) {\n parts.push(subSelect[1]);\n const selectTables = extractTableNames(rest.slice(subSelect.index));\n parts.push(...selectTables);\n }\n return truncate(parts.join(' '));\n }\n\n const updateMatch = UPDATE_RE.exec(query);\n if (updateMatch?.groups?.['operation'] && updateMatch.groups['table']) {\n return truncate(`${updateMatch.groups['operation']} ${updateMatch.groups['table']}`);\n }\n\n const deleteMatch = DELETE_RE.exec(query);\n if (deleteMatch?.groups?.['operation'] && deleteMatch.groups['table']) {\n return truncate(`${deleteMatch.groups['operation']} ${deleteMatch.groups['table']}`);\n }\n\n const selectMatch = SELECT_RE.exec(query);\n if (selectMatch?.groups?.['operation']) {\n const tables = extractTableNames(query.slice(selectMatch[0].length));\n if (tables.length > 0) {\n return truncate(`${selectMatch.groups['operation']} ${tables.join(' ')}`);\n }\n return selectMatch.groups['operation'];\n }\n\n return truncate(query.trim().split(/\\s+/)[0] ?? query);\n}\n\nconst LEADING_KEYWORD_RE = /^\\s*(?:\\(\\s*)*([A-Za-z]+)\\b/;\nconst CTE_MAIN_STATEMENT_RE = /\\(|\\)|\\b(SELECT|INSERT|UPDATE|DELETE|MERGE|VALUES|TABLE)\\b/gi;\n\n/**\n * Derives `db.operation.name` from a SQL query: the first operation keyword, in its original case.\n *\n * @see https://opentelemetry.io/docs/specs/semconv/registry/attributes/db/#db-operation-name\n */\nexport function getSqlOperationName(query: string | undefined): string | undefined {\n const match = query ? LEADING_KEYWORD_RE.exec(query) : null;\n const keyword = match?.[1];\n if (!query || !match || !keyword) {\n return undefined;\n }\n // Scanned from after `WITH`, so parentheses wrapping the whole query don't shift the depth.\n return keyword.toUpperCase() === 'WITH' ? getCteMainOperationName(query.slice(match[0].length)) : keyword;\n}\n\n/**\n * The operation of a `WITH` query is its main statement: the first operation keyword outside the\n * CTE bodies, which are all parenthesized. Counting parentheses is safe on a sanitized query, which\n * has no literals or comments left.\n */\nfunction getCteMainOperationName(query: string): string | undefined {\n let depth = 0;\n for (const match of query.matchAll(CTE_MAIN_STATEMENT_RE)) {\n if (match[0] === '(') {\n depth++;\n } else if (match[0] === ')') {\n depth--;\n } else if (depth === 0) {\n return match[1];\n }\n }\n return undefined;\n}\n\nfunction extractTableNames(sql: string): string[] {\n const tables: string[] = [];\n TOKEN_RE.lastIndex = 0;\n let match: RegExpExecArray | null;\n\n while ((match = TOKEN_RE.exec(sql)) !== null) {\n if (match[1] || match[2]) {\n tables.push((match[1] || match[2])!);\n continue;\n }\n\n const rest = sql.slice(match.index + match[0].length);\n\n const subqueryMatch = SUBQUERY_SELECT_RE.exec(rest);\n if (subqueryMatch?.[1]) {\n tables.push(subqueryMatch[1]);\n TOKEN_RE.lastIndex = match.index + match[0].length + subqueryMatch[0].length;\n continue;\n }\n\n const tableMatch = TABLE_REF_RE.exec(rest);\n if (!tableMatch) continue;\n tables.push(tableMatch[0]);\n\n let afterTable = rest.slice(tableMatch[0].length);\n let commaMatch: RegExpExecArray | null;\n while ((commaMatch = COMMA_TABLE_RE.exec(afterTable)) !== null) {\n if (!commaMatch[1]) break;\n tables.push(commaMatch[1]);\n afterTable = afterTable.slice(commaMatch[0].length);\n }\n }\n\n return tables;\n}\n\nfunction truncate(summary: string): string {\n if (summary.length <= MAX_SUMMARY_LENGTH) {\n return summary;\n }\n const truncated = summary.substring(0, MAX_SUMMARY_LENGTH);\n const lastSpace = truncated.lastIndexOf(' ');\n return lastSpace > 0 ? truncated.substring(0, lastSpace) : truncated;\n}\n\nlet integerLiteralRE: RegExp | undefined;\nlet mssqlIntegerLiteralRE: RegExp | undefined;\n\n/**\n * The lookbehind keeps `$n` and `?n` parameter placeholders out of the match. T-SQL has neither,\n * and `$1000` there is a money literal, so `$` only guards a placeholder outside `mssql`.\n *\n * Lazy init: constructing a lookbehind at module scope evaluates it on import and crashes\n * Safari <16.4 browser bundles that reach this file via the core barrel.\n */\nfunction getIntegerLiteralRE(dialect: SqlDialect | SqlLexerRules): RegExp {\n if (dialect === 'mssql') {\n if (!mssqlIntegerLiteralRE) {\n mssqlIntegerLiteralRE = new RegExp('(?<!\\\\?)-?\\\\b\\\\d+\\\\b', 'g');\n }\n return mssqlIntegerLiteralRE;\n }\n if (!integerLiteralRE) {\n integerLiteralRE = new RegExp('(?<![$?])-?\\\\b\\\\d+\\\\b', 'g');\n }\n return integerLiteralRE;\n}\n\n/**\n * SQL dialect variants that matter for finding the end of a string literal:\n * - `standard` (PostgreSQL, SQLite): `\"` quotes identifiers, `''` is the only in-string escape,\n * and PostgreSQL's `$$…$$` dollar quoting opens a literal.\n * - `mysql`: `\"` quotes a string literal unless `ANSI_QUOTES` is set, and `\\` escapes the next\n * character unless `NO_BACKSLASH_ESCAPES` is set. Both default to off, and mysql/mysql2 escape\n * inlined values with backslashes, so this is the mode their statements arrive in.\n * - `mssql`: `[...]` quotes an identifier, so a `'` inside one is part of the name. `\"` quotes\n * one too, unless the connection sets `QUOTED_IDENTIFIER OFF`, which tedious leaves on.\n *\n * An engine with other rules passes {@link SqlLexerRules} instead.\n */\nexport type SqlDialect = 'standard' | 'mysql' | 'mssql';\n\n/**\n * Lexer rules for an engine that no {@link SqlDialect} covers. They apply on top of `standard`. The\n * integration of that engine defines them, so a bundle without that integration does not contain them.\n */\nexport interface SqlLexerRules {\n /** Whether `#` starts a line comment. */\n hashComments?: boolean;\n /** Whether a block comment can contain other block comments. */\n nestedComments?: boolean;\n /** Whether `\\` escapes the next character in a string literal or a quoted identifier. */\n backslashEscapes?: boolean;\n /** Sticky pattern for the opening tag of a dollar-quoted literal. Defaults to the PostgreSQL tag. */\n dollarQuote?: RegExp;\n /** Returns the length of the engine-specific literal at `start`, which the lexer replaces with `?`. */\n matchLiteral?: (sql: string, start: number) => number;\n /**\n * Returns true when inline data starts at `start`. The lexer drops the query text from `start` to the\n * end, because data cannot be sanitized as SQL. `out` holds the sanitized text before `start`.\n */\n isInlineData?: (sql: string, start: number, out: string[]) => boolean;\n}\n\n/**\n * Maps a driver or `db.system.name` value to the dialect its statements are written in. Callers\n * report different spellings for one engine: knex uses the driver name, Prisma the provider name,\n * and OTel the semantic-convention name. An engine we do not know about is lexed as `standard`.\n */\nexport function toSqlDialect(system: unknown): SqlDialect {\n if (system === 'mysql' || system === 'mysql2' || system === 'mariadb') {\n return 'mysql';\n }\n if (system === 'mssql' || system === 'sqlserver' || system === 'microsoft.sql_server') {\n return 'mssql';\n }\n return 'standard';\n}\n\nconst NO_RULES: SqlLexerRules = {};\n\n// Sticky, so the scanner can test one position without slicing the query on every `$`.\nconst DOLLAR_QUOTE_RE = /\\$(?:[A-Za-z_]\\w*)?\\$/y;\n\n/**\n * Returns the index just past the run's closing `delimiter`, or -1 if the run never closes. The\n * caller cannot derive that from the index alone: a query ending in `[a]]` consumed a doubled\n * delimiter, not a closing one.\n *\n * A doubled delimiter (`''`) escapes itself in every dialect; backslash escapes are dialect- and\n * context-dependent, so the caller decides.\n */\nfunction findQuotedRunEnd(sql: string, start: number, delimiter: string, backslashEscapes: boolean): number {\n for (let i = start + 1; i < sql.length; i++) {\n const char = sql[i];\n if (backslashEscapes && char === '\\\\') {\n i++;\n } else if (char === delimiter) {\n if (sql[i + 1] !== delimiter) {\n return i + 1;\n }\n i++;\n }\n }\n return -1;\n}\n\n// An unterminated comment consumes the rest of the query.\nfunction findBlockCommentEnd(sql: string, start: number, nested: boolean): number {\n let depth = 1;\n let i = start + 2;\n while (i < sql.length && depth > 0) {\n if (sql[i] === '*' && sql[i + 1] === '/') {\n depth--;\n i += 2;\n } else if (nested && sql[i] === '/' && sql[i + 1] === '*') {\n depth++;\n i += 2;\n } else {\n i++;\n }\n }\n return i;\n}\n\n/**\n * Replaces every string literal with `?` and drops every comment, in one pass.\n *\n * Doing this by scanning rather than by regex is what keeps quote state and comment state from\n * being decided independently: a regex for `'...'` cannot see that the quote it stopped at was\n * backslash-escaped, and a regex for `--...` cannot see that the `--` sits inside a literal. Both\n * mistakes end with user data surviving into `db.query.text` and `db.query.summary`.\n *\n * Quoted identifiers are preserved — they are the table and column names the query summary is\n * built from.\n */\nfunction stripLiteralsAndComments(sql: string, dialect: SqlDialect | SqlLexerRules): string {\n const [base, rules]: [SqlDialect, SqlLexerRules] =\n typeof dialect === 'string' ? [dialect, NO_RULES] : ['standard', dialect];\n const isMysql = base === 'mysql';\n const backslashEscapes = !!rules.backslashEscapes;\n const out: string[] = [];\n let i = 0;\n\n while (i < sql.length) {\n const char = sql[i]!;\n const next = sql[i + 1];\n\n if ((char === '-' && next === '-') || ((isMysql || rules.hashComments) && char === '#')) {\n const lineEnd = sql.indexOf('\\n', i);\n i = lineEnd === -1 ? sql.length : lineEnd;\n continue;\n }\n\n if (char === '/' && next === '*') {\n i = findBlockCommentEnd(sql, i, !!rules.nestedComments);\n continue;\n }\n\n // In a dollar-quoted body (`$$body$$`, `$tag$body$tag$`) nothing has syntax meaning. Read the\n // previous character from the query, not from `out`, where a dropped comment would leave `$$`\n // looking like part of an identifier. Of the `standard` engines only PostgreSQL has dollar\n // quoting. SQLite `$name` parameters do not match the tag pattern, apart from the rare `$a$b`.\n if (base === 'standard' && char === '$' && !isIdentifierChar(sql[i - 1])) {\n const tag = matchDollarQuoteTag(sql, i, rules.dollarQuote);\n if (tag) {\n const bodyEnd = sql.indexOf(tag, i + tag.length);\n i = bodyEnd === -1 ? sql.length : bodyEnd + tag.length;\n out.push('?');\n continue;\n }\n }\n\n const identifierCloser = getIdentifierCloser(char, base);\n if (identifierCloser) {\n const runEnd = findQuotedRunEnd(sql, i, identifierCloser, backslashEscapes);\n // A run that never closes is not an identifier, so it collapses instead of being copied out.\n // Copying would carry every literal in the rest of the statement through unlexed.\n out.push(runEnd === -1 ? '?' : sql.slice(i, runEnd));\n i = runEnd === -1 ? sql.length : runEnd;\n continue;\n }\n\n if (char === \"'\" || (char === '\"' && isMysql)) {\n // A prefix like `X'1A'`, `B'01'`, `N'…'` or PostgreSQL's `E'a\\nb'` is part of the literal, so it has\n // to collapse into the same `?` instead of being left behind as a bare identifier.\n const prefix = char === \"'\" ? getLiteralPrefix(out, base) : undefined;\n if (prefix) {\n out.pop();\n }\n const runEnd = findQuotedRunEnd(sql, i, char, isMysql || backslashEscapes || prefix === 'E');\n i = runEnd === -1 ? sql.length : runEnd;\n out.push('?');\n continue;\n }\n\n const literalLength = rules.matchLiteral?.(sql, i);\n if (literalLength) {\n out.push('?');\n i += literalLength;\n continue;\n }\n if (rules.isInlineData?.(sql, i, out)) {\n break;\n }\n out.push(char);\n i++;\n }\n\n return out.join('');\n}\n\n/**\n * Returns the character that closes an identifier opened by `char`, or undefined if `char` opens\n * none. SQL Server brackets close on `]`, and `]]` escapes a `]` inside the name, which is the same\n * doubling rule `findQuotedRunEnd` applies to quotes.\n */\nfunction getIdentifierCloser(char: string, dialect: SqlDialect): string | undefined {\n if (char === '`') {\n return '`';\n }\n if (char === '\"' && dialect !== 'mysql') {\n return '\"';\n }\n return char === '[' && dialect === 'mssql' ? ']' : undefined;\n}\n\n/** Whether `char` can appear inside an identifier. `undefined` (start of query) counts as a break. */\nexport function isIdentifierChar(char: string | undefined): boolean {\n return char !== undefined && /[\\w$]/.test(char);\n}\n\n/** Returns the opening dollar-quote tag at `start` (`$$` or `$tag$`), or undefined if there is none. */\nfunction matchDollarQuoteTag(sql: string, start: number, pattern = DOLLAR_QUOTE_RE): string | undefined {\n pattern.lastIndex = start;\n return pattern.exec(sql)?.[0];\n}\n\n/**\n * Returns the literal-prefix character immediately before a `'`, if there is one: `X`/`B` for\n * hex/binary literals, `N` for a national-character literal (SQL Server, MySQL), or `E` for a\n * PostgreSQL escape string (which honors backslash escapes).\n */\nfunction getLiteralPrefix(out: string[], dialect: SqlDialect): 'X' | 'B' | 'N' | 'E' | undefined {\n const last = out[out.length - 1];\n // A prefix only counts when it stands alone — the `X` in `MAX'...'` belongs to the identifier\n if (last?.length !== 1 || isIdentifierChar(out[out.length - 2]?.slice(-1))) {\n return undefined;\n }\n\n const prefix = last.toUpperCase();\n if (prefix === 'X' || prefix === 'B' || prefix === 'N') {\n return prefix;\n }\n return prefix === 'E' && dialect === 'standard' ? 'E' : undefined;\n}\n\n/**\n * Sanitize SQL query as per the OTEL semantic conventions\n * https://opentelemetry.io/docs/specs/semconv/database/database-spans/#sanitization-of-dbquerytext\n *\n * Parameter placeholders survive: PostgreSQL `$n`, SQLite `?n`, and named forms like `:name` and\n * `@name`. Per the OTEL spec they mark a parameterized query, so only values (strings, numbers,\n * booleans) are sanitized.\n *\n * Pass `dialect` when the statement comes from a driver whose literals are not standard-quoted;\n * see {@link SqlDialect} and {@link SqlLexerRules}.\n */\nexport function sanitizeSqlQuery(\n sqlQuery: string | undefined,\n dialect: SqlDialect | SqlLexerRules = 'standard',\n): string {\n if (!sqlQuery) {\n return 'Unknown SQL Query';\n }\n\n return (\n // Strip comments and string literals first: everything below is a regex that cannot tell\n // whether it is looking at SQL syntax or at a user-supplied value.\n stripLiteralsAndComments(sqlQuery, dialect)\n .replace(/;\\s*$/, '') // Remove trailing semicolons\n .replace(/^[\\s;]+/, '') // Remove leading semicolons (T-SQL's `;WITH`)\n // Collapse whitespace to a single space (after removing comments)\n .replace(/\\s+/g, ' ')\n .trim() // Remove extra spaces and trim\n // Sanitize hex numbers\n .replace(/\\b0x[0-9A-Fa-f]+/gi, '?')\n // Sanitize boolean literals\n .replace(/\\b(?:TRUE|FALSE)\\b/gi, '?')\n // Sanitize numeric literals (preserve $n placeholders via negative lookbehind)\n .replace(/-?\\b\\d+\\.?\\d*[eE][+-]?\\d+\\b/g, '?') // Scientific notation\n .replace(/-?\\b\\d+\\.\\d+\\b/g, '?') // Decimals\n .replace(/-?\\.\\d+\\b/g, '?') // Decimals starting with dot\n .replace(getIntegerLiteralRE(dialect), '?') // Integers (NOT parameter placeholders)\n // Collapse IN clauses for cardinality (both ? and $n variants)\n .replace(/\\bIN\\b\\s*\\(\\s*\\?(?:\\s*,\\s*\\?)*\\s*\\)/gi, 'IN (?)')\n .replace(/\\bIN\\b\\s*\\(\\s*\\$\\d+(?:\\s*,\\s*\\$\\d+)*\\s*\\)/gi, 'IN ($?)')\n );\n}\n\nexport interface SqlQueryAttributes {\n [DB_QUERY_TEXT]: string | undefined;\n [DB_QUERY_SUMMARY]: string | undefined;\n [DB_OPERATION_NAME]: string | undefined;\n}\n\n/**\n * Sanitizes a collected SQL statement into the query attributes the SQL integrations attach to\n * their spans: `db.query.text`, `db.query.summary` and `db.operation.name`. All are `undefined`\n * when there is no statement, so an empty query omits the attributes instead of reporting the\n * sanitizer's fallback text.\n */\nexport function getSqlQueryAttributes(\n sqlQuery: string | undefined,\n dialect?: SqlDialect | SqlLexerRules,\n): SqlQueryAttributes {\n const queryText = (sqlQuery && sanitizeSqlQuery(sqlQuery, dialect)) || undefined;\n return {\n [DB_QUERY_TEXT]: queryText,\n [DB_QUERY_SUMMARY]: getSqlQuerySummary(queryText),\n [DB_OPERATION_NAME]: getSqlOperationName(queryText),\n };\n}\n\n/**\n * Names a SQL span with a low-cardinality name: `db.query.summary`, falling back to `db.namespace`\n * and then `db.system.name`. `fallback` is the integration's name for a span with none of those.\n *\n * New SQL integrations should name their spans with this regardless of span streaming.\n */\nexport function getLowCardinalitySqlSpanName(attributes: SpanAttributes, fallback: string): string {\n return toSpanName(attributes[DB_QUERY_SUMMARY] || attributes[DB_NAMESPACE] || attributes[DB_SYSTEM_NAME], fallback);\n}\n\n/**\n * Names a SQL span from its attributes. Streamed span names have to be low cardinality (see\n * {@link getLowCardinalitySqlSpanName}); otherwise the sanitized `db.query.text` is used, which\n * existing integrations keep for spans that aren't streamed.\n */\nexport function getSqlSpanName(attributes: SpanAttributes, fallback: string): string {\n const client = getClient();\n if (client && hasSpanStreamingEnabled(client)) {\n return getLowCardinalitySqlSpanName(attributes, fallback);\n }\n return toSpanName(attributes[DB_QUERY_TEXT], fallback);\n}\n\nfunction toSpanName(value: unknown, fallback: string): string {\n return typeof value === 'string' && value ? value : fallback;\n}\n","// Portable instrumentation for https://github.com/porsager/postgres\n// This can be used in any environment (Node.js, Cloudflare Workers, etc.)\n// without depending on OpenTelemetry module hooking.\n/* eslint-disable max-lines */\n\nimport {\n addNonEnumerableProperty,\n debug,\n getActiveSpan,\n isObjectLike,\n type Span,\n type SpanAttributes,\n SPAN_STATUS_ERROR,\n startSpanManual,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { getSqlQueryAttributes, getSqlSpanName } from '../utils/sql';\nimport {\n DB_NAMESPACE,\n DB_OPERATION_NAME,\n DB_QUERY_TEXT,\n DB_SYSTEM_NAME,\n SENTRY_OP,\n SENTRY_ORIGIN,\n SERVER_ADDRESS,\n SERVER_PORT,\n DB_RESPONSE_STATUS_CODE,\n ERROR_TYPE,\n} from '@sentry/conventions/attributes';\nimport { DB } from '@sentry/conventions/op';\n\n/** The callbacks postgres.js calls on a `Query` when it settles. */\nexport interface PostgresQuerySettlement {\n resolve?: (...args: unknown[]) => unknown;\n reject?: (...args: unknown[]) => unknown;\n}\n\nexport type PostgresConnectionContext = {\n ATTR_DB_NAMESPACE?: string;\n ATTR_SERVER_ADDRESS?: string;\n ATTR_SERVER_PORT?: string;\n};\n\nexport interface PostgresJsSqlInstrumentationOptions {\n /**\n * Whether to require a parent span for the instrumentation.\n * If set to true, the instrumentation will only create spans if there is a parent span\n * available in the current scope.\n * @default true\n */\n requireParentSpan?: boolean;\n /**\n * Hook to modify the span before it is started.\n * This can be used to set additional attributes or modify the span in any way.\n */\n requestHook?: (span: Span, sanitizedSqlQuery: string, postgresConnectionContext?: PostgresConnectionContext) => void;\n}\n\nconst CONNECTION_CONTEXT_SYMBOL = Symbol('sentryPostgresConnectionContext');\n\n// Use the same Symbol.for() markers as the Node.js OTel instrumentation\n// so that both approaches recognize each other and prevent double-wrapping.\nconst INSTRUMENTED_MARKER = Symbol.for('sentry.instrumented.postgresjs');\n// Marker to track if a query was created from an instrumented sql instance.\n// This prevents double-spanning when both the wrapper and the Node.js Query.prototype\n// fallback patch are active simultaneously.\nconst QUERY_FROM_INSTRUMENTED_SQL = Symbol.for('sentry.query.from.instrumented.sql');\n// postgres >= 4 publishes `postgres:query` without exposing the `Query`, so the native channel\n// subscriber can't read QUERY_FROM_INSTRUMENTED_SQL. It checks this marker on the active span instead.\nconst POSTGRESJS_WRAPPER_SPAN = Symbol.for('sentry.postgresjs.wrapper.span');\n\n/**\n * Instruments a postgres.js `sql` instance with Sentry tracing.\n *\n * This is a portable instrumentation function that works in any environment\n * (Node.js, Cloudflare Workers, etc.) without depending on OpenTelemetry.\n *\n * @example\n * ```javascript\n * import postgres from 'postgres';\n * import * as Sentry from '@sentry/cloudflare'; // or '@sentry/deno'\n *\n * const sql = Sentry.instrumentPostgresJsSql(\n * postgres({ host: 'localhost', database: 'mydb' })\n * );\n *\n * // All queries now create Sentry spans\n * await sql`SELECT * FROM users WHERE id = ${userId}`;\n * ```\n */\nexport function instrumentPostgresJsSql<T>(sql: T, options?: PostgresJsSqlInstrumentationOptions): T {\n if (!sql || typeof sql !== 'function') {\n DEBUG_BUILD && debug.warn('instrumentPostgresJsSql: provided value is not a valid postgres.js sql instance');\n return sql;\n }\n\n return _instrumentSqlInstance(sql, { requireParentSpan: true, ...options }) as T;\n}\n\n/**\n * Instruments a sql instance by wrapping its query execution methods.\n */\nfunction _instrumentSqlInstance(\n sql: unknown,\n options: PostgresJsSqlInstrumentationOptions,\n parentConnectionContext?: PostgresConnectionContext,\n): unknown {\n // Check if already instrumented to prevent double-wrapping\n // Using Symbol.for() ensures the marker survives proxying\n if ((sql as Record<symbol, unknown>)[INSTRUMENTED_MARKER]) {\n return sql;\n }\n\n // Wrap the sql function to intercept query creation\n const proxiedSql: unknown = new Proxy(sql as (...args: unknown[]) => unknown, {\n apply(target, thisArg, argumentsList: unknown[]) {\n const query = Reflect.apply(target, thisArg, argumentsList);\n\n if (isObjectLike(query) && 'handle' in query) {\n _wrapSingleQueryHandle(query as { handle: unknown; strings?: string[] }, proxiedSql, options);\n }\n\n return query;\n },\n get(target, prop) {\n const original = (target as unknown as Record<string | symbol, unknown>)[prop];\n\n if (typeof prop !== 'string' || typeof original !== 'function') {\n return original;\n }\n\n // Wrap methods that return PendingQuery objects (unsafe, file)\n if (prop === 'unsafe' || prop === 'file') {\n return _wrapQueryMethod(original as (...args: unknown[]) => unknown, target, proxiedSql, options);\n }\n\n // Wrap begin and reserve (not savepoint to avoid duplicate spans)\n if (prop === 'begin' || prop === 'reserve') {\n return _wrapCallbackMethod(original as (...args: unknown[]) => unknown, target, proxiedSql, options);\n }\n\n return original;\n },\n });\n\n // Use provided parent context if available, otherwise extract from sql.options\n if (parentConnectionContext) {\n (proxiedSql as Record<symbol, unknown>)[CONNECTION_CONTEXT_SYMBOL] = parentConnectionContext;\n } else {\n _attachConnectionContext(sql, proxiedSql as Record<symbol, unknown>);\n }\n\n // Mark both the original and proxy as instrumented to prevent double-wrapping\n (sql as Record<symbol, unknown>)[INSTRUMENTED_MARKER] = true;\n (proxiedSql as Record<symbol, unknown>)[INSTRUMENTED_MARKER] = true;\n\n return proxiedSql;\n}\n\n/**\n * Wraps query-returning methods (unsafe, file) to ensure their queries are instrumented.\n */\nfunction _wrapQueryMethod(\n original: (...args: unknown[]) => unknown,\n target: unknown,\n proxiedSql: unknown,\n options: PostgresJsSqlInstrumentationOptions,\n): (...args: unknown[]) => unknown {\n return function (this: unknown, ...args: unknown[]): unknown {\n const query = Reflect.apply(original, target, args);\n\n if (isObjectLike(query) && 'handle' in query) {\n _wrapSingleQueryHandle(query as { handle: unknown; strings?: string[] }, proxiedSql, options);\n }\n\n return query;\n };\n}\n\n/**\n * Wraps callback-based methods (begin, reserve) to recursively instrument Sql instances.\n * Note: These methods can also be used as tagged templates, which we pass through unchanged.\n *\n * Savepoint is not wrapped to avoid complex nested transaction instrumentation issues.\n * Queries within savepoint callbacks are still instrumented through the parent transaction's Sql instance.\n */\nfunction _wrapCallbackMethod(\n original: (...args: unknown[]) => unknown,\n target: unknown,\n parentSqlInstance: unknown,\n options: PostgresJsSqlInstrumentationOptions,\n): (...args: unknown[]) => unknown {\n return function (this: unknown, ...args: unknown[]): unknown {\n // Extract parent context to propagate to child instances\n const parentContext = (parentSqlInstance as Record<symbol, unknown>)[CONNECTION_CONTEXT_SYMBOL] as\n | PostgresConnectionContext\n | undefined;\n\n // Check if this is a callback-based call by verifying the last argument is a function\n const isCallbackBased = typeof args[args.length - 1] === 'function';\n\n if (!isCallbackBased) {\n // Not a callback-based call - could be tagged template or promise-based\n const result = Reflect.apply(original, target, args);\n // If result is a Promise (e.g., reserve() without callback), instrument the resolved Sql instance\n if (result && typeof (result as Promise<unknown>).then === 'function') {\n return (result as Promise<unknown>).then((sqlInstance: unknown) => {\n return _instrumentSqlInstance(sqlInstance, options, parentContext);\n });\n }\n return result;\n }\n\n // Callback-based call: wrap the callback to instrument the Sql instance\n const callback = (args.length === 1 ? args[0] : args[1]) as (sql: unknown) => unknown;\n const wrappedCallback = function (sqlInstance: unknown): unknown {\n const instrumentedSql = _instrumentSqlInstance(sqlInstance, options, parentContext);\n return callback(instrumentedSql);\n };\n\n const newArgs = args.length === 1 ? [wrappedCallback] : [args[0], wrappedCallback];\n return Reflect.apply(original, target, newArgs);\n };\n}\n\n/**\n * Wraps a single query's handle method to create spans.\n */\nfunction _wrapSingleQueryHandle(\n query: { handle: unknown; strings?: string[]; __sentryWrapped?: boolean },\n sqlInstance: unknown,\n options: PostgresJsSqlInstrumentationOptions,\n): void {\n // Prevent double wrapping - check if the handle itself is already wrapped\n if ((query.handle as { __sentryWrapped?: boolean })?.__sentryWrapped) {\n return;\n }\n\n // Mark this query as coming from an instrumented sql instance.\n // This prevents the Node.js Query.prototype fallback patch from double-spanning.\n (query as Record<symbol, unknown>)[QUERY_FROM_INSTRUMENTED_SQL] = true;\n\n const originalHandle = query.handle as (...args: unknown[]) => Promise<unknown>;\n\n // IMPORTANT: We must replace the handle function directly, not use a Proxy,\n // because Query.then() internally calls this.handle(), which would bypass a Proxy wrapper.\n const wrappedHandle = async function (\n this: PostgresQuerySettlement & { executed?: boolean },\n ...args: unknown[]\n ): Promise<unknown> {\n // postgres.js calls handle() from then/catch/finally — only the first call executes SQL,\n // subsequent calls are no-ops (guarded by this.executed). Skip span creation for no-ops.\n if (this.executed || !_shouldCreateSpans(options)) {\n return originalHandle.apply(this, args);\n }\n\n const queryAttributes = getSqlQueryAttributes(_reconstructQuery(query.strings));\n const sanitizedSqlQuery = queryAttributes[DB_QUERY_TEXT] ?? '';\n\n const connectionContext = sqlInstance\n ? ((sqlInstance as Record<symbol, unknown>)[CONNECTION_CONTEXT_SYMBOL] as PostgresConnectionContext | undefined)\n : undefined;\n\n const attributes: SpanAttributes = {\n [SENTRY_OP]: DB,\n [SENTRY_ORIGIN]: 'auto.db.postgresjs',\n [DB_SYSTEM_NAME]: 'postgres',\n ...queryAttributes,\n ...(connectionContext && _getConnectionAttributes(connectionContext)),\n };\n\n return startSpanManual({ name: getSqlSpanName(attributes, 'postgresjs.query'), attributes }, (span: Span) => {\n addNonEnumerableProperty(span, POSTGRESJS_WRAPPER_SPAN, true);\n\n if (options.requestHook) {\n try {\n options.requestHook(span, sanitizedSqlQuery, connectionContext);\n } catch (e) {\n span.setAttribute('sentry.hook.error', 'requestHook failed');\n DEBUG_BUILD && debug.error('Error in requestHook for PostgresJs instrumentation:', e);\n }\n }\n\n _wrapQuerySettlement(this, span, queryAttributes[DB_OPERATION_NAME]);\n\n // Handle synchronous errors that might occur before promise is created\n try {\n return originalHandle.apply(this, args);\n } catch (e) {\n span.setStatus({\n code: SPAN_STATUS_ERROR,\n message: e instanceof Error ? e.message : 'unknown_error',\n });\n span.end();\n throw e;\n }\n });\n };\n\n (wrappedHandle as { __sentryWrapped?: boolean }).__sentryWrapped = true;\n query.handle = wrappedHandle;\n}\n\n/**\n * Whether `span` was started by {@link instrumentPostgresJsSql}.\n *\n * @internal Exported for the diagnostics-channel integration.\n */\nexport function _isPostgresJsWrapperSpan(span: Span | undefined): boolean {\n return !!span && POSTGRESJS_WRAPPER_SPAN in span;\n}\n\n/**\n * Determines whether a span should be created based on the current context.\n * If `requireParentSpan` is set to true in the options, a span will\n * only be created if there is a parent span available.\n */\nfunction _shouldCreateSpans(options: PostgresJsSqlInstrumentationOptions): boolean {\n const hasParentSpan = getActiveSpan() !== undefined;\n return hasParentSpan || !options.requireParentSpan;\n}\n\n/**\n * Reconstructs the full SQL query from template strings with PostgreSQL placeholders.\n *\n * For sql`SELECT * FROM users WHERE id = ${123} AND name = ${'foo'}`:\n * strings = [\"SELECT * FROM users WHERE id = \", \" AND name = \", \"\"]\n * returns: \"SELECT * FROM users WHERE id = $1 AND name = $2\"\n *\n * @internal Exported for testing only\n */\nexport function _reconstructQuery(strings: string[] | undefined): string | undefined {\n if (!strings?.length) {\n return undefined;\n }\n if (strings.length === 1) {\n return strings[0] || undefined;\n }\n // Join template parts with PostgreSQL placeholders ($1, $2, etc.)\n return strings.reduce((acc, str, i) => (i === 0 ? str : `${acc}$${i}${str}`), '');\n}\n\n/**\n * Returns connection context attributes.\n *\n * @internal Exported for the diagnostics-channel integration.\n */\nexport function _getConnectionAttributes(connectionContext: PostgresConnectionContext): SpanAttributes {\n const attributes: SpanAttributes = {};\n\n const portNumber = connectionContext.ATTR_SERVER_PORT ? parseInt(connectionContext.ATTR_SERVER_PORT, 10) : undefined;\n const dbNamespace = connectionContext.ATTR_DB_NAMESPACE;\n const serverAddress = connectionContext.ATTR_SERVER_ADDRESS;\n\n if (dbNamespace) {\n attributes[DB_NAMESPACE] = dbNamespace;\n }\n if (serverAddress) {\n attributes[SERVER_ADDRESS] = serverAddress;\n }\n if (portNumber !== undefined && !isNaN(portNumber)) {\n attributes[SERVER_PORT] = portNumber;\n }\n\n return attributes;\n}\n\n/**\n * Builds a {@link PostgresConnectionContext} from postgres.js' parsed options\n * (which store `host`/`port` as arrays). Defaults to 'localhost'/5432.\n *\n * @internal Exported for the diagnostics-channel integration.\n */\nexport function _buildConnectionContext(options: {\n host?: string[];\n port?: number[];\n database?: string;\n}): PostgresConnectionContext {\n const host = options.host?.[0] || 'localhost';\n const port = options.port?.[0] || 5432;\n return {\n ATTR_DB_NAMESPACE: typeof options.database === 'string' && options.database !== '' ? options.database : undefined,\n ATTR_SERVER_ADDRESS: host,\n ATTR_SERVER_PORT: String(port),\n };\n}\n\n/**\n * Wrap `query.resolve`/`query.reject` so the span ends when the query settles.\n *\n * `Query extends Promise` and `async handle()` only dispatches — its promise\n * resolves immediately, long before the query completes. postgres.js signals\n * completion by calling `this.resolve`/`this.reject`, so we own the span end\n * there. Wrapping happens at handle-start because `reject` can fire\n * synchronously during dispatch and `cursor()` reassigns both before executing.\n */\nexport function _wrapQuerySettlement(\n query: PostgresQuerySettlement,\n span: Span,\n operationName: string | undefined,\n onSettle?: () => void,\n): void {\n const originalResolve = query.resolve;\n if (typeof originalResolve === 'function') {\n query.resolve = function (this: unknown, ...resolveArgs: unknown[]): unknown {\n onSettle?.();\n try {\n const command = (resolveArgs[0] as { command?: string } | undefined)?.command;\n // Re-set the operation name with the server-reported command, which is more reliable than the query text.\n span.setAttribute(DB_OPERATION_NAME, command || operationName);\n span.end();\n } catch (e) {\n DEBUG_BUILD && debug.error('[instrumentation:postgresjs] error ending span in resolve:', e);\n }\n return originalResolve.apply(this, resolveArgs);\n };\n }\n\n const originalReject = query.reject;\n if (typeof originalReject === 'function') {\n query.reject = function (this: unknown, ...rejectArgs: unknown[]): unknown {\n onSettle?.();\n try {\n const err = rejectArgs[0] as { message?: string; code?: string; name?: string } | undefined;\n span.setStatus({ code: SPAN_STATUS_ERROR, message: err?.message || 'unknown_error' });\n span.setAttribute(DB_RESPONSE_STATUS_CODE, err?.code || 'unknown');\n span.setAttribute(ERROR_TYPE, err?.name || 'unknown');\n span.end();\n } catch (e) {\n DEBUG_BUILD && debug.error('[instrumentation:postgresjs] error ending span in reject:', e);\n }\n return originalReject.apply(this, rejectArgs);\n };\n }\n}\n\n/**\n * Extracts and stores connection context from sql.options.\n */\nfunction _attachConnectionContext(sql: unknown, proxiedSql: Record<symbol, unknown>): void {\n const sqlInstance = sql as { options?: { host?: string[]; port?: number[]; database?: string } };\n if (!sqlInstance.options || typeof sqlInstance.options !== 'object') {\n return;\n }\n\n proxiedSql[CONNECTION_CONTEXT_SYMBOL] = _buildConnectionContext(sqlInstance.options);\n}\n","// Origin for the `http.server` child span that traces Hono's internal `app.request(...)` dispatches.\n// Shared by the `app.request` Proxy (`patchAppRequest`) and the orchestrion channel subscriber\n// (`instrumentInternalRequests` in `honoIntegration`), which both open this span.\nexport const INTERNAL_REQUEST_ORIGIN = 'auto.http.hono.internal_request';\n\n// Marks the Sentry request/response middleware so the span-wrapping patches never turn it into a\n// middleware span — most importantly when an auto-instrumented sub-app carrying this middleware is\n// mounted into a parent and `wrapSubAppMiddleware` wraps its handlers. Read by `wrapMiddlewareWithSpan`\n// and `resolveRouteName`.\nexport const SENTRY_HONO_MIDDLEWARE = '__SENTRY_HONO_MIDDLEWARE__';\n","// oxlint-disable-next-line typescript/no-unsafe-function-type\ntype AnyFunction = Function;\n\n/**\n * Proxy traps that expose `original` as `__sentry_original__` on a wrapping Proxy without defining it on the target,\n * which is the original itself. `functionToStringIntegration` only unwraps own properties, so the property has to\n * look like an own one too.\n */\nexport function sentryOriginalTraps<T extends AnyFunction>(\n original: AnyFunction,\n): Pick<ProxyHandler<T>, 'get' | 'getOwnPropertyDescriptor'> {\n return {\n get(target, prop, receiver) {\n if (prop === '__sentry_original__') {\n return original;\n }\n return Reflect.get(target, prop, receiver);\n },\n getOwnPropertyDescriptor(target, prop) {\n if (prop === '__sentry_original__') {\n return { value: original, writable: true, enumerable: false, configurable: true };\n }\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n };\n}\n","import { SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { HTTP_SERVER } from '@sentry/conventions/op';\nimport { debug, getActiveSpan, getOriginalFunction, startSpan, type WrappedFunction } from '@sentry/core';\nimport { INTERNAL_REQUEST_ORIGIN } from './constants';\nimport type { Env, Hono } from './honoTypes';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { sentryOriginalTraps } from './sentryOriginalTraps';\n\nconst INTERNAL_REQUEST_OP = HTTP_SERVER;\n\n// Re-entrancy guard shared with the orchestrion channel subscriber\n// (`instrumentInternalRequests` in `honoIntegration`). Both wrap the same `app.request`: this Proxy\n// calls through to the original, which — when the default integration is active — is orchestrion-\n// instrumented and publishes to the request channel. Without this guard the two stack a second,\n// identical internal-request span inside the first. The Proxy owns the span; the channel subscriber\n// reads this flag and opts out. `Symbol.for` on `globalThis` keeps it shared across copies of\n// `@sentry/server-utils`, matching the request-handling dedup markers.\nconst INTERNAL_REQUEST_SPAN_ACTIVE = Symbol.for('sentry.hono.internalRequestSpanActive');\ntype GuardCarrier = { [INTERNAL_REQUEST_SPAN_ACTIVE]?: boolean };\n\n/** Whether the instance `app.request` Proxy is currently opening an internal-request span. */\nexport function isInternalRequestSpanActive(): boolean {\n return !!(globalThis as GuardCarrier)[INTERNAL_REQUEST_SPAN_ACTIVE];\n}\n\nfunction setInternalRequestSpanActive(active: boolean): void {\n (globalThis as GuardCarrier)[INTERNAL_REQUEST_SPAN_ACTIVE] = active;\n}\n\nfunction stripQueryAndHash(path: string): string {\n const end = path.search(/[?#]/);\n return end === -1 ? path : path.slice(0, end);\n}\n\n/**\n * Derive the span-name path from an `app.request()` argument, mirroring Hono's own handling so the\n * name matches the path actually dispatched, with the query/hash stripped so they can't leak into\n * span names or inflate cardinality.\n *\n * Hono treats an absolute `http(s)://` input as a full URL and everything else as a path under\n * `http://localhost` (see `hono-base`'s `request`). We prepend that same fixed host rather than\n * resolving the string as a URL reference: resolution rewrites protocol-relative inputs\n * (`//example.com/foo` → host `example.com`, dropping the segment Hono keeps in the path) and throws\n * on inputs Hono accepts (`//`, `http:`). This runs before the underlying dispatch, so it must never\n * throw — the `catch` is a final guard against any remaining malformed input.\n */\nexport function extractPathname(input: unknown): string {\n if (typeof input === 'string') {\n try {\n const url = /^https?:\\/\\//.test(input)\n ? new URL(input)\n : new URL(`http://localhost${input.startsWith('/') ? '' : '/'}${input}`);\n return url.pathname;\n } catch {\n return stripQueryAndHash(input);\n }\n }\n\n if (input instanceof Request) {\n return new URL(input.url).pathname;\n }\n\n return input instanceof URL ? input.pathname : '/';\n}\n\n/**\n * Patches `app.request()` on a Hono instance so that each internal dispatch\n * is traced as an `http.server` span — child of whatever span is active at\n * the call site.\n *\n * `.request()` is a class field (arrow function), so this must run per-instance.\n * Idempotent: safe to call multiple times on the same instance.\n */\nexport function patchAppRequest<E extends Env>(app: Hono<E>): void {\n if (getOriginalFunction(app.request as unknown as WrappedFunction)) {\n DEBUG_BUILD && debug.log('[hono] app.request already patched — skipping.');\n return;\n }\n\n const originalRequest = app.request;\n\n app.request = new Proxy(originalRequest, {\n apply(_target, thisArg, args: [string | Request | URL, RequestInit?, ...unknown[]]) {\n const [input, requestInit, ...rest] = args;\n\n if (!getActiveSpan()) {\n return Reflect.apply(_target, thisArg, args);\n }\n\n let method = requestInit?.method ?? (input instanceof Request ? input.method : 'GET');\n method = method.toUpperCase();\n\n const path = extractPathname(input);\n\n return startSpan(\n {\n name: `${method} ${path}`,\n onlyIfParent: true,\n attributes: {\n [SENTRY_OP]: INTERNAL_REQUEST_OP,\n [SENTRY_ORIGIN]: INTERNAL_REQUEST_ORIGIN,\n },\n },\n () => {\n // The flag only needs to cover the synchronous dispatch start, where the orchestrion\n // channel would fire and open its duplicate span. `Reflect.apply` returns the pending\n // promise synchronously, so `finally` clears it before any nested `.request()` runs.\n setInternalRequestSpanActive(true);\n try {\n return Reflect.apply(_target, thisArg, [input, requestInit, ...rest]);\n } finally {\n setInternalRequestSpanActive(false);\n }\n },\n );\n },\n ...sentryOriginalTraps(originalRequest),\n });\n\n DEBUG_BUILD && debug.log('[hono] Patched app.request for internal dispatch tracing.');\n}\n","import { isObjectLike } from '@sentry/core';\n\n/**\n * Default implementation of the `shouldHandleError` callback.\n *\n * Returns `true` (capture) for 5xx errors and any error without a `status` property\n *\n * Returns `false` (skip) for 3xx and 4xx errors (they still generate spans and transactions for tracing)\n *\n * Checks any error-like value that carries a numeric `status` property. This covers\n * Hono's `HTTPException`, third-party middleware errors, and custom error subclasses.\n */\nexport function defaultShouldHandleError(error: unknown): boolean {\n if (!isObjectLike(error)) {\n return true;\n }\n\n const status = error.status;\n\n return !(typeof status === 'number' && status >= 300 && status < 500);\n}\n","import { SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { MIDDLEWARE } from '@sentry/conventions/op';\nimport {\n getActiveSpan,\n getOriginalFunction,\n getRootSpan,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n type WrappedFunction,\n} from '@sentry/core';\nimport { type MiddlewareHandler } from './honoTypes';\nimport { SENTRY_HONO_MIDDLEWARE } from './constants';\nimport { defaultShouldHandleError } from './defaultShouldHandleError';\nimport { sentryOriginalTraps } from './sentryOriginalTraps';\n\nconst MIDDLEWARE_ORIGIN = 'auto.middleware.hono';\n\n/**\n * Wraps a Hono middleware handler so that its execution is traced as a Sentry span.\n * Explicitly parents each span under the root (transaction) span so that all middleware\n * spans are siblings — even when OTel instrumentation introduces nested active contexts\n * (onion order: A → B → handler → B → A would otherwise nest B under A).\n */\nexport function wrapMiddlewareWithSpan(handler: MiddlewareHandler): MiddlewareHandler {\n // Never turn Sentry's own request/response middleware into a middleware span — e.g. when an\n // auto-instrumented sub-app carrying it is mounted into a parent and its handlers get wrapped.\n if ((handler as unknown as Record<PropertyKey, unknown>)[SENTRY_HONO_MIDDLEWARE]) {\n return handler;\n }\n\n if (getOriginalFunction(handler as unknown as WrappedFunction)) {\n return handler;\n }\n\n return new Proxy(handler, {\n async apply(_target, _thisArg, args: Parameters<MiddlewareHandler>) {\n const [context, next] = args;\n const activeSpan = getActiveSpan();\n const rootSpan = activeSpan ? getRootSpan(activeSpan) : undefined;\n const span = startInactiveSpan({\n name: handler.name || '<anonymous>',\n onlyIfParent: true,\n parentSpan: rootSpan,\n attributes: {\n [SENTRY_OP]: MIDDLEWARE,\n [SENTRY_ORIGIN]: MIDDLEWARE_ORIGIN,\n },\n });\n\n try {\n return await handler(context, next);\n } catch (error) {\n // Error capture is handled by `responseHandler` via `context.error`, so this wrapper only sets\n // span status (based on our default \"error\" conditions) and rethrows (no `captureException`).\n if (defaultShouldHandleError(error)) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n throw error;\n } finally {\n span.end();\n }\n },\n ...sentryOriginalTraps(handler),\n });\n}\n","import { debug } from '@sentry/core';\nimport type { Env, Hono, MiddlewareHandler } from './honoTypes';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { wrapMiddlewareWithSpan } from './wrapMiddlewareSpan';\n\n// oxlint-disable-next-line typescript/no-explicit-any\nconst patchedUseInstances = new WeakSet<Hono<any>>();\n// oxlint-disable-next-line typescript/no-explicit-any\nconst patchedMethodInstances = new WeakSet<Hono<any>>();\n\nconst HTTP_METHODS = ['get', 'post', 'put', 'delete', 'options', 'patch', 'all', 'query'] as const;\n\n/**\n * Patches `app.use` (instance own property) on a Hono instance to instrument middleware at registration time.\n *\n * Must be per-instance because `use` is a class field, not a prototype method.\n * Idempotent.\n */\nexport function patchAppUse<E extends Env>(app: Hono<E>): void {\n if (patchedUseInstances.has(app)) {\n DEBUG_BUILD && debug.log('[hono] app.use already patched — skipping.');\n return;\n }\n\n patchedUseInstances.add(app);\n\n app.use = new Proxy(app.use, {\n apply(target: typeof app.use, thisArg: typeof app, args: Parameters<typeof app.use>): ReturnType<typeof app.use> {\n const [first, ...rest] = args as [unknown, ...MiddlewareHandler[]];\n\n if (typeof first === 'string') {\n const wrappedHandlers = rest.map(handler => wrapMiddlewareWithSpan(handler));\n return Reflect.apply(target, thisArg, [first, ...wrappedHandlers]);\n }\n\n const allHandlers = [first as MiddlewareHandler, ...rest].map(handler => wrapMiddlewareWithSpan(handler));\n return Reflect.apply(target, thisArg, allHandlers);\n },\n });\n}\n\n/**\n * Patches HTTP method class fields to instrument inline middleware at registration time.\n *\n * For `app.get('/path', mw1, mw2, handler)`, all handlers except the last are middleware and get wrapped with spans.\n * The final handler (the route handler) is already covered by the root http.server transaction.\n */\nexport function patchHttpMethodHandlers<E extends Env>(app: Hono<E>): void {\n if (patchedMethodInstances.has(app)) {\n DEBUG_BUILD && debug.log('[hono] HTTP method handlers already patched - skipping.');\n return;\n }\n\n patchedMethodInstances.add(app);\n\n for (const method of HTTP_METHODS) {\n patchRegistrationMethod(app, method, wrapInlineMiddleware);\n }\n\n patchRegistrationMethod(app, 'on', args => {\n // .on(method, path, ...handlers) — first two args are method and path\n const [method, path, ...handlers] = args;\n return [method, path, ...wrapInlineMiddleware(handlers)];\n });\n}\n\n/**\n * Given `[path?, ...handlers]` or `[...handlers]`, wraps all handlers except the last one with spans.\n * The last handler is the route handler and is left as-is.\n */\nfunction wrapInlineMiddleware(args: unknown[]): unknown[] {\n const hasPathPrefix = typeof args[0] === 'string';\n const handlersStart = hasPathPrefix ? 1 : 0;\n const handlers = args.slice(handlersStart) as MiddlewareHandler[];\n\n if (handlers.length <= 1) {\n return args;\n }\n\n const wrapped = [...args];\n for (let i = handlersStart; i < wrapped.length - 1; i++) {\n wrapped[i] = wrapMiddlewareWithSpan(wrapped[i] as MiddlewareHandler);\n }\n return wrapped;\n}\n\nfunction patchRegistrationMethod(app: object, method: string, transformArgs: (args: unknown[]) => unknown[]): void {\n const registration: unknown = Reflect.get(app, method);\n if (typeof registration !== 'function') {\n return;\n }\n\n const patchedRegistration = new Proxy(registration, {\n apply(target, thisArg, args: unknown[]) {\n return Reflect.apply(target, thisArg, transformArgs(args));\n },\n });\n Reflect.set(app, method, patchedRegistration);\n}\n","import type { HonoRoute } from './honoTypes';\n\n// Hono stores the original (unwrapped) handler under this key when it wraps a sub-app's handlers\n// for a custom `onError`. Unwrapping it lets us inspect the real handler instead of the wrapper.\n// See https://github.com/honojs/hono/blob/9f0dadf141a3242a6c3b77462c7d33c6ce0f599d/src/hono-base.ts#L224-L226\nconst COMPOSED_HANDLER = '__COMPOSED_HANDLER';\n\n/**\n * Infers whether a Hono route entry is a middleware (rather than a route handler).\n *\n * Hono has no \"isMiddleware\" flag, so we rely on arity: middleware is `(context, next)` (arity >= 2)\n * while route handlers are `(context)` (arity < 2). `onError`-wrapped sub-app handlers are unwrapped\n * first so we check the original handler's arity, not the wrapper's `(c, next)` signature.\n * https://github.com/honojs/hono/blob/97c6fe1f12298c715eb7b2da65b4b6e0d81682bb/src/utils/handler.ts#L8\n *\n * This is only one signal — callers that must classify inline middleware sharing a method+path with\n * their handler additionally need positional information (`getMiddlewareFlags`).\n */\nexport function isMiddleware(handler: unknown): boolean {\n if (typeof handler !== 'function') {\n return false;\n }\n\n const composed = (handler as unknown as Record<string, unknown>)[COMPOSED_HANDLER];\n const original = typeof composed === 'function' ? composed : handler;\n\n return (original as (...args: unknown[]) => unknown).length >= 2;\n}\n\n/**\n * Tells for each route if it is a middleware. Hono has no flag for this. In a method+path group, the\n * last handler is the route handler (`app.get('/path', mw, handler)`). `.use()` adds middleware with\n * method `ALL` and no route handler, so for `ALL` routes the arity also counts. Arity alone is not\n * enough, because a route handler can declare an unused `next`.\n */\nexport function getMiddlewareFlags(routes: HonoRoute[]): boolean[] {\n // `\\0` cannot appear in an HTTP method or a URL path.\n const groupKey = (route: HonoRoute): string => `${route.method}\\0${route.path}`;\n const lastIndexByKey = new Map(routes.map((route, i) => [groupKey(route), i]));\n\n return routes.map(\n (route, i) => lastIndexByKey.get(groupKey(route)) !== i || (route.method === 'ALL' && isMiddleware(route.handler)),\n );\n}\n","import { debug, getOriginalFunction } from '@sentry/core';\nimport type { WrappedFunction } from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type { Hono, HonoRoute } from './honoTypes';\nimport { getMiddlewareFlags } from './isMiddleware';\nimport { patchAppRequest } from './patchAppRequest';\nimport { wrapMiddlewareWithSpan } from './wrapMiddlewareSpan';\nimport { sentryOriginalTraps } from './sentryOriginalTraps';\n\nexport type { HonoRoute };\n\n// oxlint-disable-next-line typescript/no-explicit-any\ntype HonoAny = Hono<any>;\n\nexport type RouteHookHandle = {\n activate: () => void;\n getPendingSubApps: () => Set<HonoAny>;\n};\n\ntype HonoBaseProto = {\n route?: (path: string, app: HonoAny) => HonoAny;\n __sentryRouteHook__?: RouteHookHandle;\n};\n\n/**\n * Creates the two-phase state machine for the route hook.\n *\n * - Pre-activation: collects sub-app references into a pending set.\n * - Post-activation: instruments sub-apps immediately at mount time.\n */\nfunction createRouteHook(): { handle: RouteHookHandle; onSubAppMounted: (subApp: HonoAny) => void } {\n const pendingSubApps = new Set<HonoAny>();\n let activated = false;\n\n return {\n handle: {\n activate: () => {\n activated = true;\n },\n getPendingSubApps: () => pendingSubApps,\n },\n onSubAppMounted: (subApp: HonoAny) => {\n if (activated) {\n DEBUG_BUILD && debug.log(`[hono] Instrumenting sub-app at mount time (${subApp.routes.length} routes).`);\n wrapSubAppMiddleware(subApp.routes);\n patchAppRequest(subApp);\n } else {\n DEBUG_BUILD &&\n debug.log(`[hono] Collecting sub-app for deferred instrumentation (${subApp.routes.length} routes).`);\n pendingSubApps.add(subApp);\n }\n },\n };\n}\n\n/**\n * Installs a hook on `HonoBase.prototype.route` to intercept sub-app mounting.\n *\n * `honoBaseProto` is `HonoBase.prototype`, where `route` is defined — one level above the concrete\n * subclass. Callers derive it from a live app instance (`Object.getPrototypeOf(Object.getPrototypeOf(app))`)\n * or from the `Hono` class (`Object.getPrototypeOf(Hono.prototype)`), so the instrumentation never\n * imports `hono` itself.\n *\n * Returns a handle with `activate()` and `getPendingSubApps()`.\n * Idempotent: subsequent calls return the same handle\n */\nexport function installRouteHookOnPrototype(honoBaseProto: HonoBaseProto): RouteHookHandle {\n const noopHandle: RouteHookHandle = { activate: () => {}, getPendingSubApps: () => new Set() };\n\n if (!honoBaseProto || typeof honoBaseProto.route !== 'function') {\n DEBUG_BUILD && debug.warn('[hono] Could not find HonoBase.prototype.route — sub-app instrumentation disabled.');\n return noopHandle;\n }\n\n // Already patched\n if (getOriginalFunction(honoBaseProto.route as unknown as WrappedFunction)) {\n return honoBaseProto.__sentryRouteHook__ ?? noopHandle;\n }\n\n const originalRoute = honoBaseProto.route;\n const { handle, onSubAppMounted } = createRouteHook();\n\n honoBaseProto.route = new Proxy(originalRoute, {\n apply(_target, thisArg, args: [string, HonoAny]) {\n const [, subApp] = args;\n if (subApp && Array.isArray(subApp.routes)) {\n onSubAppMounted(subApp);\n }\n\n return Reflect.apply(_target, thisArg, args);\n },\n ...sentryOriginalTraps(originalRoute),\n });\n honoBaseProto.__sentryRouteHook__ = handle;\n\n DEBUG_BUILD && debug.log('[hono] Installed route hook on HonoBase.prototype.');\n\n return handle;\n}\n\n/**\n * Wraps the middleware handlers of a sub-app's routes in spans.\n */\nexport function wrapSubAppMiddleware(routes: HonoRoute[]): void {\n const middlewareFlags = getMiddlewareFlags(routes);\n for (const [i, route] of routes.entries()) {\n if (middlewareFlags[i] && typeof route.handler === 'function') {\n route.handler = wrapMiddlewareWithSpan(route.handler);\n }\n }\n}\n","import { debug } from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type { Env, Hono } from './honoTypes';\nimport { patchAppRequest } from './patchAppRequest';\nimport { patchAppUse, patchHttpMethodHandlers } from './patchAppUse';\nimport { type RouteHookHandle, installRouteHookOnPrototype, wrapSubAppMiddleware } from './patchRoute';\n\n// Lazily set by the first call to earlyPatchHono or applyPatches.\nlet _routeHook: RouteHookHandle | undefined;\n\n/**\n * Hooks `HonoBase.prototype.route` at import time, before `sentry()` runs.\n *\n * Collecting sub-app references early ensures nothing is missed if sub-apps are mounted synchronously\n * before the `sentry()` middleware is registered. The `Hono` class is passed in by the caller (the\n * `@sentry/hono` SDK, where `hono` is a peer dependency) so this module never imports `hono` itself;\n * `HonoBase.prototype` is one level above the class prototype.\n */\nexport function earlyPatchHono(honoClass: { prototype: object }): void {\n _routeHook ??= installRouteHookOnPrototype(Object.getPrototypeOf(honoClass.prototype));\n}\n\n/**\n * Instruments a Hono app instance for Sentry tracing in middleware and route handlers.\n *\n * - `use` and `request` are per-instance class fields → must be patched on the instance.\n * - `route` is a prototype method → hooked once globally, covers all instances.\n * - Retroactively instruments sub-apps mounted before `sentry()` was called.\n */\nexport function applyPatches<E extends Env>(app: Hono<E>): void {\n // `HonoBase.prototype` (where `route` lives) is two levels up from the app instance:\n // app → Hono.prototype → HonoBase.prototype. Deriving it from the live app avoids importing `hono`.\n // Always call — installRouteHookOnPrototype is idempotent and returns existing handle when prototype already patched\n _routeHook = installRouteHookOnPrototype(Object.getPrototypeOf(Object.getPrototypeOf(app)));\n\n // `app.use` (instance own property) — wraps middleware at registration time on this instance.\n patchAppUse(app);\n\n // `app.get`, `app.post`, … (instance own properties) — wraps inline middleware (all-but-last handler).\n patchHttpMethodHandlers(app);\n\n patchAppRequest(app);\n\n _routeHook.activate();\n\n const pendingSubApps = _routeHook.getPendingSubApps();\n\n if (pendingSubApps.size > 0) {\n DEBUG_BUILD &&\n debug.log(\n `[hono] ${pendingSubApps.size} sub-app(s) were mounted before sentry(). Tracing is applied retroactively. Consider registering sentry() before calling app.route().`,\n );\n }\n\n for (const subApp of pendingSubApps) {\n wrapSubAppMiddleware(subApp.routes);\n patchAppRequest(subApp);\n }\n\n pendingSubApps.clear();\n}\n\n/**\n * Applies Sentry's Hono span patches to an app instance.\n *\n * Typed loosely (`object`) so the real `hono` `Hono<E, S, P>` type used by the `@sentry/hono` SDK is\n * accepted without a cast; internally it is treated as the vendored {@link Hono} shape.\n */\nexport function applyHonoPatches(app: object): void {\n applyPatches(app as Hono);\n}\n","import type { Context } from './honoTypes';\n\nexport type HonoRuntime = 'node' | 'bun' | 'deno' | 'cloudflare';\n\n/** The client side of the request's connection. */\nexport interface ConnInfo {\n address?: string;\n port?: number;\n transport?: string;\n addressType?: string;\n}\n\n// What the runtime adapters pass to `app.fetch` as `c.env`. The readers copy Hono's `getConnInfo` helpers,\n// which Hono 5 moved out of `hono`. The casts are unchecked, and `readConnInfo` catches a read that throws.\ntype NodeBindings = {\n incoming?: { socket?: { remoteAddress?: string; remotePort?: number; remoteFamily?: string } };\n};\ntype BunServer = {\n requestIP?: (request: Request) => { address?: string; port?: number; family?: string } | null;\n};\ntype DenoServeHandlerInfo = { remoteAddr?: { hostname?: string; port?: number; transport?: string } };\n\nconst READERS: Record<HonoRuntime, (context: Context) => ConnInfo | undefined> = {\n // https://github.com/honojs/node-server/blob/v2.1.5/src/conninfo.ts\n node: context => {\n const env = context.env as (NodeBindings & { server?: NodeBindings }) | undefined;\n const socket = (env?.server ?? env)?.incoming?.socket;\n return socket\n ? { address: socket.remoteAddress, port: socket.remotePort, addressType: socket.remoteFamily }\n : undefined;\n },\n // https://github.com/honojs/hono/blob/v4.13.13/src/adapter/bun/conninfo.ts\n bun: context => {\n const env = context.env as (BunServer & { server?: BunServer }) | undefined;\n const info = (env?.server ?? env)?.requestIP?.(context.req.raw);\n return info ? { address: info.address, port: info.port, addressType: info.family } : undefined;\n },\n // https://github.com/honojs/hono/blob/v4.13.13/src/adapter/deno/conninfo.ts\n deno: context => {\n const remoteAddr = (context.env as DenoServeHandlerInfo | undefined)?.remoteAddr;\n return remoteAddr\n ? { address: remoteAddr.hostname, port: remoteAddr.port, transport: remoteAddr.transport }\n : undefined;\n },\n // `c.env` holds the user's bindings here, so only the header is read.\n // https://github.com/honojs/hono/blob/v4.13.13/src/adapter/cloudflare-workers/conninfo.ts\n cloudflare: context => {\n const address = context.req.raw.headers.get('cf-connecting-ip');\n return address ? { address } : undefined;\n },\n};\n\n/** Gives `undefined` when the runtime object is missing or a read throws. */\nexport function readConnInfo(context: Context, runtime: HonoRuntime): ConnInfo | undefined {\n try {\n return READERS[runtime](context);\n } catch {\n return undefined;\n }\n}\n","import type { Context } from './honoTypes';\n\n/**\n * Checks whether the given Hono context has a fetch event.\n */\nexport function hasFetchEvent(c: Context): boolean {\n let hasFetchEvent = true;\n try {\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n c.event;\n } catch {\n hasFetchEvent = false;\n }\n return hasFetchEvent;\n}\n","import { addNonEnumerableProperty, isPlainObject } from '@sentry/core';\nimport type { Context, HonoRoute, MatchedHandler } from './honoTypes';\nimport { sentryOriginalTraps } from './sentryOriginalTraps';\n\n// `routeIndex` of the route handler that started last. `Symbol.for` shares it between SDK copies.\nconst ROUTE_HANDLER_INDEX = Symbol.for('sentry.hono.routeHandlerIndex');\n\n// Marks the index wrapper. The router reuses the match result for each request to a route, so without\n// it the wrappers pile up. A span wrapper does not count: a route handler from `app.use()` has one and\n// still needs this wrapper.\nconst RECORDS_ROUTE_HANDLER_INDEX = Symbol.for('sentry.hono.recordsRouteHandlerIndex');\n\nconst ON_ROUTE_HANDLER_START = Symbol.for('sentry.hono.onRouteHandlerStart');\n\nfunction isMatchedHandler(entry: unknown): entry is MatchedHandler {\n const pair: unknown = Array.isArray(entry) ? entry[0] : undefined;\n if (!Array.isArray(pair)) {\n return false;\n }\n\n const [handler, route]: unknown[] = pair;\n return (\n typeof handler === 'function' &&\n isPlainObject(route) &&\n typeof route.method === 'string' &&\n typeof route.path === 'string' &&\n typeof route.handler === 'function'\n );\n}\n\n/** The match result is internal to Hono. The SDK uses it only in the shape that `compose` reads. */\nexport function isMatchedHandlerList(handlers: unknown): handlers is MatchedHandler[] {\n return Array.isArray(handlers) && handlers.every(isMatchedHandler);\n}\n\n/**\n * Reads the match result like `hono/route` does (Hono 4.8+). Hono does not export the getter's symbol,\n * so this looks for a symbol getter that returns a match result.\n * https://github.com/honojs/hono/blob/v5.0.0-rc.1/src/helper/route/index.ts#L32-L34\n */\nexport function getMatchedHandlers(context: Context): MatchedHandler[] | undefined {\n const requestProto: object | null = Object.getPrototypeOf(context.req);\n if (!requestProto) {\n return undefined;\n }\n\n for (const key of Object.getOwnPropertySymbols(requestProto)) {\n if (typeof Object.getOwnPropertyDescriptor(requestProto, key)?.get !== 'function') {\n continue;\n }\n const matchResult: unknown = Reflect.get(context.req, key);\n if (Array.isArray(matchResult) && isMatchedHandlerList(matchResult[0])) {\n return matchResult[0];\n }\n }\n return undefined;\n}\n\n/** Runs `callback` each time a route handler of this request starts. */\nexport function onRouteHandlerStart(context: Context, callback: () => void): void {\n addNonEnumerableProperty(context, ON_ROUTE_HANDLER_START, callback);\n}\n\n/**\n * Wraps the route handlers so that each stores `c.req.routeIndex` when it starts. Hono 5 resets the\n * index after `next()` (https://github.com/honojs/hono/pull/4424).\n *\n * Wraps only if more than one route handler matched. A single one is the handler that responds. Arity\n * cannot tell if a handler calls `next()`: it does not count rest parameters or a default `next`.\n * Returns `true` if it wrapped.\n *\n * Safe to call during the request: `compose` reads each handler only when it calls it.\n */\nexport function wrapRouteHandlers(handlers: MatchedHandler[], middlewareFlags: boolean[]): boolean {\n const routeHandlerCount = middlewareFlags.filter(flag => !flag).length;\n if (routeHandlerCount < 2) {\n return false;\n }\n\n for (const [i, [pair]] of handlers.entries()) {\n if (!middlewareFlags[i]) {\n pair[0] = recordRouteHandlerIndex(pair[0]);\n }\n }\n return true;\n}\n\nfunction recordRouteHandlerIndex(handler: HonoRoute['handler']): HonoRoute['handler'] {\n if (Reflect.get(handler, RECORDS_ROUTE_HANDLER_INDEX)) {\n return handler;\n }\n\n const originalTraps = sentryOriginalTraps<HonoRoute['handler']>(handler);\n return new Proxy(handler, {\n apply(target, thisArg, args: [Context, ...unknown[]]) {\n const [context] = args;\n addNonEnumerableProperty(context, ROUTE_HANDLER_INDEX, context.req.routeIndex);\n const onStart: unknown = Reflect.get(context, ON_ROUTE_HANDLER_START);\n if (typeof onStart === 'function') {\n onStart();\n }\n return Reflect.apply(target, thisArg, args);\n },\n ...originalTraps,\n get(target, prop, receiver) {\n if (prop === RECORDS_ROUTE_HANDLER_INDEX) {\n return true;\n }\n return originalTraps.get?.(target, prop, receiver);\n },\n });\n}\n\nexport function getRecordedRouteHandlerIndex(context: Context): number | undefined {\n const index: unknown = Reflect.get(context, ROUTE_HANDLER_INDEX);\n return typeof index === 'number' ? index : undefined;\n}\n","import type { Context, HonoRoute } from './honoTypes';\nimport { SENTRY_HONO_MIDDLEWARE } from './constants';\nimport { getRecordedRouteHandlerIndex } from './matchResult';\n\n/**\n * Returns the path of the route that handles the request, or `undefined` if the request has no route.\n * Not the last matched route: a catch-all registered later also matches.\n */\nexport function resolveRouteName(\n context: Context,\n routes: HonoRoute[],\n middlewareFlags: boolean[],\n): string | undefined {\n const recordedIndex = getRecordedRouteHandlerIndex(context);\n const recorded = recordedIndex === undefined ? undefined : routes[recordedIndex];\n if (recorded) {\n return recorded.path;\n }\n\n // Hono runs the first matched route handler first. If a middleware returned early, it is the one that\n // would have run.\n const firstRouteHandler = routes.find((_route, i) => !middlewareFlags[i]);\n if (firstRouteHandler) {\n return firstRouteHandler.path;\n }\n\n // Only middleware matched, for example `app.use('/static/*', serveStatic())`. The Sentry middleware\n // and `/*` middleware say nothing about the route.\n for (let i = routes.length - 1; i >= 0; i--) {\n const route = routes[i];\n if (route && route.path !== '/*' && !isSentryMiddleware(route.handler)) {\n return route.path;\n }\n }\n return undefined;\n}\n\nfunction isSentryMiddleware(handler: unknown): boolean {\n return typeof handler === 'function' && Boolean(Reflect.get(handler, SENTRY_HONO_MIDDLEWARE));\n}\n","import {\n captureException,\n getActiveSpan,\n getClient,\n getDefaultIsolationScope,\n getIsolationScope,\n getRootSpan,\n INTERNAL_setSegmentNameSourceIfSegment,\n updateSpanName,\n type Scope,\n type Span,\n type SpanAttributes,\n spanToJSON,\n winterCGHeadersToDict,\n winterCGRequestToRequestData,\n} from '@sentry/core';\nimport { getClientIPAddress } from '@sentry/core/server';\nimport type { Context } from './honoTypes';\nimport { type HonoRuntime, readConnInfo } from './connInfo';\nimport { hasFetchEvent } from './hono-context';\nimport { defaultShouldHandleError } from './defaultShouldHandleError';\nimport { getMiddlewareFlags } from './isMiddleware';\nimport { getMatchedHandlers, onRouteHandlerStart, wrapRouteHandlers } from './matchResult';\nimport { resolveRouteName } from './resolveRouteName';\nimport { type SentryHonoMiddlewareOptions } from './types';\nimport {\n CLIENT_ADDRESS,\n CLIENT_PORT,\n HTTP_ROUTE,\n NETWORK_PEER_ADDRESS,\n NETWORK_PEER_PORT,\n NETWORK_TRANSPORT,\n NETWORK_TYPE,\n} from '@sentry/conventions/attributes';\n\n/**\n * Request handler for Hono framework\n */\nexport function requestHandler(context: Context, runtime: HonoRuntime): void {\n const isolationScope = getCurrentIsolationScope();\n // Read now: when a route handler starts, a user span can be active.\n const span = getActiveSpan();\n\n // Hono 5 removes `c.req.matchedRoutes`. Before Hono 4.8, it is the only source.\n const matchedHandlers = getMatchedHandlers(context);\n const routes = matchedHandlers?.map(([[, route]]) => route) ?? context.req.matchedRoutes ?? [];\n const middlewareFlags = getMiddlewareFlags(routes);\n const nameSpan = (): void =>\n updateSpanRouteName(isolationScope, span, context, resolveRouteName(context, routes, middlewareFlags));\n\n // Name early, so that events from the handlers carry the route.\n nameSpan();\n\n // A route handler that calls `next()` passes the request on, so rename when each one starts. Without\n // the getter, only the Context hook can wrap the route handlers.\n if (!matchedHandlers || wrapRouteHandlers(matchedHandlers, middlewareFlags)) {\n onRouteHandlerStart(context, nameSpan);\n }\n\n isolationScope.setSDKProcessingMetadata({\n normalizedRequest: winterCGRequestToRequestData(hasFetchEvent(context) ? context.event.request : context.req.raw),\n });\n\n setConnInfoAttributes(context, runtime, isolationScope);\n}\n\nfunction getCurrentIsolationScope(): Scope {\n const defaultScope = getDefaultIsolationScope();\n const currentIsolationScope = getIsolationScope();\n\n return defaultScope === currentIsolationScope ? defaultScope : currentIsolationScope;\n}\n\n/**\n * Adds HTTP connection info (client IP, port, transport, address type) from the runtime to the root\n * (server) span and the isolation scope.\n *\n * Keeps attributes that the runtime SDK already set: it reads forwarding headers, while the runtime\n * objects only know the socket peer, which can be a proxy.\n */\nfunction setConnInfoAttributes(context: Context, runtime: HonoRuntime, isolationScope: Scope): void {\n const activeSpan = getActiveSpan();\n if (!activeSpan) {\n return;\n }\n\n const connInfo = readConnInfo(context, runtime);\n if (!connInfo) {\n return;\n }\n\n const { address, port, transport, addressType } = connInfo;\n\n // Only collect client IP if `userInfo` is enabled (this is primarily for setting data with `.setUser`, but in this case we cannot check for `dataCollection.headers` or similar)\n const ipAddress = address && getClient()?.getDataCollectionOptions().userInfo ? address : undefined;\n\n const rootSpan = getRootSpan(activeSpan);\n const existingAttributes = spanToJSON(rootSpan).attributes ?? {};\n // Pair `client.port` only with the socket address: behind a proxy, the socket port is the proxy's.\n const writesClientAddress = ipAddress !== undefined && existingAttributes[CLIENT_ADDRESS] === undefined;\n rootSpan.setAttributes(\n onlyNewAttributes(\n {\n [CLIENT_PORT]: writesClientAddress ? port : undefined,\n [NETWORK_PEER_PORT]: port,\n [NETWORK_TRANSPORT]: transport,\n [NETWORK_TYPE]: addressType?.toLowerCase(),\n [CLIENT_ADDRESS]: ipAddress,\n [NETWORK_PEER_ADDRESS]: ipAddress,\n },\n existingAttributes,\n ),\n );\n\n if (ipAddress) {\n // Like `RequestData`, prefer the forwarding header: behind a proxy, the socket address is the proxy's.\n const userIpAddress = getClientIPAddress(winterCGHeadersToDict(context.req.raw.headers)) || ipAddress;\n isolationScope.setUser({ ...isolationScope.getUser(), ip_address: userIpAddress });\n }\n}\n\n/** Keeps the defined attributes that are not on the span yet. */\nfunction onlyNewAttributes(attributes: SpanAttributes, existingAttributes: Record<string, unknown>): SpanAttributes {\n return Object.fromEntries(\n Object.entries(attributes).filter(([key, value]) => value !== undefined && existingAttributes[key] === undefined),\n );\n}\n\n/**\n * Response handler for Hono framework\n */\nexport function responseHandler(\n context: Context,\n shouldHandleError?: SentryHonoMiddlewareOptions['shouldHandleError'],\n): void {\n captureContextError(context, shouldHandleError);\n}\n\n/**\n * Captures an unhandled context error, gated by the user's `shouldHandleError` (or the default).\n *\n * A deduplicated middleware calls it directly to report the error of its own context — e.g. the inner\n * context of an internal `.request()` whose route threw but whose failed response the outer handler\n * swallowed.\n */\nexport function captureContextError(\n context: Context,\n shouldHandleError?: SentryHonoMiddlewareOptions['shouldHandleError'],\n): void {\n if (context.error) {\n if ((shouldHandleError ?? defaultShouldHandleError)(context.error)) {\n captureException(context.error, {\n mechanism: { handled: false, type: 'auto.http.hono.context_error' },\n });\n }\n }\n}\n\nfunction updateSpanRouteName(\n isolationScope: Scope,\n activeSpan: Span | undefined,\n context: Context,\n route: string | undefined,\n): void {\n // Without a route, keep the span name from the runtime.\n if (route === undefined) {\n return;\n }\n\n const routeName = `${context.req.method} ${route}`;\n\n if (activeSpan) {\n activeSpan.updateName(routeName);\n\n const rootSpan = getRootSpan(activeSpan);\n updateSpanName(rootSpan, routeName);\n INTERNAL_setSegmentNameSourceIfSegment(rootSpan, 'route');\n rootSpan.setAttribute(HTTP_ROUTE, route);\n }\n\n isolationScope.setTransactionName(routeName);\n}\n","import { addNonEnumerableProperty, getDefaultIsolationScope, getIsolationScope } from '@sentry/core';\nimport type { HonoRuntime } from './connInfo';\nimport { SENTRY_HONO_MIDDLEWARE } from './constants';\nimport type { Context, MiddlewareHandler } from './honoTypes';\nimport { captureContextError, requestHandler, responseHandler } from './middlewareHandlers';\nimport type { SentryHonoMiddlewareOptions } from './types';\n\n// `Symbol.for` (global registry) so the markers are shared even if this module is evaluated from more\n// than one copy of `@sentry/server-utils`.\nconst HONO_REQUEST_HANDLED = Symbol.for('sentry.hono.requestHandled');\n// The effective `shouldHandleError` for the request, recorded even by a deduplicated middleware so a\n// user-provided callback wins over the default (see below).\nconst HONO_SHOULD_HANDLE_ERROR = Symbol.for('sentry.hono.shouldHandleError');\n\nexport interface CreateHonoRequestMiddlewareOptions {\n /** Selects where the connection info is read from. */\n runtime: HonoRuntime;\n\n /** Static `shouldHandleError` callback (Node/Bun/Deno). */\n shouldHandleError?: SentryHonoMiddlewareOptions['shouldHandleError'];\n\n /**\n * Resolves `shouldHandleError` per request from the context. Cloudflare accepts\n * middleware options as a function of `env`, so the callback is only known once a\n * request comes in. When provided, this wins over the static `shouldHandleError`.\n */\n resolveShouldHandleError?: (context: Context) => SentryHonoMiddlewareOptions['shouldHandleError'];\n}\n\n/**\n * The object that carries the per-request dedup/config markers.\n *\n * Prefer the per-request isolation scope over the Hono `Context`, so the request is treated as one\n * even when several Sentry middlewares run for it:\n * - a mounted sub-app that carries its own auto-registered middleware (same context, same scope),\n * - an internal `app.request()` dispatch, which runs in a *new* Hono context but the *same*\n * isolation scope (so it must not re-record the transaction name or overwrite the request data),\n * - a manual `sentry()` middleware registered alongside the auto-instrumentation.\n *\n * When there is no per-request isolation scope (the default scope), fall back to the context so that\n * at least same-context duplicates are still deduplicated.\n */\nfunction getRequestScope(context: Context): Record<PropertyKey, unknown> {\n const isolationScope = getIsolationScope();\n const target: object = isolationScope === getDefaultIsolationScope() ? context : isolationScope;\n return target as Record<PropertyKey, unknown>;\n}\n\n/**\n * Builds the core Sentry request/response Hono middleware: it names the transaction, records the\n * request, and captures unhandled context errors around `next()`.\n *\n * Idempotent per request (see {@link getRequestScope}), so duplicate registrations — a manual\n * `sentry()` alongside the auto-instrumentation, mounted sub-apps, internal `.request()` dispatches —\n * are all safe and run the handling exactly once.\n *\n * A user-provided `shouldHandleError` still takes effect even when the middleware carrying it is\n * deduplicated behind the auto-instrumentation (which is prepended first, per request, from the\n * `Context` constructor hook): the deduplicated middleware records its callback on the request scope, and the\n * middleware that actually runs `responseHandler` uses it in preference to its own default.\n */\nexport function createHonoRequestMiddleware(options: CreateHonoRequestMiddlewareOptions): MiddlewareHandler {\n const middleware: MiddlewareHandler = async (context, next) => {\n const scope = getRequestScope(context);\n\n const shouldHandleError = options.resolveShouldHandleError\n ? options.resolveShouldHandleError(context)\n : options.shouldHandleError;\n // Record a user-provided callback so it wins even if this middleware is deduplicated. Runs before\n // the dedup check so a later manual `sentry({ shouldHandleError })` overrides the auto default.\n if (shouldHandleError) {\n addNonEnumerableProperty(scope, HONO_SHOULD_HANDLE_ERROR, shouldHandleError);\n }\n\n if (scope[HONO_REQUEST_HANDLED]) {\n await next();\n // A deduplicated middleware still reports errors from its own context — e.g. an inner\n // `.request()` whose route threw but whose failed response the outer handler swallowed, so the\n // outer context never sees the error. Route naming and request data stay owned by the request\n // that ran first, so only the error is captured here.\n const dedupShouldHandleError =\n (scope[HONO_SHOULD_HANDLE_ERROR] as SentryHonoMiddlewareOptions['shouldHandleError']) ?? shouldHandleError;\n captureContextError(context, dedupShouldHandleError);\n return;\n }\n addNonEnumerableProperty(scope, HONO_REQUEST_HANDLED, true);\n\n try {\n requestHandler(context, options.runtime);\n\n await next(); // Handler runs in between Request above ⤴ and Response below ⤵\n\n const effectiveShouldHandleError =\n (scope[HONO_SHOULD_HANDLE_ERROR] as SentryHonoMiddlewareOptions['shouldHandleError']) ?? shouldHandleError;\n responseHandler(context, effectiveShouldHandleError);\n } finally {\n // An isolation scope that outlives the request (e.g. forked once around the whole server on a\n // runtime without per-request isolation) must not dedupe the next request against this one.\n addNonEnumerableProperty(scope, HONO_REQUEST_HANDLED, undefined);\n addNonEnumerableProperty(scope, HONO_SHOULD_HANDLE_ERROR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AM,oBAAoB,QAAQ,2BAC9B,QAAQ,yBAAyB,OAAO,IACxC,QAAQ;EAGZ,IAAI,mBACFC,CAAAA,GAAAA,aAAAA,yBAAAA,CAAyB,OAAO,0BAA0B,iBAAiB;EAG7E,IAAI,MAAM,uBAAuB;GAC/B,MAAM,KAAK;GAOX,oBAAoB,SADjB,MAAM,6BAAkF,iBACxC;GACnD;EACF;EACAA,CAAAA,GAAAA,aAAAA,yBAAAA,CAAyB,OAAO,sBAAsB,IAAI;EAE1D,IAAI;GACF,eAAe,SAAS,QAAQ,OAAO;GAEvC,MAAM,KAAK;GAIX,gBAAgB,SADb,MAAM,6BAAkF,iBACxC;EACrD,UAAU;GAGRA,CAAAA,GAAAA,aAAAA,yBAAAA,CAAyB,OAAO,sBAAsB,KAAA,CAAS;GAC/DA,CAAAA,GAAAA,aAAAA,yBAAAA,CAAyB,OAAO,0BAA0B,KAAA,CAAS;EACrE;CACF;CAEAA,CAAAA,GAAAA,aAAAA,yBAAAA,CAAyB,YAAY,wBAAwB,IAAI;CACjE,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"exports.js","names":["getActiveSpan","getRootSpan","spanToJSON","SENTRY_OP","HTTP_REQUEST_METHOD","HTTP_METHOD","HTTP_ROUTE","SENTRY_SEGMENT_NAME_SOURCE","getAsyncContextStrategy","getMainCarrier","AsyncLocalStorage","getDefaultCurrentScope","getDefaultIsolationScope","isContinuingTrace","generateTraceId","_INTERNAL_safeMathRandom","setAsyncContextStrategy","registerExternalPropagationContext","trace","isSpanContextValid","defineIntegration","dsnFromString","SENTRY_API_VERSION","FUNCTION","getClient","DEBUG_BUILD","debug","isObjectLike","GEN_AI_USAGE_INPUT_TOKENS","GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS","GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS","GEN_AI_USAGE_OUTPUT_TOKENS","GEN_AI_USAGE_TOTAL_TOKENS","stringify","setOutputMessagesAttribute","GEN_AI_OUTPUT_MESSAGES","SPAN_STATUS_ERROR","GEN_AI_RESPONSE_STREAMING","GEN_AI_RESPONSE_ID","GEN_AI_RESPONSE_MODEL","GEN_AI_USAGE_REASONING_OUTPUT_TOKENS","GEN_AI_RESPONSE_FINISH_REASONS","GEN_AI_RESPONSE_TEXT","GEN_AI_RESPONSE_TOOL_CALLS","isThenable","DEBUG_BUILD","debug","spanToJSON","GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK","timestampInSeconds","getDecisionInputMessages","toStateMessages","isObjectLike","addResponseAttributes","GEN_AI_RESPONSE_ID","GEN_AI_RESPONSE_MODEL","GEN_AI_CONVERSATION_ID","isObjectLike","GEN_AI_RESPONSE_FINISH_REASONS","GEN_AI_RESPONSE_TEXT","GEN_AI_RESPONSE_TOOL_CALLS","GEN_AI_OUTPUT_MESSAGES","GEN_AI_USAGE_INPUT_TOKENS","GEN_AI_USAGE_OUTPUT_TOKENS","GEN_AI_USAGE_TOTAL_TOKENS","GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS","GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS","GEN_AI_USAGE_REASONING_OUTPUT_TOKENS","extractRequestParameters","GEN_AI_REQUEST_MODEL","GEN_AI_REQUEST_TEMPERATURE","GEN_AI_REQUEST_TOP_P","GEN_AI_REQUEST_FREQUENCY_PENALTY","GEN_AI_REQUEST_PRESENCE_PENALTY","SPAN_STATUS_ERROR","captureException","instrumentStream","DEBUG_BUILD","debug","extractRequestAttributes","GEN_AI_PROVIDER_NAME","GEN_AI_OPERATION_NAME","SENTRY_ORIGIN","GEN_AI_TOOL_DEFINITIONS","extractRequestParameters","GEN_AI_INPUT_MESSAGES","getDecisionInputMessages","GEN_AI_REQUEST_MODEL","addRequestAttributes","GEN_AI_EMBEDDINGS_INPUT","stringify","GEN_AI_SYSTEM_INSTRUCTIONS","instrumentMethod","getClient","hasSpanStreamingEnabled","startSpanManual","instrumentStream","startSpan","addResponseAttributes","createDeepProxy","GEN_AI_SYSTEM_INSTRUCTIONS","GEN_AI_INPUT_MESSAGES","stringify","SPAN_STATUS_ERROR","captureException","GEN_AI_RESPONSE_TEXT","GEN_AI_RESPONSE_TOOL_CALLS","GEN_AI_RESPONSE_ID","GEN_AI_RESPONSE_MODEL","addResponseAttributes","isObjectLike","SPAN_STATUS_ERROR","processEvent","captureException","getClient","withIsolationScope","getDefaultCurrentScope","withScope","SPAN_STATUS_ERROR","withScope","getIsolationScope","startInactiveSpan","GEN_AI_INVOKE_AGENT","SENTRY_ORIGIN","GEN_AI_OPERATION_NAME","GEN_AI_PROVIDER_NAME","GEN_AI_CONVERSATION_ID","withActiveSpan","getActiveSpan","getCurrentScope","getDefaultCurrentScope","getDefaultIsolationScope","startNewTrace","getOriginalFunction","fill","startSpan","GEN_AI_EXECUTE_TOOL","GEN_AI_TOOL_NAME","GEN_AI_TOOL_DESCRIPTION","GEN_AI_TOOL_CALL_ARGUMENTS","stringify","handleCallbackErrors","GEN_AI_TOOL_CALL_RESULT","captureException","extractRequestAttributes","GEN_AI_PROVIDER_NAME","GEN_AI_OPERATION_NAME","SENTRY_ORIGIN","GEN_AI_TOOL_DEFINITIONS","GEN_AI_REQUEST_MODEL","GEN_AI_REQUEST_TEMPERATURE","GEN_AI_REQUEST_TOP_P","GEN_AI_REQUEST_TOP_K","GEN_AI_REQUEST_FREQUENCY_PENALTY","GEN_AI_REQUEST_MAX_TOKENS","addPrivateRequestAttributes","startSpanManual","instrumentMethod","getClient","hasSpanStreamingEnabled","startSpan","addResponseAttributes","isObjectLike","GEN_AI_OUTPUT_MESSAGES","isObjectLike","stringify","GEN_AI_OUTPUT_MESSAGES","SPAN_STATUS_ERROR","captureException","processChunk","GEN_AI_REQUEST_TEMPERATURE","GEN_AI_REQUEST_TOP_P","GEN_AI_REQUEST_TOP_K","GEN_AI_REQUEST_MAX_TOKENS","GEN_AI_REQUEST_FREQUENCY_PENALTY","GEN_AI_REQUEST_PRESENCE_PENALTY","extractRequestAttributes","GEN_AI_PROVIDER_NAME","GEN_AI_OPERATION_NAME","SENTRY_ORIGIN","GEN_AI_REQUEST_MODEL","GEN_AI_TOOL_DEFINITIONS","GEN_AI_INPUT_MESSAGES","GEN_AI_EMBEDDINGS_INPUT","stringify","GEN_AI_SYSTEM_INSTRUCTIONS","addResponseAttributes","GEN_AI_RESPONSE_MODEL","GEN_AI_USAGE_REASONING_OUTPUT_TOKENS","GEN_AI_RESPONSE_TEXT","GEN_AI_RESPONSE_TOOL_CALLS","instrumentMethod","getClient","hasSpanStreamingEnabled","startSpanManual","startSpan","handleCallbackErrors","createDeepProxy","getSpanName","GEN_AI_REQUEST_MODEL","GEN_AI_REQUEST_TEMPERATURE","GEN_AI_REQUEST_TOP_P","GEN_AI_REQUEST_MAX_TOKENS","GEN_AI_REQUEST_FREQUENCY_PENALTY","GEN_AI_REQUEST_PRESENCE_PENALTY","GEN_AI_REQUEST_SEED","addResponseAttributes","GEN_AI_RESPONSE_ID","GEN_AI_RESPONSE_MODEL","GEN_AI_USAGE_INPUT_TOKENS","GEN_AI_USAGE_OUTPUT_TOKENS","GEN_AI_USAGE_TOTAL_TOKENS","GEN_AI_RESPONSE_FINISH_REASONS","GEN_AI_RESPONSE_TEXT","GEN_AI_RESPONSE_TOOL_CALLS","setOutputMessagesAttribute","setOutputMessagesAttribute","extractToolDefinitions","stringify","extractRequestAttributes","GEN_AI_PROVIDER_NAME","GEN_AI_OPERATION_NAME","SENTRY_ORIGIN","GEN_AI_AGENT_NAME","GEN_AI_TOOL_DEFINITIONS","addRequestAttributes","GEN_AI_EMBEDDINGS_INPUT","GEN_AI_SYSTEM_INSTRUCTIONS","GEN_AI_INPUT_MESSAGES","getSpanName","startSpanManual","startSpan","addResponseAttributes","isObjectLike","startInactiveSpan","GEN_AI_DECIDE","SENTRY_ORIGIN","GEN_AI_OPERATION_NAME","GEN_AI_PROVIDER_NAME","GEN_AI_REQUEST_MODEL","GEN_AI_INPUT_MESSAGES","addResponseAttributes","GEN_AI_RESPONSE_MODEL","GEN_AI_USAGE_INPUT_TOKENS","GEN_AI_USAGE_OUTPUT_TOKENS","GEN_AI_USAGE_TOTAL_TOKENS","GEN_AI_OUTPUT_MESSAGES","SPAN_STATUS_ERROR","withActiveSpan","getActiveSpan","spanToJSON","SENTRY_ORIGIN","_INTERNAL_shouldSkipAiProviderWrapping","GEN_AI_CHAT","GEN_AI_EMBEDDINGS","GEN_AI_DECIDE","GEN_AI_EXTRACT","GEN_AI_PROVIDER_NAME","GEN_AI_OPERATION_NAME","SENTRY_ORIGIN","GEN_AI_REQUEST_MODEL","GEN_AI_REQUEST_TEMPERATURE","GEN_AI_REQUEST_MAX_TOKENS","GEN_AI_REQUEST_TOP_P","GEN_AI_REQUEST_TOP_K","GEN_AI_REQUEST_FREQUENCY_PENALTY","GEN_AI_REQUEST_PRESENCE_PENALTY","GEN_AI_INPUT_MESSAGES","stringify","GEN_AI_EMBEDDINGS_INPUT","GEN_AI_SYSTEM_INSTRUCTIONS","isObjectLike","addDecideResponseAttributes","GEN_AI_RESPONSE_ID","GEN_AI_RESPONSE_MODEL","GEN_AI_RESPONSE_TEXT","GEN_AI_RESPONSE_TOOL_CALLS","setOutputMessagesAttribute","GEN_AI_RESPONSE_FINISH_REASONS","GEN_AI_OUTPUT_MESSAGES","setOutputMessagesAttribute","getClient","hasSpanStreamingEnabled","SENTRY_OP","startSpanManual","startSpan","stringify","GEN_AI_REQUEST_TEMPERATURE","GEN_AI_REQUEST_MAX_TOKENS","GEN_AI_REQUEST_TOP_P","GEN_AI_REQUEST_FREQUENCY_PENALTY","GEN_AI_REQUEST_PRESENCE_PENALTY","GEN_AI_PROVIDER_NAME","GEN_AI_OPERATION_NAME","GEN_AI_REQUEST_MODEL","SENTRY_ORIGIN","GEN_AI_INPUT_MESSAGES","GEN_AI_SYSTEM_INSTRUCTIONS","GEN_AI_RESPONSE_TOOL_CALLS","isObjectLike","GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS","GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS","GEN_AI_RESPONSE_FINISH_REASONS","GEN_AI_RESPONSE_TEXT","GEN_AI_RESPONSE_MODEL","GEN_AI_RESPONSE_ID","GEN_AI_AGENT_NAME","GEN_AI_CONVERSATION_ID","isObjectLike","SENTRY_ORIGIN","addResponseAttributes","SENTRY_ORIGIN","SENTRY_OP","GEN_AI_EMBEDDINGS","GEN_AI_OPERATION_NAME","GEN_AI_REQUEST_MODEL","GEN_AI_PROVIDER_NAME","getClient","GEN_AI_EMBEDDINGS_INPUT","stringify","hasSpanStreamingEnabled","startSpan","SPAN_STATUS_ERROR","LRUMap","DEBUG_BUILD","debug","spanIsIgnored","getRootSpan","getActiveSpan","withActiveSpan","spanToJSON","GEN_AI_CONVERSATION_ID","GEN_AI_REQUEST_MODEL","GEN_AI_OPERATION_NAME","getClient","startInactiveSpan","hasSpanStreamingEnabled","SENTRY_OP","GEN_AI_CHAT","GEN_AI_TOOL_DEFINITIONS","SPAN_STATUS_ERROR","SENTRY_ORIGIN","GEN_AI_PIPELINE_NAME","GEN_AI_INVOKE_AGENT","GEN_AI_TOOL_NAME","GEN_AI_TOOL_CALL_ARGUMENTS","GEN_AI_EXECUTE_TOOL","GEN_AI_TOOL_CALL_RESULT","stringify","SENTRY_ORIGIN","SENTRY_OP","GEN_AI_EXECUTE_TOOL","GEN_AI_OPERATION_NAME","GEN_AI_TOOL_NAME","GEN_AI_AGENT_NAME","GEN_AI_TOOL_DESCRIPTION","GEN_AI_TOOL_CALL_ARGUMENTS","startSpan","GEN_AI_TOOL_CALL_RESULT","SPAN_STATUS_ERROR","GEN_AI_USAGE_INPUT_TOKENS","GEN_AI_USAGE_OUTPUT_TOKENS","GEN_AI_USAGE_TOTAL_TOKENS","GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS","GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS","GEN_AI_RESPONSE_MODEL","GEN_AI_RESPONSE_FINISH_REASONS","resultObj","stringify","setOutputMessagesAttribute","GEN_AI_RESPONSE_TEXT","GEN_AI_RESPONSE_TOOL_CALLS","SENTRY_ORIGIN","SENTRY_OP","GEN_AI_INVOKE_AGENT","GEN_AI_OPERATION_NAME","GEN_AI_PIPELINE_NAME","GEN_AI_AGENT_NAME","GEN_AI_REQUEST_MODEL","GEN_AI_TOOL_DEFINITIONS","GEN_AI_SYSTEM_INSTRUCTIONS","GEN_AI_INPUT_MESSAGES","stringify","startSpanManual","GEN_AI_RESPONSE_STREAMING","SPAN_STATUS_ERROR","startSpan","SPAN_STATUS_ERROR","GEN_AI_INVOKE_AGENT","GEN_AI_CHAT","GEN_AI_EXECUTE_TOOL","GEN_AI_EMBEDDINGS","GEN_AI_DECIDE","stringify","GEN_AI_USAGE_INPUT_TOKENS","GEN_AI_USAGE_OUTPUT_TOKENS","GEN_AI_USAGE_TOTAL_TOKENS","GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS","GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS","GEN_AI_USAGE_REASONING_OUTPUT_TOKENS","GEN_AI_OPERATION_NAME","ERROR_TYPE","GEN_AI_AGENT_NAME","GEN_AI_PIPELINE_NAME","GEN_AI_TOOL_DEFINITIONS","GEN_AI_SYSTEM_INSTRUCTIONS","GEN_AI_INPUT_MESSAGES","GEN_AI_OUTPUT_MESSAGES","GEN_AI_RESPONSE_TEXT","GEN_AI_REQUEST_MODEL","GEN_AI_PROVIDER_NAME","GEN_AI_RESPONSE_MODEL","GEN_AI_RESPONSE_ID","GEN_AI_RESPONSE_STREAMING","GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK","GEN_AI_RESPONSE_FINISH_REASONS","GEN_AI_REQUEST_TEMPERATURE","GEN_AI_REQUEST_MAX_TOKENS","GEN_AI_REQUEST_TOP_P","GEN_AI_REQUEST_TOP_K","GEN_AI_REQUEST_PRESENCE_PENALTY","GEN_AI_REQUEST_FREQUENCY_PENALTY","GEN_AI_REQUEST_SEED","GEN_AI_REQUEST_STOP_SEQUENCES","GEN_AI_TOOL_NAME","GEN_AI_TOOL_DESCRIPTION","GEN_AI_TOOL_CALL_ARGUMENTS","GEN_AI_TOOL_CALL_RESULT","LRUMap","LRUMap","getClient","DEBUG_BUILD","debug","sentryFlush","getActiveSpan","startInactiveSpan","GEN_AI_CONVERSATION_ID","SENTRY_OP","SENTRY_ORIGIN","SPAN_STATUS_ERROR","timestampInSeconds","GEN_AI_RESPONSE_MODEL","GLOBAL_OBJ","GLOBAL_OBJ","consoleSandbox","debug","getCurrentScope","isObjectLike","stringify","withActiveSpan","captureException","startInactiveSpan","SENTRY_ORIGIN","GEN_AI_OPERATION_NAME","GEN_AI_TOOL_NAME","GEN_AI_CONVERSATION_ID","GEN_AI_TOOL_CALL_ARGUMENTS","stringify","GEN_AI_TOOL_CALL_RESULT","SPAN_STATUS_ERROR","isObjectLike","piAiModuleNames","consoleSandbox","getDefaultIsolationScope","startNewTrace","withActiveSpan","LRUMap","withScope","startSpan","SENTRY_ORIGIN","GEN_AI_OPERATION_NAME","GEN_AI_AGENT_NAME","GEN_AI_CONVERSATION_ID","sentryTraceFromTraceparent","getActiveSpan","continueTrace","getIsolationScope","DB_QUERY_TEXT","DB_QUERY_SUMMARY","DB_OPERATION_NAME","DB_NAMESPACE","DB_SYSTEM_NAME","getClient","hasSpanStreamingEnabled","DEBUG_BUILD","debug","isObjectLike","DB_QUERY_TEXT","SENTRY_OP","DB","SENTRY_ORIGIN","DB_SYSTEM_NAME","startSpanManual","addNonEnumerableProperty","DB_OPERATION_NAME","SPAN_STATUS_ERROR","getActiveSpan","DB_NAMESPACE","SERVER_ADDRESS","SERVER_PORT","DB_RESPONSE_STATUS_CODE","ERROR_TYPE","HTTP_SERVER","getOriginalFunction","DEBUG_BUILD","debug","getActiveSpan","startSpan","SENTRY_OP","SENTRY_ORIGIN","isObjectLike","getOriginalFunction","getActiveSpan","getRootSpan","startInactiveSpan","SENTRY_OP","MIDDLEWARE","SENTRY_ORIGIN","SPAN_STATUS_ERROR","DEBUG_BUILD","debug","DEBUG_BUILD","debug","getOriginalFunction","DEBUG_BUILD","debug","isPlainObject","addNonEnumerableProperty","isError","getActiveSpan","winterCGRequestToRequestData","getDefaultIsolationScope","getIsolationScope","getClient","getRootSpan","spanToJSON","CLIENT_ADDRESS","CLIENT_PORT","NETWORK_PEER_PORT","NETWORK_TRANSPORT","NETWORK_TYPE","NETWORK_PEER_ADDRESS","getClientIPAddress","winterCGHeadersToDict","captureException","updateSpanName","INTERNAL_setSegmentNameSourceIfSegment","HTTP_ROUTE","getIsolationScope","getDefaultIsolationScope","addNonEnumerableProperty"],"sources":["../../../src/utils/setHttpServerSpanRouteAttribute.ts","../../../src/async-context.ts","../../../src/opentelemetry.ts","../../../src/ai/core/utils.ts","../../../src/ai/core/span-hooks.ts","../../../src/ai/openai/constants.ts","../../../src/ai/core/streaming-tool-calls.ts","../../../src/ai/core/time-to-first-chunk.ts","../../../src/ai/core/gen-ai-attributes.ts","../../../src/ai/openai/mapping.ts","../../../src/ai/openai/utils.ts","../../../src/ai/openai/streaming.ts","../../../src/ai/openai/index.ts","../../../src/ai/anthropic-ai/constants.ts","../../../src/ai/anthropic-ai/utils.ts","../../../src/ai/anthropic-ai/streaming.ts","../../../src/utils/withCleanScopes.ts","../../../src/ai/anthropic-ai/tool-runner.ts","../../../src/ai/anthropic-ai/index.ts","../../../src/ai/google-genai/constants.ts","../../../src/ai/google-genai/decisions.ts","../../../src/ai/google-genai/utils.ts","../../../src/ai/google-genai/streaming.ts","../../../src/ai/google-genai/index.ts","../../../src/ai/mistral/constants.ts","../../../src/ai/mistral/utils.ts","../../../src/ai/mistral/streaming.ts","../../../src/ai/mistral/index.ts","../../../src/ai/typesafe/constants.ts","../../../src/ai/typesafe/index.ts","../../../src/ai/pi-ai/constants.ts","../../../src/ai/pi-ai/providers.ts","../../../src/ai/workers-ai/constants.ts","../../../src/ai/workers-ai/utils.ts","../../../src/ai/workers-ai/streaming.ts","../../../src/ai/workers-ai/index.ts","../../../src/ai/langchain/constants.ts","../../../src/ai/langchain/utils.ts","../../../src/ai/langchain/typesafe-classifier.ts","../../../src/ai/langchain/embeddings.ts","../../../src/ai/langchain/index.ts","../../../src/ai/langgraph/constants.ts","../../../src/ai/langgraph/utils.ts","../../../src/ai/langgraph/agent-span.ts","../../../src/ai/langgraph/stream.ts","../../../src/ai/langgraph/index.ts","../../../src/ai/mastra/constants.ts","../../../src/ai/mastra/utils.ts","../../../src/ai/mastra/classifier-evaluation.ts","../../../src/ai/mastra/span-registry.ts","../../../src/ai/mastra/index.ts","../../../src/utils/runtime.ts","../../../src/orchestrion/detect.ts","../../../src/ai/pi-ai/recording.ts","../../../src/ai/flue/constants.ts","../../../src/ai/pi-ai/messages.ts","../../../src/ai/flue/utils.ts","../../../src/ai/flue/index.ts","../../../src/utils/sql.ts","../../../src/utils/installedModules.ts","../../../src/integrations/postgresjs-wrapper.ts","../../../src/integrations/hono/constants.ts","../../../src/integrations/hono/sentryOriginalTraps.ts","../../../src/integrations/hono/patchAppRequest.ts","../../../src/integrations/hono/defaultShouldHandleError.ts","../../../src/integrations/hono/wrapMiddlewareSpan.ts","../../../src/integrations/hono/patchAppUse.ts","../../../src/integrations/hono/isMiddleware.ts","../../../src/integrations/hono/patchRoute.ts","../../../src/integrations/hono/applyPatches.ts","../../../src/integrations/hono/connInfo.ts","../../../src/integrations/hono/hono-context.ts","../../../src/integrations/hono/matchResult.ts","../../../src/integrations/hono/resolveRouteName.ts","../../../src/integrations/hono/unwrapThrownValue.ts","../../../src/integrations/hono/middlewareHandlers.ts","../../../src/integrations/hono/createHonoMiddleware.ts"],"sourcesContent":["import {\n SENTRY_SEGMENT_NAME_SOURCE,\n HTTP_METHOD,\n HTTP_REQUEST_METHOD,\n HTTP_ROUTE,\n SENTRY_OP,\n} from '@sentry/conventions/attributes';\nimport { getActiveSpan, getRootSpan, spanToJSON } from '@sentry/core';\n\n/**\n * Set the `http.route` attribute on the root HTTP server span for the current trace.\n *\n * No-op when there is no active span, no root span, or the root span is not an\n * `http.server` span — so framework instrumentations can call this unconditionally\n * without risking attribute pollution on non-HTTP root spans.\n */\nexport function setHttpServerSpanRouteAttribute(route: string): void {\n const activeSpan = getActiveSpan();\n if (!activeSpan) {\n return;\n }\n const rootSpan = getRootSpan(activeSpan);\n if (!rootSpan) {\n return;\n }\n\n const attributes = spanToJSON(rootSpan).attributes;\n if (attributes[SENTRY_OP] !== 'http.server') {\n return;\n }\n\n // eslint-disable-next-line typescript/no-deprecated\n const method = attributes[HTTP_REQUEST_METHOD] || attributes[HTTP_METHOD] || 'GET';\n rootSpan.setAttribute(HTTP_ROUTE, route);\n rootSpan.updateName(`${method} ${route}`);\n rootSpan.setAttribute(SENTRY_SEGMENT_NAME_SOURCE, 'route');\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { Scope } from '@sentry/core';\nimport {\n getAsyncContextStrategy,\n _INTERNAL_safeMathRandom,\n generateTraceId,\n getDefaultCurrentScope,\n getDefaultIsolationScope,\n getMainCarrier,\n isContinuingTrace,\n setAsyncContextStrategy,\n} from '@sentry/core';\n\ntype ScopeStore = { scope: Scope; isolationScope: Scope };\n\n/**\n * Sets the async context strategy to use AsyncLocalStorage.\n *\n * Returns the underlying `AsyncLocalStorage` whose store is the `{ scope, isolationScope }` object, so\n * callers (e.g. `@sentry/node-native`) can read scope out of it from a native thread.\n */\nexport function setAsyncLocalStorageAsyncContextStrategy(): AsyncLocalStorage<ScopeStore> {\n // Re-use the AsyncLocalStorage of an already-installed strategy, if any. Otherwise a repeated\n // setup (e.g. a second `Sentry.init()`) would swap in a new store while integrations that captured\n // the previous one (via `getTracingChannelBinding().asyncLocalStorage`) keep reading the old one,\n // breaking scope propagation across async boundaries.\n const existingAsyncStorage = getAsyncContextStrategy(getMainCarrier()).getTracingChannelBinding?.()\n ?.asyncLocalStorage as AsyncLocalStorage<ScopeStore> | undefined;\n\n const asyncStorage = existingAsyncStorage ?? new AsyncLocalStorage<ScopeStore>();\n\n function getScopes(): { scope: Scope; isolationScope: Scope } {\n const scopes = asyncStorage.getStore();\n\n if (scopes) {\n return scopes;\n }\n\n // fallback behavior:\n // if, for whatever reason, we can't find scopes on the context here, we have to fix this somehow\n return {\n scope: getDefaultCurrentScope(),\n isolationScope: getDefaultIsolationScope(),\n };\n }\n\n function withScope<T>(callback: (scope: Scope) => T): T {\n const scope = getScopes().scope.clone();\n const isolationScope = getScopes().isolationScope;\n return asyncStorage.run({ scope, isolationScope }, () => {\n return callback(scope);\n });\n }\n\n // The isolation scope is shared, not forked, matching `withScope` above and the OpenTelemetry\n // strategy. Forking it would silently discard `setUser`/`setTag`/`setContext` calls made inside\n // the callback, as those write to the isolation scope.\n function withSetScope<T>(scope: Scope, callback: (scope: Scope) => T): T {\n const isolationScope = getScopes().isolationScope;\n return asyncStorage.run({ scope, isolationScope }, () => {\n return callback(scope);\n });\n }\n\n // The current scope is forked alongside the isolation scope, matching the OpenTelemetry strategy\n // (`buildContextWithSentryScopes` clones it on every fork). Sharing it by reference would let\n // current-scope mutations inside the callback leak back out to the caller.\n function withIsolationScope<T>(callback: (isolationScope: Scope) => T): T {\n const scope = getScopes().scope.clone();\n const isolationScope = getScopes().isolationScope.clone();\n\n // When forking an isolation scope, unless we are continuing an incoming\n // trace, we give the freshly forked scope its own trace. This way, new\n // root spans in an isolation scope will get separate traces. The previous\n // trace's `sampled` and `propagationSpanId` are dropped on purpose.\n // Carrying them over would apply the old trace's sampling decision to the\n // new one and propagate a span id from a different trace.\n if (!isContinuingTrace(scope.getPropagationContext())) {\n scope.setPropagationContext({\n traceId: generateTraceId(),\n sampleRand: _INTERNAL_safeMathRandom(),\n });\n }\n\n return asyncStorage.run({ scope, isolationScope }, () => {\n return callback(isolationScope);\n });\n }\n\n function withSetIsolationScope<T>(isolationScope: Scope, callback: (isolationScope: Scope) => T): T {\n const scope = getScopes().scope.clone();\n return asyncStorage.run({ scope, isolationScope }, () => {\n return callback(isolationScope);\n });\n }\n\n setAsyncContextStrategy({\n withScope,\n withSetScope,\n withIsolationScope,\n withSetIsolationScope,\n getCurrentScope: () => getScopes().scope,\n getIsolationScope: () => getScopes().isolationScope,\n getTracingChannelBinding: () => {\n return {\n asyncLocalStorage: asyncStorage,\n };\n },\n });\n\n return asyncStorage;\n}\n","import { isSpanContextValid, trace } from '@opentelemetry/api';\nimport type { IntegrationFn } from '@sentry/core';\nimport { defineIntegration, dsnFromString, SENTRY_API_VERSION, registerExternalPropagationContext } from '@sentry/core';\n\nconst INTEGRATION_NAME = 'OpenTelemetry' as const;\n\nconst _openTelemetryIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n\n setup(): void {\n registerExternalPropagationContext(() => {\n const activeSpan = trace.getActiveSpan();\n if (!activeSpan) {\n return undefined;\n }\n\n // OpenTelemetry hands out a span wrapping `INVALID_SPAN_CONTEXT` when tracing is suppressed,\n // or when a span is started before a tracer provider is registered. Its ids are all zeroes,\n // so fall back to the Sentry scope rather than stamping that onto everything we send.\n const spanContext = activeSpan.spanContext();\n if (!isSpanContextValid(spanContext)) {\n return undefined;\n }\n\n const { traceId, spanId } = spanContext;\n return { traceId, spanId };\n });\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Connects Sentry to an existing OpenTelemetry setup.\n *\n * Everything Sentry sends that carries trace information (errors, logs, metrics and check-ins) is\n * attached to the OpenTelemetry span that is active when it happens, so it shows up on the same\n * trace as the spans your OpenTelemetry SDK exports. Outgoing request propagation is left to your\n * OpenTelemetry propagator.\n *\n * An active Sentry span still takes precedence, so this only changes what happens when Sentry has no\n * span of its own, which is the usual setup when OpenTelemetry owns tracing.\n *\n * This does not export any spans. Configure your own span exporter and point it at Sentry using\n * {@link getOtlpTracesEndpoint}.\n */\nexport const openTelemetryIntegration = defineIntegration(_openTelemetryIntegration);\n\n/**\n * Builds the URL and auth headers for Sentry's OTLP traces endpoint, to configure an\n * `OTLPTraceExporter` with.\n *\n * Returns `undefined` if the DSN cannot be parsed.\n *\n * @example\n *\n * ```javascript\n * import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\n * import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';\n * import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';\n *\n * const provider = new NodeTracerProvider({\n * spanProcessors: [\n * new BatchSpanProcessor(new OTLPTraceExporter(Sentry.getOtlpTracesEndpoint('__DSN__'))),\n * ],\n * });\n *\n * provider.register();\n *\n * Sentry.init({\n * dsn: '__DSN__',\n * integrations: [Sentry.openTelemetryIntegration()],\n * });\n * ```\n */\nexport function getOtlpTracesEndpoint(dsn: string): { url: string; headers: Record<string, string> } | undefined {\n const parsedDsn = dsnFromString(dsn);\n if (!parsedDsn) {\n return undefined;\n }\n\n const { protocol, host, port, path, projectId, publicKey } = parsedDsn;\n const basePath = path ? `/${path}` : '';\n const portSuffix = port ? `:${port}` : '';\n\n return {\n url: `${protocol}://${host}${portSuffix}${basePath}/api/${projectId}/integration/otlp/v1/traces/`,\n headers: {\n 'X-Sentry-Auth': `Sentry sentry_version=${SENTRY_API_VERSION}, sentry_key=${publicKey}`,\n },\n };\n}\n","/* eslint-disable typescript-eslint/no-deprecated */\n/**\n * Shared utils for AI integrations (OpenAI, Anthropic, Verce.AI, etc.)\n */\nimport { debug, getClient, isObjectLike, isThenable, SPAN_STATUS_ERROR, stringify } from '@sentry/core';\nimport type { Span, SpanStatus } from '@sentry/core';\nimport {\n GEN_AI_OUTPUT_MESSAGES,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_STREAMING,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n} from '@sentry/conventions/attributes';\nimport { FUNCTION } from '@sentry/conventions/op';\nimport { DEBUG_BUILD } from '../../debug-build';\n\nexport interface GenAiOptions {\n /**\n * Record input messages/prompts on gen_ai spans. Defaults to the global\n * `dataCollection.genAI.inputs` setting; an explicit value here takes precedence.\n */\n recordInputs?: boolean;\n /**\n * Record output text/responses on gen_ai spans. Defaults to the global\n * `dataCollection.genAI.outputs` setting; an explicit value here takes precedence.\n */\n recordOutputs?: boolean;\n}\n\n/**\n * Whether to record the content of a gen_ai call: a boolean for every call, or a function that decides for\n * each call. The function runs once when the call starts, in the caller's async context, so it can read\n * request-scoped state. Returning `undefined` falls back to `dataCollection.genAI`. If it throws, the\n * content is not recorded.\n */\nexport type GenAiRecordingOption<TCall> = boolean | ((call: TCall) => boolean | undefined);\n\n/** {@link GenAiOptions} of an integration that can decide per call. `TCall` is what the function gets. */\nexport interface GenAiCallOptions<TCall> {\n /**\n * Record input messages/prompts on gen_ai spans. Defaults to the global\n * `dataCollection.genAI.inputs` setting; an explicit value here takes precedence.\n */\n recordInputs?: GenAiRecordingOption<TCall>;\n /**\n * Record output text/responses on gen_ai spans. Defaults to the global\n * `dataCollection.genAI.outputs` setting; an explicit value here takes precedence.\n */\n recordOutputs?: GenAiRecordingOption<TCall>;\n}\n\n/**\n * A method registry entry describes a single instrumented method:\n * which gen_ai operation it maps to and whether it is intrinsically streaming.\n */\nexport interface InstrumentedMethodEntry {\n /** Operation name (e.g. 'chat', 'embeddings', 'generate_content'). Omit for factory methods that only need result proxying. */\n operation?: string;\n /** True if the method itself is always streaming (not param-based) */\n streaming?: boolean;\n /** When set, the method's return value is re-proxied with this as the base path */\n proxyResultPath?: string;\n}\n\n/**\n * Maps method paths to their registry entries.\n * Used by proxy-based AI client instrumentations to determine which methods\n * to instrument, what operation name to use, and whether they stream.\n */\nexport type InstrumentedMethodRegistry = Record<string, InstrumentedMethodEntry>;\n\n// Operation names that are not inference calls: `unknown` is the fallback for methods with no\n// registered operation. It should not surface as a `gen_ai.*` op (an unknown string must not\n// masquerade as a convention), so it maps to the generic `function` op. The operation name itself\n// is preserved on `gen_ai.operation.name`.\nconst NON_INFERENCE_OPERATIONS = new Set(['unknown']);\n\n/**\n * Derive the span op from a gen_ai operation name. Inference operations become `gen_ai.<operation>`;\n * non-inference operations (`unknown`) become the generic `function` op.\n */\nexport function getGenAiSpanOp(operationName: string): string {\n return NON_INFERENCE_OPERATIONS.has(operationName) ? FUNCTION : `gen_ai.${operationName}`;\n}\n\n/**\n * Resolves AI recording options by falling back to the client's `dataCollection.genAI` settings.\n * Precedence: explicit option > dataCollection.genAI > true (genAI data collected by default)\n */\nexport function resolveAIRecordingOptions<T extends GenAiOptions>(options?: T): T & Required<GenAiOptions> {\n const genAI = getClient()?.getDataCollectionOptions().genAI;\n return {\n ...options,\n recordInputs: options?.recordInputs ?? genAI?.inputs ?? true,\n recordOutputs: options?.recordOutputs ?? genAI?.outputs ?? true,\n } as T & Required<GenAiOptions>;\n}\n\n/**\n * Resolves the recording options of one call, like {@link resolveAIRecordingOptions}, and calls the\n * options that are functions with `call`. Call it once when the call starts, so the functions run in the\n * caller's async context.\n */\nexport function resolveGenAiCallRecording<TCall>(\n options: GenAiCallOptions<TCall> | undefined,\n call: TCall,\n): Required<GenAiOptions> {\n const genAI = getClient()?.getDataCollectionOptions().genAI;\n return {\n recordInputs: resolveRecordingOption(options?.recordInputs, call) ?? genAI?.inputs ?? true,\n recordOutputs: resolveRecordingOption(options?.recordOutputs, call) ?? genAI?.outputs ?? true,\n };\n}\n\n/** Calls `option` with `call` when it is a function; `undefined` means the option does not decide. */\nexport function resolveRecordingOption<TCall>(\n option: GenAiRecordingOption<TCall> | undefined,\n call: TCall,\n): boolean | undefined {\n if (typeof option !== 'function') {\n return option;\n }\n try {\n const result = option(call);\n return result === undefined ? undefined : result === true;\n } catch (error) {\n DEBUG_BUILD && debug.warn('[gen_ai] `recordInputs`/`recordOutputs` threw, not recording content', error);\n return false;\n }\n}\n\n/**\n * Build method path from current traversal\n */\nexport function buildMethodPath(currentPath: string, prop: string): string {\n return currentPath ? `${currentPath}.${prop}` : prop;\n}\n\n/**\n * A minimal structural check for a web `ReadableStream`.\n *\n * The chunk type is the caller's assumption about the provider's stream (e.g. `Uint8Array` for SSE\n * byte streams); the check itself only looks for the `ReadableStream` methods we rely on.\n */\nexport function isReadableStream<T = unknown>(value: unknown): value is ReadableStream<T> {\n return (\n isObjectLike(value) &&\n typeof (value as { pipeThrough?: unknown }).pipeThrough === 'function' &&\n typeof (value as { getReader?: unknown }).getReader === 'function'\n );\n}\n\n/**\n * Build token usage attributes. Input tokens include cache reads and writes, which are subsets.\n */\nexport function getTokenUsageAttributes(\n promptTokens?: number,\n completionTokens?: number,\n cacheCreationInputTokens?: number,\n cacheReadInputTokens?: number,\n totalTokens?: number,\n): Record<string, number> {\n const attributes: Record<string, number> = {};\n\n if (typeof promptTokens === 'number') {\n attributes[GEN_AI_USAGE_INPUT_TOKENS] = promptTokens;\n }\n if (typeof cacheCreationInputTokens === 'number') {\n attributes[GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS] = cacheCreationInputTokens;\n }\n if (typeof cacheReadInputTokens === 'number') {\n attributes[GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS] = cacheReadInputTokens;\n }\n if (typeof completionTokens === 'number') {\n attributes[GEN_AI_USAGE_OUTPUT_TOKENS] = completionTokens;\n }\n if (typeof totalTokens === 'number') {\n attributes[GEN_AI_USAGE_TOTAL_TOKENS] = totalTokens;\n } else if (typeof promptTokens === 'number' || typeof completionTokens === 'number') {\n attributes[GEN_AI_USAGE_TOTAL_TOKENS] =\n (typeof promptTokens === 'number' ? promptTokens : 0) +\n (typeof completionTokens === 'number' ? completionTokens : 0);\n }\n return attributes;\n}\n\n/** Serialize the `state` and `questions` of an evaluation request (TypeSafe, Workers AI, Mastra classifiers). */\nexport function getEvaluationInputMessages(request: Record<string, unknown>): string | undefined {\n return stringify([{ type: 'evaluation', state: request.state, questions: request.questions }]);\n}\n\n/** Serialize the `answers` of an evaluation result (TypeSafe, Workers AI, Mastra classifiers). */\nexport function getEvaluationOutputMessages(answers: unknown): string | undefined {\n return stringify([{ type: 'evaluation', answers }]);\n}\n\n/** One assistant turn for {@link setOutputMessagesAttribute}. */\nexport interface GenAiOutputMessage {\n /** The message's text content, already flattened out of any content-part array. */\n responseText?: string;\n /** Tool calls in either the OpenAI-compatible (`function.name`) or flat (`name`) shape. */\n toolCalls?: unknown[];\n /** Recorded as `finish_reason` on the message, per the `gen_ai.output.messages` schema. */\n finishReason?: string;\n}\n\n/**\n * Build the `gen_ai.output.messages` value (assistant messages with text and/or tool-call parts).\n *\n * We set this in addition to the deprecated `gen_ai.response.text` / `gen_ai.response.tool_calls`\n * attributes because Sentry's product reads the model output from `gen_ai.output.messages` first.\n * Relay migrates `gen_ai.response.text` into `gen_ai.output.messages`, but the tool-calls half of\n * that migration is lossy — so tool-call turns would otherwise render an empty Output.\n *\n * Pass an array for providers that can return more than one choice per response; a single object is\n * the common case of one assistant turn.\n */\nexport function setOutputMessagesAttribute(span: Span, messages: GenAiOutputMessage | GenAiOutputMessage[]): void {\n const serialized = (Array.isArray(messages) ? messages : [messages])\n .map(buildOutputMessage)\n .filter((message): message is Record<string, unknown> => !!message);\n\n if (serialized.length > 0) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, JSON.stringify(serialized));\n }\n}\n\nfunction buildOutputMessage({\n responseText,\n toolCalls,\n finishReason,\n}: GenAiOutputMessage): Record<string, unknown> | undefined {\n const parts: Array<Record<string, unknown>> = [];\n\n if (typeof responseText === 'string' && responseText.length > 0) {\n parts.push({ type: 'text', content: responseText });\n }\n\n if (Array.isArray(toolCalls)) {\n for (const toolCall of toolCalls) {\n if (!toolCall || typeof toolCall !== 'object') {\n continue;\n }\n const call = toolCall as {\n id?: unknown;\n function?: { name?: unknown; arguments?: unknown };\n name?: unknown;\n arguments?: unknown;\n };\n // Normalize both the OpenAI-compatible shape (name/arguments nested under `function`)\n // and the flat shape some providers use.\n const name = call.function?.name ?? call.name;\n const args = call.function?.arguments ?? call.arguments;\n parts.push({\n type: 'tool_call',\n id: call.id,\n name,\n arguments: stringify(args ?? {}, String),\n });\n }\n }\n\n if (parts.length === 0) {\n return undefined;\n }\n\n return finishReason ? { role: 'assistant', parts, finish_reason: finishReason } : { role: 'assistant', parts };\n}\n\nexport interface StreamResponseState {\n responseId?: string;\n responseModel?: string;\n finishReasons: string[];\n responseTexts: string[];\n toolCalls: unknown[];\n promptTokens?: number;\n completionTokens?: number;\n totalTokens?: number;\n cacheCreationInputTokens?: number;\n cacheReadInputTokens?: number;\n reasoningOutputTokens?: number;\n}\n\n/**\n * Reads `signal` from the request options OpenAI and Anthropic take as their second argument.\n */\nexport function getRequestSignal(requestOptions: unknown): AbortSignal | undefined {\n return isObjectLike(requestOptions) ? (requestOptions.signal as AbortSignal | undefined) : undefined;\n}\n\n/**\n * Checks the signal rather than the error name, because SDK timeouts also throw an `AbortError`. A caller's\n * own `AbortSignal.timeout()` is a timeout too, not a cancellation.\n */\nexport function isCallerAbort(abortSignal: AbortSignal | undefined): boolean {\n return !!abortSignal?.aborted && (abortSignal.reason as { name?: unknown } | undefined)?.name !== 'TimeoutError';\n}\n\n/**\n * A caller's abort is `cancelled`, anything else `internal_error`.\n */\nexport function getErrorStatus(abortSignal: AbortSignal | undefined): SpanStatus {\n return { code: SPAN_STATUS_ERROR, message: isCallerAbort(abortSignal) ? 'cancelled' : 'internal_error' };\n}\n\n/**\n * Overrides the status of a span whose call the caller aborted.\n */\nexport function markCancelledIfAborted(span: Span, abortSignal: AbortSignal | undefined): void {\n if (isCallerAbort(abortSignal)) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n }\n}\n\n/**\n * Ends a streaming span by setting all accumulated response attributes and ending the span.\n * Shared across OpenAI, Anthropic, and Google GenAI streaming implementations.\n * `beforeSpanEnd` runs after the attributes are set, right before the span ends.\n */\nexport function endStreamSpan(\n span: Span,\n state: StreamResponseState,\n recordOutputs: boolean,\n beforeSpanEnd?: () => void,\n): void {\n if (!span.isRecording()) {\n return;\n }\n\n const attrs: Record<string, string | number | boolean> = {\n [GEN_AI_RESPONSE_STREAMING]: true,\n };\n\n if (state.responseId) attrs[GEN_AI_RESPONSE_ID] = state.responseId;\n if (state.responseModel) attrs[GEN_AI_RESPONSE_MODEL] = state.responseModel;\n\n Object.assign(\n attrs,\n getTokenUsageAttributes(\n state.promptTokens,\n state.completionTokens,\n state.cacheCreationInputTokens,\n state.cacheReadInputTokens,\n state.totalTokens,\n ),\n );\n if (typeof state.reasoningOutputTokens === 'number') {\n attrs[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS] = state.reasoningOutputTokens;\n }\n\n if (state.finishReasons.length) {\n attrs[GEN_AI_RESPONSE_FINISH_REASONS] = JSON.stringify(state.finishReasons);\n }\n if (recordOutputs && state.responseTexts.length) {\n attrs[GEN_AI_RESPONSE_TEXT] = state.responseTexts.join('');\n }\n if (recordOutputs && state.toolCalls.length) {\n attrs[GEN_AI_RESPONSE_TOOL_CALLS] = JSON.stringify(state.toolCalls);\n }\n\n span.setAttributes(attrs);\n beforeSpanEnd?.();\n span.end();\n}\n\n/**\n * Extract system instructions from messages array.\n * Finds the first system message and formats it according to OpenTelemetry semantic conventions.\n *\n * @param messages - Array of messages to extract system instructions from\n * @returns systemInstructions (JSON string) and filteredMessages (without system message)\n */\nexport function extractSystemInstructions(messages: unknown[] | unknown): {\n systemInstructions: string | undefined;\n filteredMessages: unknown[] | unknown;\n} {\n if (!Array.isArray(messages)) {\n return { systemInstructions: undefined, filteredMessages: messages };\n }\n\n const systemMessageIndex = messages.findIndex(\n msg => msg && typeof msg === 'object' && 'role' in msg && (msg as { role: string }).role === 'system',\n );\n\n if (systemMessageIndex === -1) {\n return { systemInstructions: undefined, filteredMessages: messages };\n }\n\n const systemMessage = messages[systemMessageIndex] as { role: string; content?: string | unknown };\n const systemContent =\n typeof systemMessage.content === 'string'\n ? systemMessage.content\n : systemMessage.content !== undefined\n ? JSON.stringify(systemMessage.content)\n : undefined;\n\n if (!systemContent) {\n return { systemInstructions: undefined, filteredMessages: messages };\n }\n\n const systemInstructions = JSON.stringify([{ type: 'text', content: systemContent }]);\n const filteredMessages = [...messages.slice(0, systemMessageIndex), ...messages.slice(systemMessageIndex + 1)];\n\n return { systemInstructions, filteredMessages };\n}\n\n/**\n * Creates a wrapped version of .withResponse() that replaces the data field\n * with the instrumented result while preserving metadata (response, request_id).\n */\nasync function createWithResponseWrapper<T>(\n originalWithResponse: Promise<unknown>,\n instrumentedPromise: Promise<T>,\n): Promise<unknown> {\n // Awaited together rather than in sequence so both promises get a handler attached synchronously.\n // Awaiting them one after the other leaves the second unobserved when the first rejects, which\n // surfaces as an unhandled rejection.\n const [instrumentedResult, originalWrapper] = await Promise.all([instrumentedPromise, originalWithResponse]);\n\n // Combine instrumented result with original metadata\n if (originalWrapper && typeof originalWrapper === 'object' && 'data' in originalWrapper) {\n return {\n ...originalWrapper,\n data: instrumentedResult,\n };\n }\n return instrumentedResult;\n}\n\n/**\n * Wraps a promise-like object to preserve additional methods (like .withResponse())\n * that AI SDK clients (OpenAI, Anthropic) attach to their APIPromise return values.\n *\n * Standard Promise methods (.then, .catch, .finally) are routed to the instrumented\n * promise to preserve Sentry's span instrumentation, while custom SDK methods are\n * forwarded to the original promise to maintain the SDK's API surface.\n */\nexport function wrapPromiseWithMethods<R>(\n originalPromiseLike: Promise<R>,\n instrumentedPromise: Promise<R>,\n): Promise<R> {\n // If the original result is not thenable, return the instrumented promise\n if (!isThenable(originalPromiseLike)) {\n return instrumentedPromise;\n }\n\n // Create a proxy that forwards Promise methods to instrumentedPromise\n // and preserves additional methods from the original result\n return new Proxy(originalPromiseLike, {\n get(target: object, prop: string | symbol): unknown {\n // For standard Promise methods (.then, .catch, .finally, Symbol.toStringTag),\n // use instrumentedPromise to preserve Sentry instrumentation.\n // For custom methods (like .withResponse()), use the original target.\n const useInstrumentedPromise = prop in Promise.prototype || prop === Symbol.toStringTag;\n const source = useInstrumentedPromise ? instrumentedPromise : target;\n\n const value = Reflect.get(source, prop) as unknown;\n\n // Special handling for .withResponse() to preserve instrumentation\n // .withResponse() returns { data: T, response: Response, request_id: string }\n if (prop === 'withResponse' && typeof value === 'function') {\n return function wrappedWithResponse(this: unknown): unknown {\n const originalWithResponse = (value as (...args: unknown[]) => unknown).call(target);\n return createWithResponseWrapper(originalWithResponse, instrumentedPromise);\n };\n }\n\n return typeof value === 'function' ? value.bind(source) : value;\n },\n }) as Promise<R>;\n}\n","import { debug } from '@sentry/core';\nimport type { Span } from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\n\n/** How a gen_ai call ended, as passed to {@link GenAiSpanHooks.onSpanEnd}. */\nexport interface GenAiSpanResult<TResponse> {\n /** The response as the library returned it. `undefined` for streams and failed calls. */\n response?: TResponse;\n /** Set when the call failed. */\n error?: unknown;\n}\n\n/**\n * Hooks that let an integration's users add their own attributes to its gen_ai spans. `TCall` is the same\n * call info that `recordInputs`/`recordOutputs` get, and both hooks get the same object.\n *\n * They only run for spans that are recorded. A hook that throws is logged and does not affect the call.\n */\nexport interface GenAiSpanHooks<TCall, TResponse = unknown> {\n /**\n * Runs after the span started and the SDK set its request attributes, in the caller's async context, so\n * it can read request-scoped state.\n */\n onSpanStart?: (span: Span, call: TCall) => void;\n /**\n * Runs after the SDK set its response attributes, right before the span ends. That can be in another\n * async context than the call, for example when a stream is consumed later.\n */\n onSpanEnd?: (span: Span, call: TCall, result: GenAiSpanResult<TResponse>) => void;\n}\n\n/** Runs {@link GenAiSpanHooks.onSpanStart}. */\nexport function runGenAiSpanStart<TCall>(\n hooks: Pick<GenAiSpanHooks<TCall>, 'onSpanStart'>,\n span: Span,\n call: TCall,\n): void {\n const onSpanStart = hooks.onSpanStart;\n if (onSpanStart && span.isRecording()) {\n runGenAiSpanHook('onSpanStart', () => onSpanStart(span, call));\n }\n}\n\n/** Runs {@link GenAiSpanHooks.onSpanEnd}. Call it right before the span ends. */\nexport function runGenAiSpanEnd<TCall, TResponse>(\n hooks: GenAiSpanHooks<TCall, TResponse>,\n span: Span,\n call: TCall,\n result: GenAiSpanResult<TResponse>,\n): void {\n const onSpanEnd = hooks.onSpanEnd;\n if (onSpanEnd && span.isRecording()) {\n runGenAiSpanHook('onSpanEnd', () => onSpanEnd(span, call, result));\n }\n}\n\nfunction runGenAiSpanHook(name: string, hook: () => void): void {\n try {\n hook();\n } catch (error) {\n DEBUG_BUILD && debug.warn(`[gen_ai] \\`${name}\\` threw`, error);\n }\n}\n","import type { InstrumentedMethodRegistry } from '../core/utils';\n\nexport const OPENAI_INTEGRATION_NAME = 'OpenAI' as const;\n\n// https://platform.openai.com/docs/quickstart?api-mode=responses\n// https://platform.openai.com/docs/quickstart?api-mode=chat\n// https://platform.openai.com/docs/api-reference/conversations\nexport const OPENAI_METHOD_REGISTRY = {\n 'responses.create': { operation: 'chat' },\n 'chat.completions.create': { operation: 'chat' },\n 'embeddings.create': { operation: 'embeddings' },\n // Conversations API - for conversation state management\n // https://platform.openai.com/docs/guides/conversation-state\n 'conversations.create': { operation: 'chat' },\n // https://developers.openai.com/api/docs/guides/decisions\n 'decisions.create': { operation: 'decide' },\n} as const satisfies InstrumentedMethodRegistry;\nexport const RESPONSES_TOOL_CALL_EVENT_TYPES = [\n 'response.output_item.added',\n 'response.function_call_arguments.delta',\n 'response.function_call_arguments.done',\n 'response.output_item.done',\n] as const;\nexport const RESPONSE_EVENT_TYPES = [\n 'response.created',\n 'response.in_progress',\n 'response.failed',\n 'response.completed',\n 'response.incomplete',\n 'response.queued',\n 'response.output_text.delta',\n ...RESPONSES_TOOL_CALL_EVENT_TYPES,\n] as const;\n","interface ToolCallKeyState {\n calls: Map<string, { id?: string }>;\n keyByIndex: Map<number, string>;\n lastKey?: string;\n}\n\n/**\n * Find the key of the call a tool call delta belongs to. A numeric `index` groups deltas, except that a different\n * non-empty `id` arriving on an index that is already taken opens a new call (a known `id` continues its own call).\n * Some providers omit the index and send each parallel call whole: a known `id` continues that call, a new `id` (or\n * a name without an id) starts a new call, and anything else continues the latest one.\n */\nexport function getToolCallKey(\n toolCall: { index?: number | null; id?: string },\n name: string | undefined,\n accumulator: ToolCallKeyState,\n): string {\n const { calls } = accumulator;\n const findById = (id: string): string | undefined => {\n for (const [key, call] of calls) {\n if (call.id === id) return key;\n }\n return undefined;\n };\n\n if (typeof toolCall.index === 'number') {\n const key = accumulator.keyByIndex.get(toolCall.index) ?? `index-${toolCall.index}`;\n const known = toolCall.id ? findById(toolCall.id) : undefined;\n if (known !== undefined) {\n accumulator.keyByIndex.set(toolCall.index, known);\n return known;\n }\n const existingId = calls.get(key)?.id;\n if (existingId && toolCall.id && existingId !== toolCall.id) {\n const next = findById(toolCall.id) ?? `index-${toolCall.index}-${calls.size}`;\n accumulator.keyByIndex.set(toolCall.index, next);\n return next;\n }\n return key;\n }\n if (toolCall.id) {\n const known = findById(toolCall.id);\n if (known !== undefined) {\n return known;\n }\n }\n if (toolCall.id || name || accumulator.lastKey === undefined) {\n return `no-index-${calls.size}`;\n }\n return accumulator.lastKey;\n}\n","import { spanToJSON, timestampInSeconds } from '@sentry/core';\nimport type { Span } from '@sentry/core';\nimport { GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK } from '@sentry/conventions/attributes';\n\n/**\n * Sets `gen_ai.response.time_to_first_chunk` on a streamed span, in seconds from the span start.\n * Call it for each received chunk. Only the first call per span records a value.\n */\nexport function recordTimeToFirstChunk(span: Span): void {\n const { attributes, start_timestamp } = spanToJSON(span);\n if (attributes[GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK] === undefined) {\n span.setAttribute(GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK, timestampInSeconds() - start_timestamp);\n }\n}\n","/**\n * Gen-AI telemetry attributes that are not (yet) covered by `@sentry/conventions`.\n *\n * Attributes with an equivalent in `@sentry/conventions/attributes` are imported from there directly\n * at their call sites. The constants below either have no conventions equivalent, are Sentry-internal\n * meta attributes, are span-operation values (not attribute keys), or intentionally emit a different\n * key than the current conventions attribute.\n *\n * Based on OpenTelemetry Semantic Conventions for Generative AI\n * @see https://opentelemetry.io/docs/specs/semconv/gen-ai/\n */\n\n/**\n * Whether streaming was enabled for the request\n */\nexport const GEN_AI_REQUEST_STREAM_ATTRIBUTE = 'gen_ai.request.stream';\n\n/**\n * The encoding format for the model request\n */\nexport const GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE = 'gen_ai.request.encoding_format';\n\n/**\n * The dimensions for the model request\n */\nexport const GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE = 'gen_ai.request.dimensions';\n\n/**\n * The reason why the model stopped generating tokens\n */\nexport const GEN_AI_RESPONSE_STOP_REASON_ATTRIBUTE = 'gen_ai.response.stop_reason';\n\n/**\n * The tool call ID\n */\nexport const GEN_AI_TOOL_CALL_ID_ATTRIBUTE = 'gen_ai.tool.call.id';\n","/**\n * Maps OpenAI decisions requests and responses to the format Jev calls are recorded in, so Sentry renders\n * both the same way.\n */\nimport { isObjectLike } from '@sentry/core';\nimport { getEvaluationInputMessages, getEvaluationOutputMessages } from '../core/utils';\nimport type { GenAiMessage, GenAiMessagePart } from '../types';\n\n/**\n * Serialize a decisions request. Its evidence is `input` where Jev's is `state`; it is recorded as `state`\n * so both render the same.\n */\nexport function getDecisionInputMessages(params: Record<string, unknown>): string | undefined {\n const questions = Array.isArray(params.questions) ? params.questions.map(toJevQuestionFormat) : params.questions;\n return getEvaluationInputMessages({ state: toStateMessages(params.input), questions: keyByName(questions) });\n}\n\n/**\n * Lay out evidence messages as gen_ai messages, so they render like Google's. Other input items (tool calls and\n * their outputs) keep their layout, with output parts mapped like message parts.\n */\nfunction toStateMessages(input: unknown): unknown {\n if (!Array.isArray(input)) {\n return input;\n }\n\n return input.map(item => {\n if (!isObjectLike(item)) {\n return item;\n }\n if (typeof item.role === 'string') {\n return {\n // The gen_ai conventions have no `developer` role.\n role: (item.role === 'developer' ? 'system' : item.role) as GenAiMessage['role'],\n parts: Array.isArray(item.content)\n ? item.content.filter(isObjectLike).map(toMessagePart)\n : [{ type: 'text', content: item.content }],\n } satisfies GenAiMessage;\n }\n return Array.isArray(item.output) ? { ...item, output: item.output.filter(isObjectLike).map(toMessagePart) } : item;\n });\n}\n\n/**\n * An image in a data URL is reported by its media type only: the URL holds base64, which the conventions require to be\n * dropped.\n */\nfunction toMessagePart(part: Record<PropertyKey, unknown>): GenAiMessagePart {\n if (part.type === 'input_image' && typeof part.image_url === 'string') {\n const dataUrlMimeType = /^data:([^;,]+)/.exec(part.image_url)?.[1];\n return part.image_url.startsWith('data:')\n ? { type: 'blob', modality: 'image', mime_type: dataUrlMimeType }\n : { type: 'uri', modality: 'image', uri: part.image_url };\n }\n if (part.type === 'input_json') {\n return { type: 'object', content: part.data };\n }\n return { type: 'text', content: part.text ?? part.refusal };\n}\n\n/** Serialize the answers of a decisions response, laid out and keyed like Jev answers. */\nexport function getDecisionOutputMessages(answers: unknown[]): string | undefined {\n return getEvaluationOutputMessages(keyByName(answers.map(toJevAnswerFormat)));\n}\n\n/**\n * Lay out a decisions question like a Jev question, with its options in `criteria`: choices as\n * `{ [value]: description }` (an empty description when there is none), and score levels as their labels,\n * indexed by score value, with any level descriptions in `descriptions`, keyed by score value.\n */\nfunction toJevQuestionFormat(question: unknown): unknown {\n if (!isObjectLike(question)) {\n return question;\n }\n\n if (question.type === 'choice' && Array.isArray(question.choices)) {\n const { choices, ...rest } = question;\n const criteria = Object.fromEntries(\n choices\n .filter(isObjectLike)\n .map(choice => [String(choice.value), typeof choice.description === 'string' ? choice.description : '']),\n );\n return { ...rest, criteria };\n }\n\n if (question.type === 'score' && Array.isArray(question.levels)) {\n const { levels, ...rest } = question;\n const criteria = levels.map(level => (isObjectLike(level) ? level.label : level));\n // Sentry renders score criteria as a list of labels only, so level descriptions go in their own field,\n // keyed by score value like an answer's `legend`.\n const descriptions = Object.fromEntries(\n levels.flatMap((level, index) =>\n isObjectLike(level) && typeof level.description === 'string' ? [[String(index), level.description]] : [],\n ),\n );\n return Object.keys(descriptions).length ? { ...rest, criteria, descriptions } : { ...rest, criteria };\n }\n\n return question;\n}\n\n/**\n * Lay out choice and score answers like Jev answers: probabilities keyed by option or score value, with\n * score labels in a `legend`. Predicate answers are already in the shape Sentry renders.\n */\nfunction toJevAnswerFormat(answer: unknown): unknown {\n if (\n !isObjectLike(answer) ||\n (answer.type !== 'choice' && answer.type !== 'score') ||\n !Array.isArray(answer.probabilities)\n ) {\n return answer;\n }\n\n const options = answer.probabilities.filter(isObjectLike);\n const probabilities = Object.fromEntries(options.map(option => [String(option.value), option.probability]));\n if (answer.type === 'choice') {\n // Choice values can be booleans, but Sentry renders a choice as a string, like its `probabilities` keys.\n return { ...answer, choice: String(answer.choice), probabilities };\n }\n\n const legend = Object.fromEntries(\n options.filter(option => typeof option.label === 'string').map(option => [String(option.value), option.label]),\n );\n return { ...answer, probabilities, legend };\n}\n\n/**\n * The decisions API lists questions and answers as arrays with an optional `name`, where the conventions\n * key them by question name. An unnamed item is keyed by its position.\n */\nfunction keyByName(items: unknown): unknown {\n if (!Array.isArray(items)) {\n return items;\n }\n\n return Object.fromEntries(\n items.map((item, index) => {\n if (!isObjectLike(item)) {\n return [String(index), item];\n }\n const { name, ...rest } = item;\n return [typeof name === 'string' ? name : String(index), rest];\n }),\n );\n}\n","/* eslint-disable typescript-eslint/no-deprecated */\nimport { isObjectLike } from '@sentry/core';\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_OUTPUT_MESSAGES,\n GEN_AI_REQUEST_FREQUENCY_PENALTY,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_REQUEST_PRESENCE_PENALTY,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_REQUEST_TOP_P,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n} from '@sentry/conventions/attributes';\nimport {\n GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE,\n GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE,\n GEN_AI_REQUEST_STREAM_ATTRIBUTE,\n} from '../core/gen-ai-attributes';\nimport { getDecisionOutputMessages } from './mapping';\nimport type { ChatCompletionChunk, ResponseStreamingEvent } from './types';\n\n/**\n * Check if streaming event is from the Responses API\n */\nexport function isResponsesApiStreamEvent(event: unknown): event is ResponseStreamingEvent {\n return (\n event !== null &&\n typeof event === 'object' &&\n 'type' in event &&\n typeof (event as Record<string, unknown>).type === 'string' &&\n ((event as Record<string, unknown>).type as string).startsWith('response.')\n );\n}\n\n/**\n * Check if streaming event is a chat completion chunk\n */\nexport function isChatCompletionChunk(event: unknown): event is ChatCompletionChunk {\n return (\n event !== null &&\n typeof event === 'object' &&\n 'object' in event &&\n (event as Record<string, unknown>).object === 'chat.completion.chunk'\n );\n}\n\n/**\n * Add response attributes to a span using duck-typing.\n * Works for Chat Completions, Responses API, Embeddings, and Conversations API responses. Decision\n * answers are only recorded when `operationName` is `decide`.\n */\nexport function addResponseAttributes(\n span: Span,\n result: unknown,\n recordOutputs?: boolean,\n operationName?: string,\n): void {\n if (!result || typeof result !== 'object') return;\n\n const response = result as Record<string, unknown>;\n const attrs: Record<string, SpanAttributeValue> = {};\n\n // Response ID\n if (typeof response.id === 'string') {\n attrs[GEN_AI_RESPONSE_ID] = response.id;\n }\n\n // Response model\n if (typeof response.model === 'string') {\n attrs[GEN_AI_RESPONSE_MODEL] = response.model;\n }\n\n // Conversation ID (conversation objects use id as conversation link)\n if (response.object === 'conversation' && typeof response.id === 'string') {\n attrs[GEN_AI_CONVERSATION_ID] = response.id;\n }\n\n if (isObjectLike(response.usage)) {\n addUsageAttributes(attrs, response.usage);\n }\n\n // Finish reasons from choices (chat completions)\n if (Array.isArray(response.choices)) {\n const choices = response.choices as Array<Record<string, unknown>>;\n const finishReasons = choices\n .map(choice => choice.finish_reason)\n .filter((reason): reason is string => typeof reason === 'string');\n if (finishReasons.length > 0) {\n attrs[GEN_AI_RESPONSE_FINISH_REASONS] = JSON.stringify(finishReasons);\n }\n\n if (recordOutputs) {\n // Response text from choices\n const responseTexts = choices.map(choice => {\n const message = choice.message as Record<string, unknown> | undefined;\n return (message?.content as string) || '';\n });\n attrs[GEN_AI_RESPONSE_TEXT] = JSON.stringify(responseTexts);\n\n // Tool calls from choices\n const toolCalls = choices\n .map(choice => {\n const message = choice.message as Record<string, unknown> | undefined;\n return message?.tool_calls;\n })\n .filter(calls => Array.isArray(calls) && calls.length > 0)\n .flat();\n\n if (toolCalls.length > 0) {\n attrs[GEN_AI_RESPONSE_TOOL_CALLS] = JSON.stringify(toolCalls);\n }\n }\n }\n\n // Finish reason from status (responses API)\n if (typeof response.status === 'string') {\n // Only set if not already set from choices\n if (!attrs[GEN_AI_RESPONSE_FINISH_REASONS]) {\n attrs[GEN_AI_RESPONSE_FINISH_REASONS] = JSON.stringify([response.status]);\n }\n }\n\n if (recordOutputs) {\n // Response text from output_text (responses API)\n if (typeof response.output_text === 'string' && !attrs[GEN_AI_RESPONSE_TEXT]) {\n attrs[GEN_AI_RESPONSE_TEXT] = response.output_text;\n }\n\n // Typed answers (decisions API)\n if (operationName === 'decide' && Array.isArray(response.answers)) {\n const outputMessages = getDecisionOutputMessages(response.answers);\n if (outputMessages) {\n attrs[GEN_AI_OUTPUT_MESSAGES] = outputMessages;\n }\n }\n\n // Tool calls from output array (responses API)\n if (Array.isArray(response.output) && response.output.length > 0 && !attrs[GEN_AI_RESPONSE_TOOL_CALLS]) {\n const functionCalls = (response.output as Array<Record<string, unknown>>).filter(\n item => item?.type === 'function_call',\n );\n if (functionCalls.length > 0) {\n attrs[GEN_AI_RESPONSE_TOOL_CALLS] = JSON.stringify(functionCalls);\n }\n }\n }\n\n span.setAttributes(attrs);\n}\n\n/**\n * Token usage, in both naming conventions (chat: prompt_tokens/completion_tokens,\n * responses and decisions: input_tokens/output_tokens).\n */\nfunction addUsageAttributes(attrs: Record<string, SpanAttributeValue>, usage: Record<string, unknown>): void {\n const inputTokens = usage.prompt_tokens ?? usage.input_tokens;\n if (typeof inputTokens === 'number') {\n attrs[GEN_AI_USAGE_INPUT_TOKENS] = inputTokens;\n }\n\n const outputTokens = usage.completion_tokens ?? usage.output_tokens;\n if (typeof outputTokens === 'number') {\n attrs[GEN_AI_USAGE_OUTPUT_TOKENS] = outputTokens;\n }\n\n if (typeof usage.total_tokens === 'number') {\n attrs[GEN_AI_USAGE_TOTAL_TOKENS] = usage.total_tokens;\n }\n const inputDetails = usage.prompt_tokens_details ?? usage.input_tokens_details;\n if (isObjectLike(inputDetails)) {\n if (typeof inputDetails.cached_tokens === 'number') {\n attrs[GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS] = inputDetails.cached_tokens;\n }\n if (typeof inputDetails.cache_write_tokens === 'number') {\n attrs[GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS] = inputDetails.cache_write_tokens;\n }\n }\n const outputDetails = usage.completion_tokens_details ?? usage.output_tokens_details;\n if (isObjectLike(outputDetails) && typeof outputDetails.reasoning_tokens === 'number') {\n attrs[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS] = outputDetails.reasoning_tokens;\n }\n}\n\n/**\n * Extract the Conversations API id (`conversation: \"conv_...\"`) from request parameters.\n * `previous_response_id` is deliberately not read: it names the previous response, so it changes on\n * every turn and cannot group a conversation's spans.\n * @see https://platform.openai.com/docs/guides/conversation-state\n */\nfunction extractConversationId(params: Record<string, unknown>): string | undefined {\n return 'conversation' in params && typeof params.conversation === 'string' ? params.conversation : undefined;\n}\n\n/**\n * Extract request parameters including model settings and conversation context\n */\nexport function extractRequestParameters(params: Record<string, unknown>): Record<string, unknown> {\n const attributes: Record<string, unknown> = {\n [GEN_AI_REQUEST_MODEL]: params.model ?? 'unknown',\n };\n\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 ('frequency_penalty' in params) attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY] = params.frequency_penalty;\n if ('presence_penalty' in params) attributes[GEN_AI_REQUEST_PRESENCE_PENALTY] = params.presence_penalty;\n if ('stream' in params) attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE] = params.stream;\n if ('encoding_format' in params) attributes[GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE] = params.encoding_format;\n if ('dimensions' in params) attributes[GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE] = params.dimensions;\n\n // Capture conversation ID for linking messages across API calls\n const conversationId = extractConversationId(params);\n if (conversationId) {\n attributes[GEN_AI_CONVERSATION_ID] = conversationId;\n }\n\n return attributes;\n}\n","import { captureException, SPAN_STATUS_ERROR } from '@sentry/core';\nimport type { Span } from '@sentry/core';\nimport { getToolCallKey } from '../core/streaming-tool-calls';\nimport type { GenAiSpanResult } from '../core/span-hooks';\nimport { endStreamSpan } from '../core/utils';\nimport { recordTimeToFirstChunk } from '../core/time-to-first-chunk';\nimport { RESPONSE_EVENT_TYPES } from './constants';\nimport type {\n ChatCompletionChunk,\n ChatCompletionToolCall,\n OpenAIResponseObject,\n ResponseFunctionCall,\n ResponseStreamingEvent,\n} from './types';\nimport { isChatCompletionChunk, isResponsesApiStreamEvent } from './utils';\n\n/**\n * State object used to accumulate information from a stream of OpenAI events/chunks.\n */\ninterface StreamingState {\n /** Types of events encountered in the stream. */\n eventTypes: string[];\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 prompt/input tokens used. */\n promptTokens: number | undefined;\n /** Number of completion/output tokens used. */\n completionTokens: number | undefined;\n /** Total number of tokens used (prompt + completion). */\n totalTokens: number | undefined;\n cacheReadInputTokens: number | undefined;\n cacheCreationInputTokens: number | undefined;\n /**\n * Accumulated tool calls from Chat Completion streaming, keyed by string in the order they were opened.\n * @see https://platform.openai.com/docs/guides/function-calling?api-mode=chat#streaming\n */\n chatCompletionToolCalls: Map<string, ChatCompletionToolCall>;\n /** Key of the latest tool call, which unindexed argument fragments continue. */\n lastChatCompletionToolCallKey?: string;\n /** Key of the call currently open for a reported `index`, when a new `id` reused that index. */\n chatCompletionToolCallKeyByIndex?: Map<number, string>;\n /**\n * Accumulated function calls from Responses API streaming.\n * @see https://platform.openai.com/docs/guides/function-calling?api-mode=responses#streaming\n */\n responsesApiToolCalls: Array<ResponseFunctionCall | unknown>;\n}\n\n/**\n * Processes tool calls from a chat completion chunk delta.\n * Follows the pattern: accumulate by index, then convert to array at the end.\n *\n * @param toolCalls - Array of tool calls from the delta.\n * @param state - The current streaming state to update.\n *\n * @see https://platform.openai.com/docs/guides/function-calling#streaming\n */\nfunction processChatCompletionToolCalls(toolCalls: ChatCompletionToolCall[], state: StreamingState): void {\n for (const toolCall of toolCalls) {\n if (!toolCall.function) continue;\n const index = getToolCallKey(toolCall, toolCall.function.name, {\n calls: state.chatCompletionToolCalls,\n keyByIndex: (state.chatCompletionToolCallKeyByIndex ??= new Map()),\n lastKey: state.lastChatCompletionToolCallKey,\n });\n\n // Initialize tool call if this is the first chunk for this index\n const existingToolCall = state.chatCompletionToolCalls.get(index);\n if (!existingToolCall) {\n state.chatCompletionToolCalls.set(index, {\n ...toolCall,\n function: {\n name: toolCall.function.name,\n arguments: toolCall.function.arguments || '',\n },\n });\n } else {\n // Accumulate function arguments from subsequent chunks\n if (toolCall.function.arguments && existingToolCall.function) {\n existingToolCall.function.arguments += toolCall.function.arguments;\n }\n }\n state.lastChatCompletionToolCallKey = index;\n }\n}\n\n/**\n * Processes a single OpenAI ChatCompletionChunk event, updating the streaming state.\n *\n * @param chunk - The ChatCompletionChunk event to process.\n * @param state - The current streaming state to update.\n * @param recordOutputs - Whether to record output text fragments.\n */\nfunction processChatCompletionChunk(chunk: ChatCompletionChunk, state: StreamingState, recordOutputs: boolean): void {\n state.responseId = chunk.id ?? state.responseId;\n state.responseModel = chunk.model ?? state.responseModel;\n\n if (chunk.usage) {\n // For stream responses, the input tokens remain constant across all events in the stream.\n // Output tokens, however, are only finalized in the last event.\n // Since we can't guarantee that the last event will include usage data or even be a typed event,\n // we update the output token values on every event that includes them.\n // This ensures that output token usage is always set, even if the final event lacks it.\n state.promptTokens = chunk.usage.prompt_tokens;\n state.completionTokens = chunk.usage.completion_tokens;\n state.totalTokens = chunk.usage.total_tokens;\n state.cacheReadInputTokens = chunk.usage.prompt_tokens_details?.cached_tokens ?? state.cacheReadInputTokens;\n state.cacheCreationInputTokens =\n chunk.usage.prompt_tokens_details?.cache_write_tokens ?? state.cacheCreationInputTokens;\n }\n\n for (const choice of chunk.choices ?? []) {\n if (recordOutputs) {\n if (choice.delta?.content) {\n state.responseTexts.push(choice.delta.content);\n }\n\n // Handle tool calls from delta\n if (choice.delta?.tool_calls) {\n processChatCompletionToolCalls(choice.delta.tool_calls, state);\n }\n }\n if (choice.finish_reason) {\n state.finishReasons.push(choice.finish_reason);\n }\n }\n}\n\n/**\n * Processes a single OpenAI Responses API streaming event, updating the streaming state and span.\n *\n * @param streamEvent - The event to process (may be an error or unknown object).\n * @param state - The current streaming state to update.\n * @param recordOutputs - Whether to record output text fragments.\n * @param span - The span to update with error status if needed.\n */\nfunction processResponsesApiEvent(\n streamEvent: ResponseStreamingEvent | unknown | Error,\n state: StreamingState,\n recordOutputs: boolean,\n span: Span,\n): void {\n if (!(streamEvent && typeof streamEvent === 'object')) {\n state.eventTypes.push('unknown:non-object');\n return;\n }\n if (streamEvent instanceof Error) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n captureException(streamEvent, {\n mechanism: {\n handled: false,\n type: 'auto.ai.openai.stream-response',\n },\n });\n return;\n }\n\n if (!('type' in streamEvent)) return;\n const event = streamEvent as ResponseStreamingEvent;\n\n if (!RESPONSE_EVENT_TYPES.includes(event.type)) {\n state.eventTypes.push(event.type);\n return;\n }\n\n // Handle output text delta\n if (recordOutputs) {\n // Handle tool call events for Responses API\n if (event.type === 'response.output_item.done' && 'item' in event) {\n state.responsesApiToolCalls.push(event.item);\n }\n\n if (event.type === 'response.output_text.delta' && 'delta' in event && event.delta) {\n state.responseTexts.push(event.delta);\n return;\n }\n }\n\n if ('response' in event) {\n const { response } = event as { response: OpenAIResponseObject };\n state.responseId = response.id ?? state.responseId;\n state.responseModel = response.model ?? state.responseModel;\n\n if (response.usage) {\n // For stream responses, the input tokens remain constant across all events in the stream.\n // Output tokens, however, are only finalized in the last event.\n // Since we can't guarantee that the last event will include usage data or even be a typed event,\n // we update the output token values on every event that includes them.\n // This ensures that output token usage is always set, even if the final event lacks it.\n state.promptTokens = response.usage.input_tokens;\n state.completionTokens = response.usage.output_tokens;\n state.totalTokens = response.usage.total_tokens;\n state.cacheReadInputTokens = response.usage.input_tokens_details?.cached_tokens ?? state.cacheReadInputTokens;\n state.cacheCreationInputTokens =\n response.usage.input_tokens_details?.cache_write_tokens ?? state.cacheCreationInputTokens;\n }\n\n if (response.status) {\n state.finishReasons.push(response.status);\n }\n\n if (recordOutputs && response.output_text) {\n state.responseTexts.push(response.output_text);\n }\n }\n}\n\n/**\n * Instruments a stream of OpenAI events, updating the provided span with relevant attributes and\n * optionally recording output text. This function yields each event from the input stream as it is processed.\n *\n * @template T - The type of events in the stream.\n * @param stream - The async iterable stream of events to instrument.\n * @param span - The span to add attributes to and to finish at the end of the stream.\n * @param recordOutputs - Whether to record output text fragments in the span.\n * @param beforeSpanEnd - Runs right before the span ends, with the error when the stream failed.\n * @returns An async generator yielding each event from the input stream.\n */\nexport async function* instrumentStream<T>(\n stream: AsyncIterable<T>,\n span: Span,\n recordOutputs: boolean,\n beforeSpanEnd?: (result: GenAiSpanResult<never>) => void,\n): AsyncGenerator<T, void, unknown> {\n const state: StreamingState = {\n eventTypes: [],\n responseTexts: [],\n finishReasons: [],\n responseId: '',\n responseModel: '',\n promptTokens: undefined,\n completionTokens: undefined,\n totalTokens: undefined,\n cacheReadInputTokens: undefined,\n cacheCreationInputTokens: undefined,\n chatCompletionToolCalls: new Map(),\n responsesApiToolCalls: [],\n };\n\n const result: GenAiSpanResult<never> = {};\n\n try {\n for await (const event of stream) {\n recordTimeToFirstChunk(span);\n if (isChatCompletionChunk(event)) {\n processChatCompletionChunk(event, state, recordOutputs);\n } else if (isResponsesApiStreamEvent(event)) {\n processResponsesApiEvent(event, state, recordOutputs, span);\n }\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 const allToolCalls = [...state.chatCompletionToolCalls.values(), ...state.responsesApiToolCalls];\n endStreamSpan(span, { ...state, toolCalls: allToolCalls }, recordOutputs, () => beforeSpanEnd?.(result));\n }\n}\n","/* eslint-disable typescript-eslint/no-deprecated */\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { getClient, hasSpanStreamingEnabled, startSpan, startSpanManual, debug, stringify } from '@sentry/core';\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_TOOL_DEFINITIONS,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport type { InstrumentedMethodEntry } from '../core/utils';\nimport {\n buildMethodPath,\n extractSystemInstructions,\n getErrorStatus,\n getGenAiSpanOp,\n getRequestSignal,\n resolveGenAiCallRecording,\n wrapPromiseWithMethods,\n} from '../core/utils';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport { OPENAI_METHOD_REGISTRY } from './constants';\nimport { instrumentStream } from './streaming';\nimport type { ChatCompletionChunk, OpenAiCallInfo, OpenAiOptions, OpenAIStream, ResponseStreamingEvent } from './types';\nimport { getDecisionInputMessages } from './mapping';\nimport { addResponseAttributes, extractRequestParameters } from './utils';\n\n/**\n * Extract available tools from request parameters\n */\nfunction extractAvailableTools(params: Record<string, unknown>): string | undefined {\n const tools = Array.isArray(params.tools) ? params.tools : [];\n const hasWebSearchOptions = params.web_search_options && typeof params.web_search_options === 'object';\n const webSearchOptions = hasWebSearchOptions\n ? [{ type: 'web_search_options', ...(params.web_search_options as Record<string, unknown>) }]\n : [];\n\n const availableTools = [...tools, ...webSearchOptions];\n if (availableTools.length === 0) {\n return undefined;\n }\n\n try {\n return JSON.stringify(availableTools);\n } catch (error) {\n DEBUG_BUILD && debug.error('Failed to serialize OpenAI tools:', error);\n return undefined;\n }\n}\n\n/**\n * Extract request attributes from method arguments\n */\nexport function extractRequestAttributes(\n args: unknown[],\n operationName: string,\n recordInputs: boolean,\n): Record<string, unknown> {\n const attributes: Record<string, unknown> = {\n [GEN_AI_PROVIDER_NAME]: 'openai',\n [GEN_AI_OPERATION_NAME]: operationName,\n [SENTRY_ORIGIN]: 'auto.ai.openai',\n };\n\n if (args.length > 0 && typeof args[0] === 'object' && args[0] !== null) {\n const params = args[0] as Record<string, unknown>;\n\n if (recordInputs) {\n attributes[GEN_AI_TOOL_DEFINITIONS] = extractAvailableTools(params);\n }\n\n Object.assign(attributes, extractRequestParameters(params));\n\n if (recordInputs && operationName === 'decide') {\n attributes[GEN_AI_INPUT_MESSAGES] = getDecisionInputMessages(params);\n }\n } else {\n attributes[GEN_AI_REQUEST_MODEL] = 'unknown';\n }\n\n return attributes;\n}\n\n// Extract and record AI request inputs, if present. This is intentionally separate from response attributes.\nexport function addRequestAttributes(span: Span, params: Record<string, unknown>, operationName: string): void {\n // A decision's input is recorded when its span starts, in `extractRequestAttributes`.\n if (operationName === 'decide') {\n return;\n }\n\n // Store embeddings input on a separate attribute\n if (operationName === 'embeddings' && 'input' in params) {\n const input = params.input;\n\n // No input provided\n if (input == null) {\n return;\n }\n\n // Empty input string\n if (typeof input === 'string' && input.length === 0) {\n return;\n }\n\n // Empty array input\n if (Array.isArray(input) && input.length === 0) {\n return;\n }\n\n span.setAttribute(GEN_AI_EMBEDDINGS_INPUT, stringify(input, String));\n return;\n }\n\n const src = 'input' in params ? params.input : 'messages' in params ? params.messages : undefined;\n\n if (!src) {\n return;\n }\n\n if (Array.isArray(src) && src.length === 0) {\n return;\n }\n\n const { systemInstructions, filteredMessages } = extractSystemInstructions(src);\n\n if (systemInstructions) {\n span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS, systemInstructions);\n }\n\n span.setAttribute(GEN_AI_INPUT_MESSAGES, stringify(filteredMessages));\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) => Promise<R>,\n methodPath: string,\n instrumentedMethod: InstrumentedMethodEntry,\n context: unknown,\n options: OpenAiOptions,\n): (...args: T) => Promise<R> {\n return function instrumentedCall(...args: T): Promise<R> {\n const operationName = instrumentedMethod.operation || 'unknown';\n const params = args[0] as Record<string, unknown> | undefined;\n const call: OpenAiCallInfo = { operation: operationName, request: params };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n const requestAttributes = extractRequestAttributes(args, operationName, recordInputs);\n const model = (requestAttributes[GEN_AI_REQUEST_MODEL] as string) || 'unknown';\n\n const isStreamRequested = params && typeof params === 'object' && params.stream === true;\n const abortSignal = getRequestSignal(args[1]);\n const client = getClient();\n\n const spanConfig = {\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name:\n model !== 'unknown' || !(client && hasSpanStreamingEnabled(client))\n ? `${operationName} ${model}`\n : operationName,\n op: getGenAiSpanOp(operationName),\n attributes: requestAttributes as Record<string, SpanAttributeValue>,\n };\n\n if (isStreamRequested) {\n let originalResult!: Promise<R>;\n\n const instrumentedPromise = startSpanManual(spanConfig, (span: Span) => {\n originalResult = originalMethod.apply(context, args);\n\n if (recordInputs && params) {\n addRequestAttributes(span, params, operationName);\n }\n runGenAiSpanStart(options, span, call);\n\n // Return async processing\n return (async () => {\n try {\n const result = await originalResult;\n return instrumentStream(\n result as OpenAIStream<ChatCompletionChunk | ResponseStreamingEvent>,\n span,\n recordOutputs,\n streamResult => runGenAiSpanEnd(options, span, call, streamResult),\n ) as unknown as R;\n } catch (error) {\n span.setStatus(getErrorStatus(abortSignal));\n runGenAiSpanEnd(options, span, call, { error });\n span.end();\n throw error;\n }\n })();\n });\n\n return wrapPromiseWithMethods(originalResult, instrumentedPromise);\n }\n\n // Non-streaming\n let originalResult!: Promise<R>;\n\n const instrumentedPromise = startSpan(spanConfig, (span: Span) => {\n // Call synchronously to capture the promise\n originalResult = originalMethod.apply(context, args);\n\n if (recordInputs && params) {\n addRequestAttributes(span, params, operationName);\n }\n runGenAiSpanStart(options, span, call);\n\n return originalResult.then(\n result => {\n addResponseAttributes(span, result, recordOutputs, operationName);\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 * Create a deep proxy for OpenAI client instrumentation\n */\nfunction createDeepProxy<T extends object>(target: T, currentPath = '', options: OpenAiOptions): T {\n const propertyCache = new Map<PropertyKey, { original: unknown; wrapped: unknown }>();\n\n return new Proxy(target, {\n get(obj: object, prop: string | symbol): unknown {\n const value = Reflect.get(obj, prop) as unknown;\n const cachedEntry = propertyCache.get(prop);\n if (cachedEntry) {\n if (cachedEntry.original === value) {\n return cachedEntry.wrapped;\n }\n propertyCache.delete(prop);\n }\n\n const methodPath = buildMethodPath(currentPath, String(prop));\n\n const instrumentedMethod = OPENAI_METHOD_REGISTRY[methodPath as keyof typeof OPENAI_METHOD_REGISTRY];\n if (typeof value === 'function' && instrumentedMethod) {\n const wrappedMethod = instrumentMethod(\n value as (...args: unknown[]) => Promise<unknown>,\n methodPath,\n instrumentedMethod,\n obj,\n options,\n );\n propertyCache.set(prop, { original: value, wrapped: wrappedMethod });\n return wrappedMethod;\n }\n\n if (typeof value === 'function') {\n // Bind non-instrumented functions to preserve the original `this` context,\n // which is required for accessing private class fields (e.g. #baseURL) in OpenAI SDK v5.\n const boundMethod = value.bind(obj);\n propertyCache.set(prop, { original: value, wrapped: boundMethod });\n return boundMethod;\n }\n\n if (value && typeof value === 'object') {\n const nestedProxy = createDeepProxy(value, methodPath, options);\n propertyCache.set(prop, { original: value, wrapped: nestedProxy });\n return nestedProxy;\n }\n\n return value;\n },\n }) as T;\n}\n\n/**\n * Instrument an OpenAI client with Sentry tracing\n * Can be used across Node.js, Cloudflare Workers, and Vercel Edge\n */\nexport function instrumentOpenAiClient<T extends object>(client: T, options?: OpenAiOptions): T {\n return createDeepProxy(client, '', options ?? {});\n}\n","import type { InstrumentedMethodRegistry } from '../core/utils';\n\nexport const ANTHROPIC_AI_INTEGRATION_NAME = 'Anthropic_AI' as const;\n\n// https://docs.anthropic.com/en/api/messages\nexport const ANTHROPIC_METHOD_REGISTRY = {\n 'messages.create': { operation: 'chat' },\n 'messages.stream': { operation: 'chat', streaming: true },\n 'completions.create': { operation: 'chat' },\n 'beta.messages.create': { operation: 'chat' },\n} as const satisfies InstrumentedMethodRegistry;\n\nexport const ANTHROPIC_AI_ORIGIN = 'auto.ai.anthropic';\n","/* eslint-disable typescript-eslint/no-deprecated */\nimport { captureException, isObjectLike, SPAN_STATUS_ERROR, stringify } from '@sentry/core';\nimport type { Span, SpanStatusType } from '@sentry/core';\nimport {\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n} from '@sentry/conventions/attributes';\nimport { extractSystemInstructions, getTokenUsageAttributes } from '../core/utils';\nimport type { AnthropicAiResponse, ContentBlock } from './types';\n\n/**\n * The `gen_ai.provider.name` of the client that owns an SDK resource such as `messages`. The SDK's clients\n * for other platforms set their own, e.g. `aws.bedrock` for `AnthropicBedrock`.\n */\nexport function getProviderName(resource: unknown): string {\n const name = (resource as { _client?: { _genAIProviderName?: unknown } } | null | undefined)?._client\n ?._genAIProviderName;\n return typeof name === 'string' && name ? name : 'anthropic';\n}\n\n/**\n * Get the input messages attribute, with system instructions extracted into their own attribute.\n */\nexport function getMessagesAttributes(messages: unknown): Record<string, string | undefined> {\n if (Array.isArray(messages) && messages.length === 0) {\n return {};\n }\n\n const { systemInstructions, filteredMessages } = extractSystemInstructions(messages);\n\n const attributes: Record<string, string | undefined> = {};\n if (systemInstructions) {\n attributes[GEN_AI_SYSTEM_INSTRUCTIONS] = systemInstructions;\n }\n attributes[GEN_AI_INPUT_MESSAGES] = stringify(filteredMessages);\n return attributes;\n}\n\nconst ANTHROPIC_ERROR_TYPE_TO_SPAN_STATUS: Record<string, SpanStatusType> = {\n invalid_request_error: 'invalid_argument',\n authentication_error: 'unauthenticated',\n permission_error: 'permission_denied',\n not_found_error: 'not_found',\n request_too_large: 'failed_precondition',\n rate_limit_error: 'resource_exhausted',\n api_error: 'internal_error',\n overloaded_error: 'unavailable',\n};\n\n/**\n * Map an Anthropic API error type to a SpanStatusType value.\n * @see https://docs.anthropic.com/en/api/errors#error-shapes\n */\nexport function mapAnthropicErrorToStatusMessage(errorType: string | undefined): SpanStatusType {\n if (!errorType) {\n return 'internal_error';\n }\n return ANTHROPIC_ERROR_TYPE_TO_SPAN_STATUS[errorType] || 'internal_error';\n}\n\n/**\n * Capture error information from the response\n * @see https://docs.anthropic.com/en/api/errors#error-shapes\n */\nfunction handleResponseError(span: Span, response: AnthropicAiResponse): void {\n if (response.error) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: mapAnthropicErrorToStatusMessage(response.error.type) });\n\n captureException(response.error, {\n mechanism: {\n handled: false,\n type: 'auto.ai.anthropic.anthropic_error',\n },\n });\n }\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/** Anthropic accepts the system prompt as a string or as an array of text blocks. */\nfunction systemToText(system: unknown): string | undefined {\n if (!Array.isArray(system)) {\n return typeof system === 'string' ? system : undefined;\n }\n return system\n .map(block => (isObjectLike(block) ? block.text : undefined))\n .filter(text => typeof text === 'string' && text)\n .join('\\n');\n}\n\n/**\n * Include the system prompt in the messages list, if available\n */\nexport function messagesFromParams(params: Record<string, unknown>): unknown[] {\n const { system, messages, input, prompt } = params;\n\n const systemText = systemToText(system);\n const systemMessages = systemText ? [{ role: 'system', content: systemText }] : [];\n\n const inputParamMessages = Array.isArray(input) ? input : input != null ? [input] : undefined;\n\n const messagesParamMessages = Array.isArray(messages) ? messages : messages != null ? [messages] : [];\n\n // The legacy Completions API takes a single raw `prompt` string instead of a message list. Model\n // it as one user message so it lands on `gen_ai.input.messages` like every other request shape.\n const promptMessages = prompt != null ? [{ role: 'user', content: stringify(prompt, String) }] : [];\n\n const userMessages = inputParamMessages ?? (messagesParamMessages.length ? messagesParamMessages : promptMessages);\n\n return [...systemMessages, ...userMessages];\n}\n","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","import type { Scope } from '@sentry/core';\nimport { getClient, getDefaultCurrentScope, withIsolationScope, withScope } from '@sentry/core';\n\n/**\n * Run `callback` with `isolationScope` and a fresh copy of the default current scope. For work that\n * a library schedules from whichever async context last woke it: a forked scope would carry over the\n * data of that context, such as the conversation id of another run. Only the client of that context\n * is kept, because an SDK that initializes inside each request, such as `@sentry/cloudflare`, binds\n * it to the request's scope alone.\n */\nexport function withCleanScopes<T>(isolationScope: Scope, callback: () => T): T {\n const client = getClient();\n return withIsolationScope(isolationScope, () => {\n const scope = getDefaultCurrentScope().clone();\n if (client) {\n scope.setClient(client);\n }\n return withScope(scope, callback);\n });\n}\n","import type { Span, WrappedFunction } from '@sentry/core';\nimport {\n captureException,\n fill,\n getActiveSpan,\n getCurrentScope,\n getDefaultCurrentScope,\n getDefaultIsolationScope,\n getIsolationScope,\n getOriginalFunction,\n handleCallbackErrors,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n startNewTrace,\n startSpan,\n stringify,\n withActiveSpan,\n withScope,\n} from '@sentry/core';\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_OPERATION_NAME,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DESCRIPTION,\n GEN_AI_TOOL_NAME,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_EXECUTE_TOOL, GEN_AI_INVOKE_AGENT } from '@sentry/conventions/op';\nimport { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport { getErrorStatus, resolveGenAiCallRecording } from '../core/utils';\nimport { withCleanScopes } from '../../utils/withCleanScopes';\nimport { ANTHROPIC_AI_ORIGIN } from './constants';\nimport type { AnthropicAiCallInfo, AnthropicAiOptions } from './types';\n\ntype AnyFunction = (...args: unknown[]) => unknown;\ntype RunnableTool = { name: string; description?: unknown };\ntype RunContext = { toolUse?: { id?: unknown }; toolUseBlock?: { id?: unknown }; signal?: AbortSignal } | undefined;\ntype ToolRunner = { params?: { tools?: unknown } };\ntype SessionToolRunner = { tools?: unknown; sessionId?: unknown };\n\n/** Wrap the `toolRunner()` method of `owner` so the runners it returns trace their tool calls. */\nexport function instrumentToolRunnerFactory(\n owner: object,\n instrumentRunner: (runner: unknown, options: AnthropicAiOptions) => void,\n options: AnthropicAiOptions,\n): void {\n wrapInPlace(owner, 'toolRunner', (toolRunner, thisArg, args) => {\n const runner = toolRunner.apply(thisArg, args);\n instrumentRunner(runner, options);\n return runner;\n });\n}\n\n/** Give each tool call of a tool runner a `gen_ai.execute_tool` span. */\nexport function instrumentToolRunner(runner: unknown, options: AnthropicAiOptions): void {\n if (!runner || typeof runner !== 'object') {\n return;\n }\n\n instrumentTools((runner as ToolRunner).params?.tools, options);\n\n // `addTools()` keeps its tools out of `params`.\n wrapInPlace(runner, 'addTools', (addTools, thisArg, tools) => {\n instrumentTools(tools, options);\n return addTools.apply(thisArg, tools);\n });\n wrapInPlace(runner, 'setMessagesParams', (setMessagesParams, thisArg, args) => {\n const result = setMessagesParams.apply(thisArg, args);\n instrumentTools((runner as ToolRunner).params?.tools, options);\n return result;\n });\n}\n\n/** Give each tool call of a Managed Agents session runner an `execute_tool` span, under one `invoke_agent` span per session. */\nexport function instrumentSessionToolRunner(runner: unknown, options: AnthropicAiOptions): void {\n if (!runner || typeof runner !== 'object') {\n return;\n }\n\n const { tools, sessionId } = runner as SessionToolRunner;\n // The session runner has no `addTools()`: it only runs the tools it was created with.\n instrumentTools(tools, options);\n wrapInPlace(runner, Symbol.asyncIterator, (iterate, thisArg) =>\n traceSessionLoop(\n iterate.call(thisArg) as AsyncIterator<unknown>,\n typeof sessionId === 'string' ? sessionId : undefined,\n ),\n );\n}\n\n/** Wraps the SDK's session iterator so the whole session runs inside one `invoke_agent` span. */\nasync function* traceSessionLoop(\n sdkIterator: AsyncIterator<unknown>,\n sessionId: string | undefined,\n): AsyncGenerator<unknown> {\n const { span, firstResult } = startSession(sdkIterator, sessionId);\n\n try {\n let result = await firstResult;\n while (!result.done) {\n yield result.value;\n result = await sdkIterator.next();\n }\n } catch (error) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n throw error;\n } finally {\n try {\n // After a `break`, closing the SDK loop waits for its in-flight tools, so the span ends after them.\n await sdkIterator.return?.();\n } finally {\n span.end();\n }\n }\n}\n\n// The SDK starts its tool loop on the first `next()`, so that call runs in the session and every tool inherits it.\nfunction startSession(\n sdkIterator: AsyncIterator<unknown>,\n sessionId: string | undefined,\n): { span: Span; firstResult: Promise<IteratorResult<unknown>> } {\n const start = (): { span: Span; firstResult: Promise<IteratorResult<unknown>> } =>\n withScope(scope => {\n // A tool shared between runners can't tell its session, so the id reaches its spans through the scope, unless\n // the app set one with `Sentry.setConversationId()`.\n if (sessionId && !scope.getScopeData().conversationId && !getIsolationScope().getScopeData().conversationId) {\n scope.setConversationId(sessionId);\n }\n\n const span = startInactiveSpan({\n name: 'invoke_agent',\n op: GEN_AI_INVOKE_AGENT,\n attributes: {\n [SENTRY_ORIGIN]: ANTHROPIC_AI_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'invoke_agent',\n [GEN_AI_PROVIDER_NAME]: 'anthropic',\n ...(sessionId ? { [GEN_AI_CONVERSATION_ID]: sessionId } : {}),\n },\n });\n // `async`, so a `next()` that throws rejects `firstResult` and still ends the span.\n return { span, firstResult: withActiveSpan(span, async () => sdkIterator.next()) };\n });\n\n // At top level all sessions would share the process's trace, so each gets its own; anywhere else it stays in the\n // caller's.\n return !getActiveSpan() && getCurrentScope() === getDefaultCurrentScope()\n ? withCleanScopes(getDefaultIsolationScope().clone(), () => startNewTrace(start))\n : start();\n}\n\nfunction instrumentTools(tools: unknown, options: AnthropicAiOptions): void {\n if (!Array.isArray(tools)) {\n return;\n }\n\n for (const tool of tools) {\n // Toolsets are nameless entries whose `run` takes `(ctx, toolUse)`, so only named tools are wrapped.\n if (tool && typeof tool === 'object' && typeof (tool as RunnableTool).name === 'string') {\n wrapInPlace(tool, 'run', (run, thisArg, args) => runWithSpan(tool as RunnableTool, run, thisArg, args, options));\n }\n }\n}\n\nfunction wrapInPlace(\n owner: object,\n key: string | symbol,\n call: (original: AnyFunction, thisArg: unknown, args: unknown[]) => unknown,\n): void {\n const current = (owner as Record<string | symbol, unknown>)[key];\n if (typeof current === 'function' && !getOriginalFunction(current as WrappedFunction)) {\n fill(\n owner,\n key,\n (original: AnyFunction) =>\n function (this: unknown, ...args: unknown[]): unknown {\n return call(original, this, args);\n },\n );\n }\n}\n\nfunction runWithSpan(\n tool: RunnableTool,\n run: AnyFunction,\n thisArg: unknown,\n args: unknown[],\n options: AnthropicAiOptions,\n): unknown {\n const [input, context] = args as [unknown, RunContext];\n const call: AnthropicAiCallInfo = { operation: 'execute_tool', tool, input };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n // SDK versions before `toolUse` existed pass only `toolUseBlock`.\n const callId = (context?.toolUse ?? context?.toolUseBlock)?.id;\n\n return startSpan(\n {\n name: `execute_tool ${tool.name}`,\n op: GEN_AI_EXECUTE_TOOL,\n attributes: {\n [SENTRY_ORIGIN]: ANTHROPIC_AI_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'execute_tool',\n [GEN_AI_TOOL_NAME]: tool.name,\n ...(typeof tool.description === 'string' ? { [GEN_AI_TOOL_DESCRIPTION]: tool.description } : {}),\n ...(typeof callId === 'string' ? { [GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: callId } : {}),\n ...(recordInputs ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(input) } : {}),\n },\n },\n span => {\n runGenAiSpanStart(options, span, call);\n return handleCallbackErrors(\n () => run.apply(thisArg, args),\n error => {\n handleToolError(span, error, context);\n runGenAiSpanEnd(options, span, call, { error });\n },\n undefined,\n result => {\n if (recordOutputs) {\n span.setAttribute(GEN_AI_TOOL_CALL_RESULT, stringify(result));\n }\n runGenAiSpanEnd(options, span, call, { response: result });\n },\n );\n },\n );\n}\n\nfunction handleToolError(span: Span, error: unknown, context: RunContext): void {\n span.setStatus(getErrorStatus(context?.signal));\n // An aborted tool, caller abort or timeout, throws because the run stopped, not because the tool failed.\n if (context?.signal?.aborted) {\n return;\n }\n\n // Only a runner passes `toolUse`/`toolUseBlock` (SDK 0.85+), and it hands the throw to the model as a result.\n // A direct call rethrows to its caller, and a `ToolError` is sent on purpose, so neither is captured.\n const fromRunner = !!(context?.toolUse ?? context?.toolUseBlock);\n if (fromRunner && (error as Error | undefined)?.name !== 'ToolError') {\n captureException(error, { mechanism: { handled: true, type: ANTHROPIC_AI_ORIGIN } });\n }\n}\n","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","import type { InstrumentedMethodRegistry } from '../core/utils';\n\nexport const GOOGLE_GENAI_INTEGRATION_NAME = 'Google_GenAI' as const;\n\n// https://ai.google.dev/api/rest/v1/models/generateContent\n// https://ai.google.dev/api/rest/v1/chats/sendMessage\n// https://googleapis.github.io/js-genai/release_docs/classes/models.Models.html#generatecontentstream\n// https://googleapis.github.io/js-genai/release_docs/classes/chats.Chat.html#sendmessagestream\n// https://ai.google.dev/api/decisions\nexport const GOOGLE_GENAI_METHOD_REGISTRY = {\n 'models.generateContent': { operation: 'generate_content' },\n 'models.generateContentStream': { operation: 'generate_content', streaming: true },\n 'models.embedContent': { operation: 'embeddings' },\n 'chats.create': { proxyResultPath: 'chat' },\n 'chat.sendMessage': { operation: 'chat' },\n 'chat.sendMessageStream': { operation: 'chat', streaming: true },\n 'decisions.create': { operation: 'decide' },\n} as const satisfies InstrumentedMethodRegistry;\n\n// Constants for internal use\nexport const GOOGLE_GENAI_SYSTEM_NAME = 'google_genai';\n","// Google's questions and answers already use Jev's layout, so only the evaluated input is mapped.\nimport { GEN_AI_OUTPUT_MESSAGES } from '@sentry/conventions/attributes';\nimport type { Span } from '@sentry/core';\nimport { isObjectLike } from '@sentry/core';\nimport { getEvaluationInputMessages, getEvaluationOutputMessages, getTokenUsageAttributes } from '../core/utils';\nimport type { GenAiMessage, GenAiMessagePart } from '../types';\n\n/**\n * Serialize a decisions request. Its evidence is `input` where Jev's is `state`; it is recorded as `state`\n * so both render the same.\n */\nexport function getDecisionInputMessages(params: Record<string, unknown>): string | undefined {\n return getEvaluationInputMessages({ state: toStateMessages(params.input), questions: params.questions });\n}\n\n/**\n * Multimodal evidence is one part or a list of parts, recorded as one user message so it renders like OpenAI's.\n * Inline media is reported by modality and media type only: its `data` is base64, which the conventions require\n * to be dropped.\n */\nfunction toStateMessages(input: unknown): unknown {\n if (typeof input === 'string') {\n return input;\n }\n\n const parts = (Array.isArray(input) ? input : [input]).filter(isObjectLike).map((part): GenAiMessagePart => {\n if (part.type === 'text') {\n return { type: 'text', content: part.text };\n }\n if (typeof part.uri === 'string') {\n return { type: 'uri', modality: part.type, mime_type: part.mime_type, uri: part.uri };\n }\n return { type: 'blob', modality: part.type, mime_type: part.mime_type };\n });\n return [{ role: 'user', parts } satisfies GenAiMessage];\n}\n\nexport function addDecisionResponseAttributes(span: Span, response: unknown, recordOutputs: boolean): void {\n if (!isObjectLike(response)) {\n return;\n }\n\n if (isObjectLike(response.usage)) {\n const usage = response.usage as Record<string, number | undefined>;\n span.setAttributes(\n getTokenUsageAttributes(\n usage.total_input_tokens,\n usage.total_output_tokens,\n undefined,\n usage.total_cached_tokens,\n usage.total_tokens,\n ),\n );\n }\n\n if (recordOutputs && response.answers !== undefined) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, getEvaluationOutputMessages(response.answers));\n }\n}\n","import { isObjectLike, stringify } from '@sentry/core';\nimport type { Span } from '@sentry/core';\nimport { GEN_AI_OUTPUT_MESSAGES } from '@sentry/conventions/attributes';\n\n// Copied from https://googleapis.github.io/js-genai/release_docs/index.html\nexport type ContentListUnion = Content | Content[] | PartListUnion;\nexport type ContentUnion = Content | PartUnion[] | PartUnion;\nexport type Content = {\n parts?: Part[];\n role?: string;\n};\nexport type PartUnion = Part | string;\nexport type Part = Record<string, unknown> & {\n inlineData?: {\n data?: string;\n displayName?: string;\n mimeType?: string;\n };\n text?: string;\n};\nexport type PartListUnion = PartUnion[] | PartUnion;\n\n/**\n * A message part as described in https://develop.sentry.dev/sdk/telemetry/traces/modules/ai-agents/.\n * Parts Sentry cannot type are dropped when the message is rendered, so Google's own `Part` shape\n * (`{ text }`, `{ functionCall }`, ...) has to be translated into this one.\n */\nexport type MessagePart = Record<string, unknown> & { type: string };\n\nexport type Message = {\n role: string;\n parts: MessagePart[];\n};\n\n// `gen_ai` roles are `user`, `assistant`, `tool` and `system`; Google only ever emits `user` or `model`.\nfunction normalizeRole(role: string): string {\n return role === 'model' ? 'assistant' : role;\n}\n\nfunction mimeTypeOf(value: Record<PropertyKey, unknown>): string | undefined {\n return typeof value.mimeType === 'string' ? value.mimeType : undefined;\n}\n\n/**\n * Binary payloads are reported by media type only: `inlineData.data` is base64 bytes, which the\n * conventions require to be dropped rather than recorded.\n */\nexport function partToMessagePart(part: unknown): MessagePart | undefined {\n if (typeof part === 'string') {\n return { type: 'text', content: part };\n }\n\n if (!isObjectLike(part)) {\n return undefined;\n }\n\n if (typeof part.text === 'string') {\n return { type: part.thought === true ? 'reasoning' : 'text', content: part.text };\n }\n\n const { functionCall, functionResponse, inlineData, fileData } = part;\n\n if (isObjectLike(functionCall)) {\n return {\n type: 'tool_call',\n id: functionCall.id,\n name: functionCall.name,\n arguments: stringify(functionCall.args ?? {}, String),\n };\n }\n\n if (isObjectLike(functionResponse)) {\n return {\n type: 'tool_call_response',\n id: functionResponse.id,\n name: functionResponse.name,\n result: stringify(functionResponse.response ?? {}, String),\n };\n }\n\n if (isObjectLike(inlineData)) {\n return { type: 'blob', mime_type: mimeTypeOf(inlineData) };\n }\n\n if (isObjectLike(fileData)) {\n return { type: 'uri', mime_type: mimeTypeOf(fileData), uri: fileData.fileUri };\n }\n\n // Part kinds we don't know yet render as JSON rather than disappearing.\n return { type: 'object', content: part };\n}\n\nfunction partsToMessageParts(parts: unknown): MessagePart[] {\n const list = Array.isArray(parts) ? parts : parts != null ? [parts] : [];\n return list.map(partToMessagePart).filter((part): part is MessagePart => part !== undefined);\n}\n\nfunction isContent(value: unknown): value is Content {\n return isObjectLike(value) && (typeof value.role === 'string' || Array.isArray(value.parts));\n}\n\nfunction contentToMessage(content: Content, role: string): Message {\n return {\n role: normalizeRole(typeof content.role === 'string' ? content.role : role),\n parts: partsToMessageParts(content.parts),\n };\n}\n\n/**\n * Bare parts are collected into one message rather than one message each: `[{ text }, { inlineData }]`\n * is a single multimodal turn in Google's API, not two turns.\n */\nexport function contentUnionToMessages(content: ContentListUnion, role = 'user'): Message[] {\n if (Array.isArray(content)) {\n const messages: Message[] = [];\n let looseParts: MessagePart[] = [];\n\n const flushLooseParts = (): void => {\n if (looseParts.length) {\n messages.push({ role: normalizeRole(role), parts: looseParts });\n looseParts = [];\n }\n };\n\n for (const item of content) {\n if (isContent(item)) {\n flushLooseParts();\n const message = contentToMessage(item, role);\n if (message.parts.length) {\n messages.push(message);\n }\n } else {\n const part = partToMessagePart(item);\n if (part) {\n looseParts.push(part);\n }\n }\n }\n\n flushLooseParts();\n return messages;\n }\n\n if (isContent(content)) {\n const message = contentToMessage(content, role);\n return message.parts.length ? [message] : [];\n }\n\n const part = partToMessagePart(content);\n return part ? [{ role: normalizeRole(role), parts: [part] }] : [];\n}\n\n/** Collect the message parts of every candidate in a response. */\nexport function candidatesToMessageParts(candidates: unknown): MessagePart[] {\n if (!Array.isArray(candidates)) {\n return [];\n }\n\n return candidates.flatMap(candidate =>\n isObjectLike(candidate) && isObjectLike(candidate.content)\n ? partsToMessageParts(candidate.content.parts as PartListUnion | undefined)\n : [],\n );\n}\n\n/**\n * A streamed response delivers its text a few characters at a time, so the parts collected across\n * chunks would otherwise be hundreds of one-word fragments.\n */\nfunction mergeAdjacentTextParts(parts: MessagePart[]): MessagePart[] {\n const merged: MessagePart[] = [];\n\n for (const part of parts) {\n const previous = merged[merged.length - 1];\n const mergeable = part.type === 'text' || part.type === 'reasoning';\n\n if (mergeable && previous?.type === part.type && typeof previous.content === 'string') {\n previous.content += typeof part.content === 'string' ? part.content : '';\n } else {\n merged.push({ ...part });\n }\n }\n\n return merged;\n}\n\n/**\n * Set alongside the deprecated `gen_ai.response.text` / `gen_ai.response.tool_calls`: Relay migrates\n * those into `gen_ai.output.messages`, but the tool-calls half of that migration is lossy, so a turn\n * that only calls a tool would otherwise render an empty Output.\n */\nexport function setOutputMessagesAttribute(span: Span, parts: MessagePart[]): void {\n const merged = mergeAdjacentTextParts(parts);\n if (merged.length) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, JSON.stringify([{ role: 'assistant', parts: merged }]));\n }\n}\n\n/** Flatten a `ContentUnion` instruction into the plain text `gen_ai.system_instructions` expects. */\nexport function systemInstructionToText(systemInstruction: unknown): string | undefined {\n const texts = contentUnionToMessages(systemInstruction as ContentUnion, 'system')\n .flatMap(message => message.parts)\n .map(part => (part.type === 'text' && typeof part.content === 'string' ? part.content : ''))\n .filter(text => text.length > 0);\n\n return texts.length ? texts.join('\\n') : undefined;\n}\n","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 { GoogleGenAIResponse } from './types';\nimport type { MessagePart } from './utils';\nimport { candidatesToMessageParts, setOutputMessagesAttribute } from './utils';\n\n/**\n * State object used to accumulate information from a stream of Google GenAI 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 prompt/input tokens used. Tool-use prompt tokens are added when the stream ends. */\n promptTokens?: number;\n toolUsePromptTokens?: number;\n /** Number of completion/output tokens used. */\n completionTokens?: number;\n candidateTokens?: number;\n reasoningOutputTokens?: number;\n /** Number of total tokens used. */\n totalTokens?: number;\n cacheReadInputTokens?: number;\n /** Accumulated tool calls (finalized) */\n toolCalls: Array<Record<string, unknown>>;\n /** Accumulated output message parts (for output recording). */\n outputParts: MessagePart[];\n}\n\n/**\n * Checks if a response chunk contains an error\n * @param chunk - The response chunk to check\n * @param span - The span to update if error is found\n * @returns Whether an error occurred\n */\nfunction isErrorChunk(chunk: GoogleGenAIResponse, span: Span): boolean {\n const feedback = chunk?.promptFeedback;\n if (feedback?.blockReason) {\n const message = feedback.blockReasonMessage ?? feedback.blockReason;\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n captureException(`Content blocked: ${message}`, {\n mechanism: { handled: false, type: 'auto.ai.google_genai' },\n });\n return true;\n }\n return false;\n}\n\n/**\n * Processes response metadata from a chunk\n * @param chunk - The response chunk to process\n * @param state - The state of the streaming process\n */\nfunction handleResponseMetadata(chunk: GoogleGenAIResponse, state: StreamingState): void {\n if (typeof chunk.responseId === 'string') state.responseId = chunk.responseId;\n if (typeof chunk.modelVersion === 'string') state.responseModel = chunk.modelVersion;\n\n const usage = chunk.usageMetadata;\n if (usage) {\n if (typeof usage.promptTokenCount === 'number') state.promptTokens = usage.promptTokenCount;\n if (typeof usage.toolUsePromptTokenCount === 'number') state.toolUsePromptTokens = usage.toolUsePromptTokenCount;\n if (typeof usage.candidatesTokenCount === 'number') state.candidateTokens = usage.candidatesTokenCount;\n if (typeof usage.thoughtsTokenCount === 'number') state.reasoningOutputTokens = usage.thoughtsTokenCount;\n if (state.candidateTokens !== undefined || state.reasoningOutputTokens !== undefined) {\n state.completionTokens = (state.candidateTokens ?? 0) + (state.reasoningOutputTokens ?? 0);\n }\n if (typeof usage.totalTokenCount === 'number') state.totalTokens = usage.totalTokenCount;\n if (typeof usage.cachedContentTokenCount === 'number') state.cacheReadInputTokens = usage.cachedContentTokenCount;\n }\n}\n\n/**\n * Processes candidate content from a response chunk\n * @param chunk - The response chunk to process\n * @param state - The state of the streaming process\n * @param recordOutputs - Whether to record outputs\n */\nfunction handleCandidateContent(chunk: GoogleGenAIResponse, state: StreamingState, recordOutputs: boolean): void {\n // The SDK getter already extracts function calls from candidate parts.\n if (Array.isArray(chunk.functionCalls)) {\n state.toolCalls.push(...chunk.functionCalls);\n }\n\n if (recordOutputs) {\n state.outputParts.push(...candidatesToMessageParts(chunk.candidates));\n }\n\n for (const candidate of chunk.candidates ?? []) {\n if (candidate?.finishReason && !state.finishReasons.includes(candidate.finishReason)) {\n state.finishReasons.push(candidate.finishReason);\n }\n\n for (const part of candidate?.content?.parts ?? []) {\n if (recordOutputs && part.text) state.responseTexts.push(part.text);\n }\n }\n}\n\n/**\n * Processes a single chunk from the Google GenAI stream\n * @param chunk - The chunk 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 processChunk(chunk: GoogleGenAIResponse, state: StreamingState, recordOutputs: boolean, span: Span): void {\n if (!chunk || isErrorChunk(chunk, span)) return;\n recordTimeToFirstChunk(span);\n handleResponseMetadata(chunk, state);\n handleCandidateContent(chunk, state, recordOutputs);\n}\n\n/**\n * Instruments an async iterable stream of Google GenAI response chunks, updates the span with\n * streaming attributes and (optionally) the aggregated output text, and yields\n * each chunk from the input stream unchanged.\n */\nexport async function* instrumentStream(\n stream: AsyncIterable<GoogleGenAIResponse>,\n span: Span,\n recordOutputs: boolean,\n abortSignal?: AbortSignal,\n beforeSpanEnd?: (result: GenAiSpanResult<never>) => void,\n): AsyncGenerator<GoogleGenAIResponse, void, unknown> {\n const state: StreamingState = {\n responseTexts: [],\n finishReasons: [],\n toolCalls: [],\n outputParts: [],\n };\n const result: GenAiSpanResult<never> = {};\n\n try {\n for await (const chunk of stream) {\n processChunk(chunk, state, recordOutputs, span);\n yield chunk;\n }\n } catch (error) {\n span.setStatus(getErrorStatus(abortSignal));\n result.error = error;\n throw error;\n } finally {\n if (recordOutputs) {\n setOutputMessagesAttribute(span, state.outputParts);\n }\n if (typeof state.promptTokens === 'number') state.promptTokens += state.toolUsePromptTokens ?? 0;\n endStreamSpan(span, state, recordOutputs, () => beforeSpanEnd?.(result));\n }\n}\n","/* eslint-disable typescript-eslint/no-deprecated */\n/* eslint-disable max-lines */\nimport {\n getClient,\n handleCallbackErrors,\n hasSpanStreamingEnabled,\n startSpan,\n startSpanManual,\n stringify,\n} from '@sentry/core';\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_INPUT_MESSAGES,\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_PRESENCE_PENALTY,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_REQUEST_TOP_K,\n GEN_AI_REQUEST_TOP_P,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_TOOL_DEFINITIONS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { InstrumentedMethodEntry } from '../core/utils';\nimport {\n buildMethodPath,\n getErrorStatus,\n getGenAiSpanOp,\n getRequestSignal,\n getTokenUsageAttributes,\n resolveGenAiCallRecording,\n} from '../core/utils';\nimport { GOOGLE_GENAI_METHOD_REGISTRY, GOOGLE_GENAI_SYSTEM_NAME } from './constants';\nimport { addDecisionResponseAttributes, getDecisionInputMessages } from './decisions';\nimport { instrumentStream } from './streaming';\nimport type { Candidate, ContentPart, GoogleGenAICallInfo, GoogleGenAIOptions, GoogleGenAIResponse } from './types';\nimport type { ContentListUnion, Message, PartListUnion } from './utils';\nimport {\n candidatesToMessageParts,\n contentUnionToMessages,\n setOutputMessagesAttribute,\n systemInstructionToText,\n} from './utils';\n\n/**\n * Extract model from parameters or chat context object\n * For chat instances, the model is available on the chat object as 'model' (older versions) or 'modelVersion' (newer versions)\n */\nexport function extractModel(params: Record<string, unknown>, context?: unknown): string {\n if ('model' in params && typeof params.model === 'string') {\n return params.model;\n }\n\n // Try to get model from chat context object (chat instance has model property)\n if (context && typeof context === 'object') {\n const contextObj = context as Record<string, unknown>;\n\n // Check for 'model' property (older versions, and streaming)\n if ('model' in contextObj && typeof contextObj.model === 'string') {\n return contextObj.model;\n }\n\n // Check for 'modelVersion' property (newer versions)\n if ('modelVersion' in contextObj && typeof contextObj.modelVersion === 'string') {\n return contextObj.modelVersion;\n }\n }\n\n return 'unknown';\n}\n\n/**\n * Extract generation config parameters\n */\nfunction extractConfigAttributes(config: Record<string, unknown>): Record<string, SpanAttributeValue> {\n const attributes: Record<string, SpanAttributeValue> = {};\n\n if ('temperature' in config && typeof config.temperature === 'number') {\n attributes[GEN_AI_REQUEST_TEMPERATURE] = config.temperature;\n }\n if ('topP' in config && typeof config.topP === 'number') {\n attributes[GEN_AI_REQUEST_TOP_P] = config.topP;\n }\n if ('topK' in config && typeof config.topK === 'number') {\n attributes[GEN_AI_REQUEST_TOP_K] = config.topK;\n }\n if ('maxOutputTokens' in config && typeof config.maxOutputTokens === 'number') {\n attributes[GEN_AI_REQUEST_MAX_TOKENS] = config.maxOutputTokens;\n }\n if ('frequencyPenalty' in config && typeof config.frequencyPenalty === 'number') {\n attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY] = config.frequencyPenalty;\n }\n if ('presencePenalty' in config && typeof config.presencePenalty === 'number') {\n attributes[GEN_AI_REQUEST_PRESENCE_PENALTY] = config.presencePenalty;\n }\n\n return attributes;\n}\n\n/**\n * Extract request attributes from method arguments\n * Builds the base attributes for span creation including system info, model, and config\n */\nexport function extractRequestAttributes(\n operationName: string,\n params?: Record<string, unknown>,\n context?: unknown,\n recordInputs = true,\n): Record<string, SpanAttributeValue> {\n const attributes: Record<string, SpanAttributeValue> = {\n [GEN_AI_PROVIDER_NAME]: GOOGLE_GENAI_SYSTEM_NAME,\n [GEN_AI_OPERATION_NAME]: operationName,\n [SENTRY_ORIGIN]: 'auto.ai.google_genai',\n };\n\n if (params) {\n attributes[GEN_AI_REQUEST_MODEL] = extractModel(params, context);\n\n // Extract generation config parameters\n if ('config' in params && typeof params.config === 'object' && params.config) {\n const config = params.config as Record<string, unknown>;\n Object.assign(attributes, extractConfigAttributes(config));\n\n // Extract available tools from config\n if (recordInputs && 'tools' in config && Array.isArray(config.tools)) {\n const functionDeclarations = config.tools.flatMap(\n (tool: { functionDeclarations: unknown[] }) => tool.functionDeclarations,\n );\n attributes[GEN_AI_TOOL_DEFINITIONS] = JSON.stringify(functionDeclarations);\n }\n }\n\n const decisionInput = recordInputs && operationName === 'decide' ? getDecisionInputMessages(params) : undefined;\n if (decisionInput) {\n attributes[GEN_AI_INPUT_MESSAGES] = decisionInput;\n }\n } else {\n attributes[GEN_AI_REQUEST_MODEL] = extractModel({}, context);\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 * Handles different parameter formats for different Google GenAI methods.\n */\nexport function addPrivateRequestAttributes(span: Span, params: Record<string, unknown>, operationName: string): void {\n if (operationName === 'embeddings') {\n const contents = params.contents;\n if (contents != null) {\n span.setAttribute(GEN_AI_EMBEDDINGS_INPUT, stringify(contents, String));\n }\n return;\n }\n\n // config.systemInstruction: ContentUnion. It has its own attribute, so it never joins the message list.\n if (\n 'config' in params &&\n params.config &&\n typeof params.config === 'object' &&\n 'systemInstruction' in params.config &&\n params.config.systemInstruction\n ) {\n const systemInstructions = systemInstructionToText(params.config.systemInstruction);\n if (systemInstructions) {\n span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS, JSON.stringify([{ type: 'text', content: systemInstructions }]));\n }\n }\n\n const messages: Message[] = [];\n\n // For chats.create: history contains the conversation history\n if ('history' in params) {\n messages.push(...contentUnionToMessages(params.history as PartListUnion, 'user'));\n }\n\n // For models.generateContent: ContentListUnion\n if ('contents' in params) {\n messages.push(...contentUnionToMessages(params.contents as ContentListUnion, 'user'));\n }\n\n // For chat.sendMessage: message can be PartListUnion\n if ('message' in params) {\n messages.push(...contentUnionToMessages(params.message as PartListUnion, 'user'));\n }\n\n if (messages.length) {\n span.setAttributes({\n [GEN_AI_INPUT_MESSAGES]: stringify(messages),\n });\n }\n}\n\n/**\n * Add response attributes from the Google GenAI response\n * @see https://github.com/googleapis/js-genai/blob/v1.19.0/src/types.ts#L2313\n */\nexport function addResponseAttributes(\n span: Span,\n response: GoogleGenAIResponse,\n recordOutputs?: boolean,\n operationName?: string,\n): void {\n if (!response || typeof response !== 'object') return;\n\n if (operationName === 'decide') {\n addDecisionResponseAttributes(span, response, !!recordOutputs);\n return;\n }\n\n if (response.modelVersion) {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, response.modelVersion);\n }\n\n // Add usage metadata if present\n if (response.usageMetadata && typeof response.usageMetadata === 'object') {\n const usage = response.usageMetadata;\n const hasOutput = typeof usage.candidatesTokenCount === 'number' || typeof usage.thoughtsTokenCount === 'number';\n span.setAttributes(\n getTokenUsageAttributes(\n typeof usage.promptTokenCount === 'number'\n ? usage.promptTokenCount + (usage.toolUsePromptTokenCount ?? 0)\n : undefined,\n hasOutput ? (usage.candidatesTokenCount ?? 0) + (usage.thoughtsTokenCount ?? 0) : undefined,\n undefined,\n usage.cachedContentTokenCount,\n usage.totalTokenCount,\n ),\n );\n if (typeof usage.thoughtsTokenCount === 'number') {\n span.setAttribute(GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, usage.thoughtsTokenCount);\n }\n }\n\n if (recordOutputs) {\n setOutputMessagesAttribute(span, candidatesToMessageParts(response.candidates));\n }\n\n // Add response text if recordOutputs is enabled\n if (recordOutputs && Array.isArray(response.candidates) && response.candidates.length > 0) {\n const responseTexts = response.candidates\n .map((candidate: Candidate) => {\n if (candidate.content?.parts && Array.isArray(candidate.content.parts)) {\n return candidate.content.parts\n .map((part: ContentPart) => (typeof part.text === 'string' ? part.text : ''))\n .filter((text: string) => text.length > 0)\n .join('');\n }\n return '';\n })\n .filter((text: string) => text.length > 0);\n\n if (responseTexts.length > 0) {\n span.setAttributes({\n [GEN_AI_RESPONSE_TEXT]: responseTexts.join(''),\n });\n }\n }\n\n // Add tool calls if recordOutputs is enabled\n if (recordOutputs && response.functionCalls) {\n const functionCalls = response.functionCalls;\n if (Array.isArray(functionCalls) && functionCalls.length > 0) {\n span.setAttributes({\n [GEN_AI_RESPONSE_TOOL_CALLS]: JSON.stringify(functionCalls),\n });\n }\n }\n}\n\n/**\n * Recover the config a chat message sends but does not carry in its own arguments.\n *\n * `chats.create()` takes a config that `@google/genai` reuses for every message, resolving each\n * request as `params.config ?? chat.config`. A per-message config therefore replaces the chat\n * config rather than merging into it, and the chat config applies only when the message omits one.\n * That config lives on the chat instance, which both instrumentation paths already hold: the client\n * proxy passes it as the method's `context`, the diagnostics-channel path as `data.self`.\n *\n * The chat `history` stays off the message spans. The SDK does send it, folded into `contents`, and\n * the instance carries the whole transcript, but repeating every past turn on every message span\n * duplicates what earlier spans already reported and grows without bound.\n */\nexport function resolveChatParams(\n operationName: string,\n params: Record<string, unknown> | undefined,\n context: unknown,\n): Record<string, unknown> | undefined {\n // `!= null` mirrors the SDK's `??`: an explicit `null` config falls back to the chat's.\n if (operationName !== 'chat' || params?.config != null || !context || typeof context !== 'object') {\n return params;\n }\n\n const chatConfig = (context as Record<string, unknown>).config;\n if (!chatConfig || typeof chatConfig !== 'object') {\n return params;\n }\n\n return { ...params, config: chatConfig };\n}\n\n/**\n * Reads the caller's `config.abortSignal` from params resolved by `resolveChatParams`.\n */\nexport function getAbortSignal(params: Record<string, unknown> | undefined): AbortSignal | undefined {\n return (params?.config as { abortSignal?: AbortSignal } | undefined)?.abortSignal;\n}\n\n/** `decisions.create` takes its abort signal in its request options, not in a `config`. */\nexport function getCallAbortSignal(\n operationName: string,\n params: Record<string, unknown> | undefined,\n requestOptions: unknown,\n): AbortSignal | undefined {\n return operationName === 'decide' ? getRequestSignal(requestOptions) : getAbortSignal(params);\n}\n\n/**\n * Instrument any async or synchronous genai method with Sentry spans\n * Handles operations like models.generateContent and chat.sendMessage and chats.create\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: GoogleGenAIOptions,\n): (...args: T) => R | Promise<R> {\n const isEmbeddings = instrumentedMethod.operation === 'embeddings';\n\n return new Proxy(originalMethod, {\n apply(target, _, args: T): R | Promise<R> {\n const operationName = instrumentedMethod.operation || 'unknown';\n const params = args[0] as Record<string, unknown> | undefined;\n const call: GoogleGenAICallInfo = { operation: operationName, request: params };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n const attributeParams = resolveChatParams(operationName, params, context);\n const abortSignal = getCallAbortSignal(operationName, attributeParams, args[1]);\n const requestAttributes = extractRequestAttributes(operationName, attributeParams, context, recordInputs);\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 spanName =\n (typeof model === 'string' && model !== 'unknown') || !(client && hasSpanStreamingEnabled(client))\n ? `${operationName} ${model}`\n : operationName;\n\n // Check if this is a streaming method\n if (instrumentedMethod.streaming) {\n // Use startSpanManual for streaming methods to control span lifecycle\n return startSpanManual(\n {\n name: spanName,\n op: getGenAiSpanOp(operationName),\n attributes: requestAttributes,\n },\n async (span: Span) => {\n try {\n if (recordInputs && attributeParams) {\n addPrivateRequestAttributes(span, attributeParams, operationName);\n }\n runGenAiSpanStart(options, span, call);\n const stream = await target.apply(context, args);\n return instrumentStream(stream, span, recordOutputs, abortSignal, result =>\n runGenAiSpanEnd(options, span, call, result),\n ) as R;\n } catch (error) {\n span.setStatus(getErrorStatus(abortSignal));\n runGenAiSpanEnd(options, span, call, { error });\n span.end();\n throw error;\n }\n },\n );\n }\n // Single span for both sync and async operations\n return startSpan(\n {\n name: spanName,\n op: getGenAiSpanOp(operationName),\n attributes: requestAttributes,\n },\n (span: Span) => {\n if (recordInputs && attributeParams) {\n addPrivateRequestAttributes(span, attributeParams, operationName);\n }\n runGenAiSpanStart(options, span, call);\n\n // The rejection is rethrown to the caller. `startSpan` keeps the status set here.\n return handleCallbackErrors(\n () => target.apply(context, args),\n error => {\n span.setStatus(getErrorStatus(abortSignal));\n runGenAiSpanEnd(options, span, call, { error });\n },\n () => {},\n result => {\n // Only add response attributes for content-producing methods, not for embeddings\n if (!isEmbeddings) {\n addResponseAttributes(span, result, recordOutputs, operationName);\n }\n runGenAiSpanEnd(options, span, call, { response: result });\n },\n );\n },\n );\n },\n });\n}\n\n/**\n * Create a deep proxy for Google GenAI client instrumentation\n * Recursively instruments methods and handles special cases like chats.create\n */\nfunction createDeepProxy<T extends object>(target: T, currentPath = '', options: GoogleGenAIOptions): T {\n const propertyCache = new Map<PropertyKey, { original: unknown; wrapped: unknown }>();\n\n return new Proxy(target, {\n get: (t, prop, receiver) => {\n const value = Reflect.get(t, prop, receiver);\n const cachedEntry = propertyCache.get(prop);\n if (cachedEntry) {\n if (cachedEntry.original === value) {\n return cachedEntry.wrapped;\n }\n propertyCache.delete(prop);\n }\n\n const methodPath = buildMethodPath(currentPath, String(prop));\n\n const instrumentedMethod: InstrumentedMethodEntry | undefined =\n GOOGLE_GENAI_METHOD_REGISTRY[methodPath as keyof typeof GOOGLE_GENAI_METHOD_REGISTRY];\n if (typeof value === 'function' && instrumentedMethod) {\n // If an operation is specified, we need to instrument the method itself\n const wrappedMethod = instrumentedMethod.operation\n ? instrumentMethod(value as (...args: unknown[]) => unknown, methodPath, instrumentedMethod, t, options)\n : value.bind(t);\n\n if (!instrumentedMethod.proxyResultPath) {\n propertyCache.set(prop, { original: value, wrapped: wrappedMethod });\n return wrappedMethod;\n }\n\n // If a proxyResultPath is specified, we need to proxy the result of the method.\n // Note: This currently only properly handles synchronous methods. For async methods,\n // the Promise itself would be proxied instead of the resolved value. Currently we\n // don't have a case where this is needed, so I'll keep it simple for now.\n const methodWithProxiedResult = function (...args: unknown[]): unknown {\n const result = wrappedMethod(...args);\n if (result && typeof result === 'object') {\n return createDeepProxy(result as object, instrumentedMethod.proxyResultPath, options);\n }\n return result;\n };\n propertyCache.set(prop, { original: value, wrapped: methodWithProxiedResult });\n return methodWithProxiedResult;\n }\n\n if (typeof value === 'function') {\n // Bind non-instrumented functions to preserve the original `this` context\n const boundMethod = value.bind(t);\n propertyCache.set(prop, { original: value, wrapped: boundMethod });\n return boundMethod;\n }\n\n if (value && typeof value === 'object') {\n const nestedProxy = createDeepProxy(value, methodPath, options);\n propertyCache.set(prop, { original: value, wrapped: nestedProxy });\n return nestedProxy;\n }\n\n return value;\n },\n });\n}\n\n/**\n * Instrument a Google GenAI 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 client object\n * @param client - The Google GenAI 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 *\n * @example\n * ```typescript\n * import { GoogleGenAI } from '@google/genai';\n * import { instrumentGoogleGenAIClient } from '@sentry/node';\n *\n * const genAI = new GoogleGenAI({ apiKey: process.env.GOOGLE_GENAI_API_KEY });\n * const instrumentedClient = instrumentGoogleGenAIClient(genAI);\n *\n * // Now both chats.create and sendMessage will be instrumented\n * const chat = instrumentedClient.chats.create({ model: 'gemini-1.5-pro' });\n * const response = await chat.sendMessage({ message: 'Hello' });\n * ```\n */\nexport function instrumentGoogleGenAIClient<T extends object>(client: T, options?: GoogleGenAIOptions): T {\n return createDeepProxy(client, '', options ?? {});\n}\n","import type { InstrumentedMethodRegistry } from '../core/utils';\n\nexport const MISTRAL_INTEGRATION_NAME = 'Mistral' as const;\n\n// Matches the value `inferSystemFromInstance` reports for `@langchain/mistralai`, so a call recorded\n// through LangChain and a call recorded here carry the same provider.\nexport const MISTRAL_PROVIDER_NAME = 'mistralai' as const;\n\nexport const MISTRAL_ORIGIN = 'auto.ai.mistralai' as const;\n\n// https://docs.mistral.ai/api/\n// `*.stream` methods are intrinsically streaming (no `stream: true` param), so they are flagged here.\n// `parse`/`parseStream` are the structured-output entry points; they call the underlying request\n// functions directly rather than `this.complete`/`this.stream`, so they need their own entries and\n// cannot produce a duplicate span.\nexport const MISTRAL_METHOD_REGISTRY = {\n 'chat.complete': { operation: 'chat' },\n 'chat.stream': { operation: 'chat', streaming: true },\n 'chat.parse': { operation: 'chat' },\n 'chat.parseStream': { operation: 'chat', streaming: true },\n 'embeddings.create': { operation: 'embeddings' },\n 'agents.complete': { operation: 'invoke_agent' },\n 'agents.stream': { operation: 'invoke_agent', streaming: true },\n} as const satisfies InstrumentedMethodRegistry;\n","/* eslint-disable typescript-eslint/no-deprecated */\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport type { GenAiOutputMessage } from '../core/utils';\nimport { setOutputMessagesAttribute } from '../core/utils';\nimport {\n GEN_AI_REQUEST_FREQUENCY_PENALTY,\n GEN_AI_REQUEST_MAX_TOKENS,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_REQUEST_PRESENCE_PENALTY,\n GEN_AI_REQUEST_SEED,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_REQUEST_TOP_P,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n} from '@sentry/conventions/attributes';\n\n/**\n * Turn a Mistral message content (string or content-chunk array) into a plain string.\n */\nexport function contentToString(content: unknown): string {\n if (typeof content === 'string') {\n return content;\n }\n if (Array.isArray(content)) {\n return content\n .map(part =>\n part && typeof part === 'object' && typeof (part as { text?: unknown }).text === 'string'\n ? (part as { text: string }).text\n : '',\n )\n .join('');\n }\n return '';\n}\n\n/**\n * Build the span name for an instrumented Mistral call. Agent ids and a missing model are left out\n * to keep the name low cardinality.\n */\nexport function getSpanName(operationName: string, attributes: Record<string, unknown>): string {\n const model = attributes[GEN_AI_REQUEST_MODEL];\n\n if (operationName === 'invoke_agent' || typeof model !== 'string') {\n return operationName;\n }\n\n return `${operationName} ${model}`;\n}\n\n/**\n * Reads the caller's signal from Mistral's request options. The SDK spreads `options` over\n * `options.fetchOptions`, so a top-level `signal` wins.\n */\nexport function getMistralRequestSignal(requestOptions: unknown): AbortSignal | undefined {\n const options = requestOptions as { signal?: AbortSignal; fetchOptions?: { signal?: AbortSignal } } | undefined;\n return options?.signal ?? options?.fetchOptions?.signal;\n}\n\n/**\n * Extract request parameters. Mistral request fields are camelCase.\n */\nexport function extractRequestParameters(params: Record<string, unknown>): Record<string, unknown> {\n const attributes: Record<string, unknown> = {};\n\n if (params.model != null) attributes[GEN_AI_REQUEST_MODEL] = params.model;\n if ('temperature' in params) attributes[GEN_AI_REQUEST_TEMPERATURE] = params.temperature;\n if ('topP' in params) attributes[GEN_AI_REQUEST_TOP_P] = params.topP;\n if ('maxTokens' in params) attributes[GEN_AI_REQUEST_MAX_TOKENS] = params.maxTokens;\n if ('frequencyPenalty' in params) attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY] = params.frequencyPenalty;\n if ('presencePenalty' in params) attributes[GEN_AI_REQUEST_PRESENCE_PENALTY] = params.presencePenalty;\n if ('randomSeed' in params) attributes[GEN_AI_REQUEST_SEED] = params.randomSeed;\n\n return attributes;\n}\n\n/**\n * Add response attributes to a span using duck-typing. Mistral responses are camelCase\n * (`choices[].message`, `usage.promptTokens`), matching the SDK's deserialized objects.\n */\nexport function addResponseAttributes(span: Span, result: unknown, recordOutputs?: boolean): void {\n if (!result || typeof result !== 'object') return;\n\n const response = result as Record<string, unknown>;\n const attrs: Record<string, SpanAttributeValue> = {};\n\n if (typeof response.id === 'string') {\n attrs[GEN_AI_RESPONSE_ID] = response.id;\n }\n\n if (typeof response.model === 'string') {\n attrs[GEN_AI_RESPONSE_MODEL] = response.model;\n }\n\n if (response.usage && typeof response.usage === 'object') {\n const usage = response.usage as Record<string, unknown>;\n if (typeof usage.promptTokens === 'number') attrs[GEN_AI_USAGE_INPUT_TOKENS] = usage.promptTokens;\n if (typeof usage.completionTokens === 'number') attrs[GEN_AI_USAGE_OUTPUT_TOKENS] = usage.completionTokens;\n if (typeof usage.totalTokens === 'number') attrs[GEN_AI_USAGE_TOTAL_TOKENS] = usage.totalTokens;\n }\n\n let outputMessages: GenAiOutputMessage[] = [];\n\n if (Array.isArray(response.choices)) {\n const choices = response.choices as Array<Record<string, unknown>>;\n\n const finishReasons = choices\n .map(choice => choice.finishReason)\n .filter((reason): reason is string => typeof reason === 'string');\n if (finishReasons.length > 0) {\n attrs[GEN_AI_RESPONSE_FINISH_REASONS] = JSON.stringify(finishReasons);\n }\n\n if (recordOutputs) {\n // One entry per choice: Mistral can return several when `n` > 1, and both attributes are\n // specified as arrays of messages rather than one merged blob.\n outputMessages = choices.map(choice => {\n const message = choice.message as Record<string, unknown> | undefined;\n return {\n responseText: contentToString(message?.content),\n toolCalls: Array.isArray(message?.toolCalls) ? message.toolCalls : undefined,\n finishReason: typeof choice.finishReason === 'string' ? choice.finishReason : undefined,\n };\n });\n\n const responseTexts = outputMessages.map(message => message.responseText).filter(Boolean);\n if (responseTexts.length > 0) {\n attrs[GEN_AI_RESPONSE_TEXT] = JSON.stringify(responseTexts);\n }\n\n const toolCalls = outputMessages.flatMap(message => message.toolCalls ?? []);\n if (toolCalls.length > 0) {\n attrs[GEN_AI_RESPONSE_TOOL_CALLS] = JSON.stringify(toolCalls);\n }\n }\n }\n\n span.setAttributes(attrs);\n\n if (recordOutputs) {\n setOutputMessagesAttribute(span, outputMessages);\n }\n}\n","import type { Span } from '@sentry/core';\nimport type { GenAiSpanResult } from '../core/span-hooks';\nimport { endStreamSpan, getErrorStatus, setOutputMessagesAttribute } from '../core/utils';\nimport { recordTimeToFirstChunk } from '../core/time-to-first-chunk';\nimport type { MistralCompletionChunk, MistralToolCall } from './types';\nimport { contentToString } from './utils';\n\n/**\n * State accumulated while consuming a Mistral event stream.\n */\ninterface StreamingState {\n responseTexts: string[];\n finishReasons: string[];\n responseId: string;\n responseModel: string;\n promptTokens: number | undefined;\n completionTokens: number | undefined;\n totalTokens: number | undefined;\n /** Tool calls accumulated by their delta `index`; `function.arguments` arrives fragmented. */\n toolCalls: Record<number, MistralToolCall>;\n}\n\n/** Which drain path owns accumulation. See {@link instrumentEventStream}. */\ntype StreamConsumer = 'iterator' | 'reader';\n\ntype AsyncIterableStream = { [Symbol.asyncIterator]: () => AsyncIterator<unknown> };\n\ninterface StreamReaderLike {\n read: () => Promise<{ done: boolean; value?: unknown }>;\n cancel?: (reason?: unknown) => Promise<unknown>;\n}\n\ninterface ReadableStreamLike {\n getReader?: (...args: unknown[]) => StreamReaderLike;\n cancel?: (reason?: unknown) => Promise<unknown>;\n tee?: () => unknown;\n pipeTo?: (destination: unknown, options?: unknown) => Promise<unknown>;\n pipeThrough?: (transform: unknown, options?: unknown) => unknown;\n}\n\n/** Whether a value can be drained with `for await`. */\nexport function isAsyncIterable(value: unknown): value is AsyncIterableStream {\n return !!value && typeof (value as AsyncIterableStream)[Symbol.asyncIterator] === 'function';\n}\n\nfunction createStreamingState(): StreamingState {\n return {\n responseTexts: [],\n finishReasons: [],\n responseId: '',\n responseModel: '',\n promptTokens: undefined,\n completionTokens: undefined,\n totalTokens: undefined,\n toolCalls: {},\n };\n}\n\nfunction processToolCalls(toolCalls: MistralToolCall[], state: StreamingState): void {\n for (const toolCall of toolCalls) {\n const index = toolCall.index;\n if (index === undefined || !toolCall.function) {\n continue;\n }\n\n const existing = state.toolCalls[index];\n if (!existing) {\n state.toolCalls[index] = {\n ...toolCall,\n function: { name: toolCall.function.name, arguments: toolCall.function.arguments ?? '' },\n };\n } else if (toolCall.function.arguments && existing.function) {\n existing.function.arguments = `${existing.function.arguments}${toolCall.function.arguments}`;\n }\n }\n}\n\nfunction processChunk(chunk: MistralCompletionChunk, state: StreamingState, recordOutputs: boolean): void {\n state.responseId = chunk.id ?? state.responseId;\n state.responseModel = chunk.model ?? state.responseModel;\n\n if (chunk.usage) {\n // Input tokens stay constant across the stream; output tokens are only finalized in the last\n // event, so we overwrite on every event that carries usage to guarantee the totals are set.\n state.promptTokens = chunk.usage.promptTokens;\n state.completionTokens = chunk.usage.completionTokens;\n state.totalTokens = chunk.usage.totalTokens;\n }\n\n for (const choice of chunk.choices ?? []) {\n if (recordOutputs) {\n // Deltas carry either a plain string or the same content-chunk array the non-streaming\n // responses use, so both go through `contentToString`.\n const content = contentToString(choice.delta?.content);\n if (content) {\n state.responseTexts.push(content);\n }\n if (choice.delta?.toolCalls) {\n processToolCalls(choice.delta.toolCalls, state);\n }\n }\n if (choice.finishReason) {\n state.finishReasons.push(choice.finishReason);\n }\n }\n}\n\n/** Mistral yields `CompletionEvent` objects that wrap the chunk under `data`. */\nfunction processEvent(event: unknown, state: StreamingState, recordOutputs: boolean): void {\n const chunk = (event as { data?: MistralCompletionChunk } | undefined)?.data;\n if (chunk && typeof chunk === 'object') {\n processChunk(chunk, state, recordOutputs);\n }\n}\n\nasync function* instrumentIterator(\n iterate: () => AsyncIterator<unknown>,\n state: StreamingState,\n recordOutputs: boolean,\n claim: (consumer: StreamConsumer) => boolean,\n settle: (error?: unknown) => void,\n): AsyncGenerator<unknown, void, unknown> {\n try {\n for await (const event of { [Symbol.asyncIterator]: iterate }) {\n if (claim('iterator')) {\n processEvent(event, state, recordOutputs);\n }\n yield event;\n }\n } catch (error) {\n settle(error);\n throw error;\n } finally {\n settle();\n }\n}\n\nfunction wrapReader(\n reader: StreamReaderLike,\n state: StreamingState,\n recordOutputs: boolean,\n claim: (consumer: StreamConsumer) => boolean,\n settle: (error?: unknown) => void,\n markCancelled: () => void,\n): StreamReaderLike {\n // Captured before the proxy exists so the wrappers below call the real reader, not themselves.\n const originalRead = reader.read;\n const originalCancel = reader.cancel;\n const read = (): Promise<{ done: boolean; value?: unknown }> => originalRead.call(reader);\n const cancel =\n typeof originalCancel === 'function'\n ? (reason?: unknown): Promise<unknown> => originalCancel.call(reader, reason)\n : undefined;\n\n return new Proxy(reader, {\n get(target: StreamReaderLike, prop: string | symbol): unknown {\n if (prop === 'read') {\n return async (): Promise<{ done: boolean; value?: unknown }> => {\n try {\n const result = await read();\n if (result.done) {\n settle();\n } else if (claim('reader')) {\n processEvent(result.value, state, recordOutputs);\n }\n return result;\n } catch (error) {\n settle(error);\n throw error;\n }\n };\n }\n\n if (prop === 'cancel' && cancel) {\n return async (reason?: unknown): Promise<unknown> => {\n markCancelled();\n try {\n return await cancel(reason);\n } finally {\n settle();\n }\n };\n }\n\n const value = Reflect.get(target, prop, target) as unknown;\n return typeof value === 'function' ? value.bind(target) : value;\n },\n });\n}\n\n/**\n * A stream that pulls through `readable`'s instrumented reader.\n *\n * `tee`, `pipeTo` and `pipeThrough` acquire their reader through internal slots rather than by\n * calling the public `getReader`, so patching that method alone leaves them uninstrumented: the\n * chunks bypass accumulation and the span is never ended. Handing them this stream instead routes\n * them back through the wrapped reader, so there is still exactly one accumulating consumer.\n *\n * Same idea as `monitorStream` in `@sentry/deno`, with two deliberate differences: chunks are pulled\n * on demand rather than drained in a `start` loop, so backpressure still reaches the source, and\n * `cancel` is forwarded (the hole #24054 fixed there) so the source stops producing when the\n * consumer disconnects.\n */\nfunction instrumentedSource(readable: ReadableStreamLike): ReadableStream<unknown> {\n // The patched `getReader`, so reads are accumulated and the span is ended by the shared logic.\n // oxlint-disable-next-line typescript/no-non-null-assertion -- only called when `getReader` is a function\n const reader = readable.getReader!();\n\n return new ReadableStream({\n async pull(controller) {\n const { done, value } = await reader.read();\n if (done) {\n controller.close();\n return;\n }\n controller.enqueue(value);\n },\n async cancel(reason) {\n await reader.cancel?.(reason);\n },\n });\n}\n\n/**\n * Instrument a Mistral event stream in place: accumulate response attributes as it is drained and\n * end `span` when it finishes.\n *\n * The stream is patched rather than replaced because `EventStream` extends `ReadableStream`, so\n * handing back a bare async generator would drop `getReader`, `tee`, `pipeTo` and the rest of the\n * `ReadableStream` API the caller is entitled to.\n *\n * Both `for await` and `getReader()` are valid ways to drain a `ReadableStream`, and the SDK's\n * iterator polyfill reads through `getReader()`, so both are wrapped. The first path to see a chunk\n * claims accumulation and the other stays a pass-through, which keeps a chunk from being counted\n * twice when one path drives the other.\n *\n * Returns `false` for a value that is not a stream, leaving it untouched.\n */\nexport function instrumentEventStream(\n stream: unknown,\n span: Span,\n recordOutputs: boolean,\n abortSignal?: AbortSignal,\n beforeSpanEnd?: (result: GenAiSpanResult<never>) => void,\n): boolean {\n if (!isAsyncIterable(stream)) {\n return false;\n }\n\n const state = createStreamingState();\n let consumer: StreamConsumer | undefined;\n let settled = false;\n let cancelled = false;\n\n // Called for each received event.\n const claim = (candidate: StreamConsumer): boolean => {\n recordTimeToFirstChunk(span);\n consumer ??= candidate;\n return consumer === candidate;\n };\n\n // Set synchronously when the caller asks to cancel, before the underlying cancel is awaited.\n // Cancelling can reject an in-flight `read()` (it aborts the HTTP body the stream reads from), and\n // that rejection would otherwise reach `settle` first and record a deliberate abort as a failure.\n const markCancelled = (): void => {\n cancelled = true;\n };\n\n const settle = (error?: unknown): void => {\n if (settled) {\n return;\n }\n settled = true;\n if (error !== undefined && !cancelled) {\n span.setStatus(getErrorStatus(abortSignal));\n }\n\n const toolCalls = Object.values(state.toolCalls);\n\n if (recordOutputs) {\n // Set the authoritative `gen_ai.output.messages` alongside the deprecated response attributes\n // `endStreamSpan` writes, so tool calls survive Relay's lossy migration. A stream is a single\n // assistant turn, so the accumulated fragments make up one message.\n setOutputMessagesAttribute(span, {\n responseText: state.responseTexts.join(''),\n toolCalls,\n finishReason: state.finishReasons[0],\n });\n }\n\n endStreamSpan(span, { ...state, toolCalls }, recordOutputs, () =>\n beforeSpanEnd?.(error !== undefined && !cancelled ? { error } : {}),\n );\n };\n\n const iterate = stream[Symbol.asyncIterator].bind(stream);\n const instrumented = instrumentIterator(iterate, state, recordOutputs, claim, settle);\n stream[Symbol.asyncIterator] = () => instrumented;\n\n const readable = stream as ReadableStreamLike;\n\n if (typeof readable.getReader === 'function') {\n const getReader = readable.getReader.bind(readable);\n readable.getReader = (...args: unknown[]) =>\n wrapReader(getReader(...args), state, recordOutputs, claim, settle, markCancelled);\n }\n\n if (typeof readable.cancel === 'function') {\n const cancel = readable.cancel.bind(readable);\n readable.cancel = async (reason?: unknown): Promise<unknown> => {\n markCancelled();\n try {\n return await cancel(reason);\n } finally {\n settle();\n }\n };\n }\n\n // Only patched when `getReader` is present, since that is what `instrumentedSource` pulls through.\n if (typeof readable.getReader === 'function') {\n if (typeof readable.tee === 'function') {\n readable.tee = () => instrumentedSource(readable).tee();\n }\n\n if (typeof readable.pipeTo === 'function') {\n readable.pipeTo = (destination: unknown, options?: unknown) =>\n instrumentedSource(readable).pipeTo(destination as WritableStream<unknown>, options as StreamPipeOptions);\n }\n\n if (typeof readable.pipeThrough === 'function') {\n readable.pipeThrough = (transform: unknown, options?: unknown) =>\n instrumentedSource(readable).pipeThrough(\n transform as ReadableWritablePair<unknown, unknown>,\n options as StreamPipeOptions,\n );\n }\n }\n\n return true;\n}\n","import { startSpan, startSpanManual, stringify } from '@sentry/core';\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_AGENT_NAME,\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_TOOL_DEFINITIONS,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { InstrumentedMethodEntry } from '../core/utils';\nimport {\n buildMethodPath,\n extractSystemInstructions,\n getErrorStatus,\n getGenAiSpanOp,\n resolveGenAiCallRecording,\n wrapPromiseWithMethods,\n} from '../core/utils';\nimport { GEN_AI_REQUEST_STREAM_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport { MISTRAL_METHOD_REGISTRY, MISTRAL_ORIGIN, MISTRAL_PROVIDER_NAME } from './constants';\nimport { instrumentEventStream } from './streaming';\nimport type { MistralCallInfo, MistralOptions } from './types';\nimport { addResponseAttributes, extractRequestParameters, getMistralRequestSignal, getSpanName } from './utils';\n\n/**\n * Serialize tool definitions from request parameters, if present.\n */\nfunction extractToolDefinitions(params: Record<string, unknown>): string | undefined {\n if (!Array.isArray(params.tools) || params.tools.length === 0) {\n return undefined;\n }\n return stringify(params.tools);\n}\n\n/**\n * Extract request attributes from method arguments.\n *\n * `streaming` comes from the called method, not the request: v2 streams only through the dedicated\n * `*.stream` methods, and their `stream` request field is optional, so a params-derived value would\n * be missing on most streaming calls.\n */\nexport function extractRequestAttributes(\n args: unknown[],\n operationName: string,\n recordInputs: boolean,\n streaming: boolean,\n): Record<string, unknown> {\n const attributes: Record<string, unknown> = {\n [GEN_AI_PROVIDER_NAME]: MISTRAL_PROVIDER_NAME,\n [GEN_AI_OPERATION_NAME]: operationName,\n [SENTRY_ORIGIN]: MISTRAL_ORIGIN,\n [GEN_AI_REQUEST_STREAM_ATTRIBUTE]: streaming,\n };\n\n if (args.length > 0 && typeof args[0] === 'object' && args[0] !== null) {\n const params = args[0] as Record<string, unknown>;\n\n if (operationName === 'invoke_agent' && typeof params.agentId === 'string') {\n attributes[GEN_AI_AGENT_NAME] = params.agentId;\n }\n\n const tools = recordInputs ? extractToolDefinitions(params) : undefined;\n if (tools) {\n attributes[GEN_AI_TOOL_DEFINITIONS] = tools;\n }\n\n Object.assign(attributes, extractRequestParameters(params));\n }\n\n return attributes;\n}\n\n/**\n * Record AI request inputs on the span, if recording is enabled.\n */\nexport function addRequestAttributes(span: Span, params: Record<string, unknown>, operationName: string): void {\n if (operationName === 'embeddings') {\n const input = params.inputs;\n if (input == null || (typeof input === 'string' && input.length === 0) || (Array.isArray(input) && !input.length)) {\n return;\n }\n span.setAttribute(GEN_AI_EMBEDDINGS_INPUT, stringify(input, String));\n return;\n }\n\n const src = 'messages' in params ? params.messages : undefined;\n if (!src || (Array.isArray(src) && src.length === 0)) {\n return;\n }\n\n const { systemInstructions, filteredMessages } = extractSystemInstructions(src);\n if (systemInstructions) {\n span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS, systemInstructions);\n }\n span.setAttribute(GEN_AI_INPUT_MESSAGES, stringify(filteredMessages));\n}\n\n/**\n * Instrument a single Mistral SDK method with a gen_ai span.\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) => Promise<R>,\n instrumentedMethod: InstrumentedMethodEntry,\n context: unknown,\n options: MistralOptions,\n): (...args: T) => Promise<R> {\n return function instrumentedCall(...args: T): Promise<R> {\n const operationName = instrumentedMethod.operation || 'unknown';\n const isStreamRequested = !!instrumentedMethod.streaming;\n const params = args[0] as Record<string, unknown> | undefined;\n const abortSignal = getMistralRequestSignal(args[1]);\n const call: MistralCallInfo = { operation: operationName, request: params };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n const requestAttributes = extractRequestAttributes(args, operationName, recordInputs, isStreamRequested);\n\n const spanConfig = {\n name: getSpanName(operationName, requestAttributes),\n op: getGenAiSpanOp(operationName),\n attributes: requestAttributes as Record<string, SpanAttributeValue>,\n };\n\n if (isStreamRequested) {\n let originalResult!: Promise<R>;\n\n const instrumentedPromise = startSpanManual(spanConfig, (span: Span) => {\n originalResult = originalMethod.apply(context, args);\n\n if (recordInputs && params) {\n addRequestAttributes(span, params, operationName);\n }\n runGenAiSpanStart(options, span, call);\n\n return originalResult.then(\n result => {\n // Patched in place so the caller keeps the real `EventStream`; `instrumentEventStream`\n // takes over ending the span once the stream is drained.\n const isStream = instrumentEventStream(result, span, recordOutputs, abortSignal, streamResult =>\n runGenAiSpanEnd(options, span, call, streamResult),\n );\n if (!isStream) {\n runGenAiSpanEnd(options, span, call, { response: result });\n span.end();\n }\n return result;\n },\n error => {\n span.setStatus(getErrorStatus(abortSignal));\n runGenAiSpanEnd(options, span, call, { error });\n span.end();\n throw error;\n },\n );\n });\n\n return wrapPromiseWithMethods(originalResult, instrumentedPromise);\n }\n\n let originalResult!: Promise<R>;\n\n const instrumentedPromise = startSpan(spanConfig, (span: Span) => {\n originalResult = originalMethod.apply(context, args);\n\n if (recordInputs && params) {\n addRequestAttributes(span, params, operationName);\n }\n runGenAiSpanStart(options, span, call);\n\n return originalResult.then(\n result => {\n addResponseAttributes(span, result, 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 * Create a deep proxy for Mistral client instrumentation.\n */\nfunction createDeepProxy<T extends object>(target: T, currentPath = '', options: MistralOptions): T {\n return new Proxy(target, {\n get(obj: object, prop: string): unknown {\n const value = (obj as Record<string, unknown>)[prop];\n const methodPath = buildMethodPath(currentPath, String(prop));\n\n const instrumentedMethod = MISTRAL_METHOD_REGISTRY[methodPath as keyof typeof MISTRAL_METHOD_REGISTRY];\n if (typeof value === 'function' && instrumentedMethod) {\n return instrumentMethod(value as (...args: unknown[]) => Promise<unknown>, instrumentedMethod, obj, options);\n }\n\n if (typeof value === 'function') {\n // Preserve the original `this` for uninstrumented methods (private class fields).\n return value.bind(obj);\n }\n\n if (value && typeof value === 'object') {\n return createDeepProxy(value, methodPath, options);\n }\n\n return value;\n },\n }) as T;\n}\n\n/**\n * Instrument a Mistral client with Sentry tracing.\n * Can be used across Node.js, Cloudflare Workers, and Vercel Edge.\n */\nexport function instrumentMistralAiClient<T extends object>(client: T, options?: MistralOptions): T {\n return createDeepProxy(client, '', options ?? {});\n}\n","export const TYPESAFE_INTEGRATION_NAME = 'TypeSafe' as const;\n\nexport const TYPESAFE_PROVIDER_NAME = 'typesafe' as const;\n\nexport const TYPESAFE_ORIGIN = 'auto.ai.typesafe' as const;\n","import {\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_OUTPUT_MESSAGES,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_DECIDE } from '@sentry/conventions/op';\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport { isObjectLike, SPAN_STATUS_ERROR, startInactiveSpan, withActiveSpan } from '@sentry/core';\nimport type { GenAiSpanHooks } from '../core/span-hooks';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { GenAiCallOptions } from '../core/utils';\nimport { getEvaluationInputMessages, getEvaluationOutputMessages, resolveGenAiCallRecording } from '../core/utils';\nimport { TYPESAFE_ORIGIN, TYPESAFE_PROVIDER_NAME } from './constants';\n\n/** The call that `recordInputs`/`recordOutputs` decide on, and that the span hooks get. */\nexport interface TypeSafeCallInfo {\n /** The request, the first argument of `systemOne` as passed. */\n request: unknown;\n}\n\n/** Options for the TypeSafe integration. `onSpanEnd` gets the parsed `systemOne` result. */\nexport type TypeSafeOptions = GenAiCallOptions<TypeSafeCallInfo> & GenAiSpanHooks<TypeSafeCallInfo>;\n\n/**\n * Start the span for a `systemOne(request)` call. The request model falls back to the client's\n * `defaultModel`, the same way the SDK resolves it.\n */\nexport function startDecideSpan(\n request: unknown,\n client: unknown,\n recordInputs: boolean,\n attributes?: SpanAttributes,\n): Span {\n const params = isObjectLike(request) ? request : {};\n const defaultModel = isObjectLike(client) ? client.defaultModel : undefined;\n const model =\n typeof params.model === 'string' ? params.model : typeof defaultModel === 'string' ? defaultModel : undefined;\n\n return startInactiveSpan({\n name: model ? `decide ${model}` : 'decide',\n // oxlint-disable-next-line typescript/no-deprecated -- the rename to `gen_ai.decide` comes in a follow-up\n op: GEN_AI_DECIDE,\n // Extra attributes (e.g. another integration's origin) are set at start, so samplers see them.\n attributes: { ...getRequestAttributes(params, model, recordInputs), ...attributes },\n });\n}\n\nfunction getRequestAttributes(\n request: Record<string, unknown>,\n model: string | undefined,\n recordInputs: boolean,\n): SpanAttributes {\n return {\n [SENTRY_ORIGIN]: TYPESAFE_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'decide',\n [GEN_AI_PROVIDER_NAME]: TYPESAFE_PROVIDER_NAME,\n [GEN_AI_REQUEST_MODEL]: model,\n ...(recordInputs ? { [GEN_AI_INPUT_MESSAGES]: getEvaluationInputMessages(request) } : {}),\n };\n}\n\n/**\n * Add the response model, token usage and (optionally) the answers of a `systemOne` result.\n * Also used for TypeSafe models on Workers AI.\n */\nexport function addResponseAttributes(span: Span, result: unknown, recordOutputs: boolean): void {\n if (!isObjectLike(result)) {\n return;\n }\n\n if (typeof result.model === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, result.model);\n }\n\n const usage = isObjectLike(result.usage) ? result.usage : undefined;\n const inputTokens = typeof usage?.input_tokens === 'number' ? usage.input_tokens : undefined;\n const outputTokens = typeof usage?.output_tokens === 'number' ? usage.output_tokens : undefined;\n if (inputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, inputTokens);\n }\n if (outputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, outputTokens);\n }\n if (inputTokens !== undefined && outputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, inputTokens + outputTokens);\n }\n\n if (recordOutputs && result.answers !== undefined) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, getEvaluationOutputMessages(result.answers));\n }\n}\n\n/**\n * `systemOne` returns a lazy `APIPromise` before the request settles, and parses the body on the first\n * `.then()`. Wait on `asResponse()` (the raw fetch, which does not parse the body) and read a clone of\n * the body, so the caller's own parse is unaffected. Call this before the caller can await the result,\n * so the clone is taken first. Returns `false` when `result` is not an `APIPromise`.\n */\nexport function onSystemOneResponse(\n result: unknown,\n onBody: (body: unknown) => void,\n onError: (error: unknown) => void,\n): boolean {\n if (!isObjectLike(result) || typeof result.asResponse !== 'function') {\n return false;\n }\n\n (result.asResponse() as Promise<Response>).then(\n response =>\n response\n .clone()\n .json()\n .then(\n body => onBody(body),\n () => onBody(undefined),\n ),\n error => onError(error),\n );\n\n return true;\n}\n\n/**\n * Instrument a TypeSafe client (`@typesafe-ai/sdk`) with Sentry tracing.\n */\nexport function instrumentTypeSafeClient<T extends object>(client: T, options?: TypeSafeOptions): T {\n return new Proxy(client, {\n get(target, prop) {\n // Read with the real client as receiver: the SDK keeps its API key in a private class field.\n const value: unknown = Reflect.get(target, prop, target);\n if (typeof value !== 'function') {\n return value;\n }\n if (prop === 'systemOne') {\n return (...args: unknown[]) =>\n instrumentSystemOne(value as (...args: unknown[]) => unknown, target, args, options ?? {});\n }\n return value.bind(target);\n },\n });\n}\n\nfunction instrumentSystemOne(\n systemOne: (...args: unknown[]) => unknown,\n client: object,\n args: unknown[],\n options: TypeSafeOptions,\n): unknown {\n const call: TypeSafeCallInfo = { request: args[0] };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n const span = startDecideSpan(args[0], client, recordInputs);\n runGenAiSpanStart(options, span, call);\n const endWithError = (error: unknown): void => {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n runGenAiSpanEnd(options, span, call, { error });\n span.end();\n };\n\n let result: unknown;\n try {\n result = withActiveSpan(span, () => systemOne.apply(client, args));\n } catch (error) {\n endWithError(error);\n throw error;\n }\n\n const waiting = onSystemOneResponse(\n result,\n body => {\n addResponseAttributes(span, body, recordOutputs);\n runGenAiSpanEnd(options, span, call, { response: body });\n span.end();\n },\n endWithError,\n );\n if (!waiting) {\n runGenAiSpanEnd(options, span, call, { response: result });\n span.end();\n }\n\n return result;\n}\n","export const PI_AI_INTEGRATION_NAME = 'PiAi' as const;\n\nexport const PI_AI_ORIGIN = 'auto.ai.pi_ai';\n","import { SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { _INTERNAL_shouldSkipAiProviderWrapping, getActiveSpan, spanToJSON } from '@sentry/core';\nimport { PI_AI_ORIGIN } from './constants';\n\n/**\n * Whether the active span is a pi-ai `chat` span, which means a provider SDK call being made is pi-ai\n * sending its request.\n */\nexport function isInsidePiAiSpan(): boolean {\n const span = getActiveSpan();\n return !!span && spanToJSON(span).attributes[SENTRY_ORIGIN] === PI_AI_ORIGIN;\n}\n\n/**\n * Whether a provider integration should leave a call alone, because the integration driving the SDK\n * reports it. LangChain and Vercel AI mark the providers they drive as skipped; pi-ai is detected per\n * request, by its active span.\n */\nexport function shouldSkipAiProviderSpan(integrationName: string): boolean {\n return _INTERNAL_shouldSkipAiProviderWrapping(integrationName) || isInsidePiAiSpan();\n}\n","/**\n * The provider value for the `gen_ai.provider.name` attribute.\n * @see https://developers.cloudflare.com/workers-ai/\n */\nexport const WORKERS_AI_PROVIDER_NAME = 'cloudflare.workers_ai';\n\n/**\n * The Sentry origin for spans created by the Workers AI instrumentation.\n */\nexport const WORKERS_AI_ORIGIN = 'auto.ai.cloudflare.workers_ai';\n\n/**\n * The key used to register this provider in the AI provider skip registry.\n *\n * @see `_INTERNAL_skipAiProviderWrapping`\n */\nexport const WORKERS_AI_INTEGRATION_NAME = 'WorkersAI' as const;\n","/* eslint-disable typescript-eslint/no-deprecated */\nimport {\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_OUTPUT_MESSAGES,\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_PRESENCE_PENALTY,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_REQUEST_TOP_K,\n GEN_AI_REQUEST_TOP_P,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_CHAT, GEN_AI_EMBEDDINGS, GEN_AI_DECIDE, GEN_AI_EXTRACT } from '@sentry/conventions/op';\nimport { isObjectLike, stringify } from '@sentry/core';\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport { GEN_AI_REQUEST_STREAM_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport {\n extractSystemInstructions,\n getEvaluationInputMessages,\n getTokenUsageAttributes,\n setOutputMessagesAttribute,\n} from '../core/utils';\nimport { addResponseAttributes as addDecideResponseAttributes } from '../typesafe';\n// Re-exported so `workers-ai/streaming.ts` keeps importing it from this module.\nexport { setOutputMessagesAttribute };\nimport { WORKERS_AI_ORIGIN, WORKERS_AI_PROVIDER_NAME } from './constants';\nimport type { WorkersAiChoice, WorkersAiInput, WorkersAiOutput } from './types';\n\nexport type WorkersAiOperationName = 'chat' | 'embeddings' | 'decide' | 'extract';\n\nexport const WORKERS_AI_OPERATION_SPAN_OPS: Record<WorkersAiOperationName, string> = {\n chat: GEN_AI_CHAT,\n embeddings: GEN_AI_EMBEDDINGS,\n decide: GEN_AI_DECIDE,\n extract: GEN_AI_EXTRACT,\n};\n\n/**\n * Model ID prefixes of the evaluation models (TypeSafe Jev and Cloudflare Clef), traced as `decide` spans.\n */\nconst DECIDE_MODEL_PREFIXES = ['typesafe/jev', '@cf/cloudflare/clef'];\n\n/**\n * Model ID prefixes of the field extraction models (Cloudflare Clairic), traced as `extract` spans.\n */\nconst EXTRACT_MODEL_PREFIXES = ['@cf/cloudflare/clairic'];\n\nconst BLOB_SUBSTITUTE = '[Blob substitute]';\n\n/**\n * Determine the gen_ai operation name from the model and inputs passed to `AI.run`.\n * Workers AI exposes a single `run` method, so we infer the operation from the model ID and the input shape.\n */\nexport function getOperationName(model: unknown, inputs: unknown): WorkersAiOperationName {\n if (typeof model === 'string' && DECIDE_MODEL_PREFIXES.some(prefix => model.startsWith(prefix))) {\n return 'decide';\n }\n if (typeof model === 'string' && EXTRACT_MODEL_PREFIXES.some(prefix => model.startsWith(prefix))) {\n return 'extract';\n }\n if (inputs && typeof inputs === 'object') {\n if ('messages' in inputs || 'prompt' in inputs) {\n return 'chat';\n }\n if ('text' in inputs) {\n return 'embeddings';\n }\n }\n return 'chat';\n}\n\n/**\n * Extract the request attributes (model, request parameters, system, origin) from a `run` call.\n */\nexport function extractRequestAttributes(\n model: unknown,\n inputs: unknown,\n operationName: string,\n): Record<string, SpanAttributeValue> {\n const attributes: Record<string, SpanAttributeValue> = {\n [GEN_AI_PROVIDER_NAME]: WORKERS_AI_PROVIDER_NAME,\n [GEN_AI_OPERATION_NAME]: operationName,\n [SENTRY_ORIGIN]: WORKERS_AI_ORIGIN,\n [GEN_AI_REQUEST_MODEL]: typeof model === 'string' ? model : 'unknown',\n };\n\n if (inputs && typeof inputs === 'object') {\n const params = inputs as WorkersAiInput;\n\n if (typeof params.temperature === 'number') {\n attributes[GEN_AI_REQUEST_TEMPERATURE] = params.temperature;\n }\n if (typeof params.max_tokens === 'number') {\n attributes[GEN_AI_REQUEST_MAX_TOKENS] = params.max_tokens;\n }\n if (typeof params.top_p === 'number') {\n attributes[GEN_AI_REQUEST_TOP_P] = params.top_p;\n }\n if (typeof params.top_k === 'number') {\n attributes[GEN_AI_REQUEST_TOP_K] = params.top_k;\n }\n if (typeof params.frequency_penalty === 'number') {\n attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY] = params.frequency_penalty;\n }\n if (typeof params.presence_penalty === 'number') {\n attributes[GEN_AI_REQUEST_PRESENCE_PENALTY] = params.presence_penalty;\n }\n if (params.stream === true) {\n attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE] = true;\n }\n }\n\n return attributes;\n}\n\n/**\n * Record the request inputs (messages/prompt/embeddings input) on the span.\n * Only called when `recordInputs` is enabled.\n */\nexport function addRequestAttributes(span: Span, inputs: unknown, operationName: string): void {\n if (!inputs || typeof inputs !== 'object') {\n return;\n }\n const params = inputs as WorkersAiInput;\n\n if (operationName === 'decide') {\n span.setAttribute(GEN_AI_INPUT_MESSAGES, getEvaluationInputMessages(inputs as Record<string, unknown>));\n return;\n }\n\n if (operationName === 'extract') {\n // Record the request body as passed, but never the image data.\n const { model: _model, ...request } = inputs as Record<string, unknown>;\n if (Array.isArray(request.images)) {\n request.images = request.images.map(() => BLOB_SUBSTITUTE);\n }\n span.setAttribute(GEN_AI_INPUT_MESSAGES, stringify([request]));\n return;\n }\n\n // Store embeddings input on a separate attribute\n if (operationName === 'embeddings') {\n const text = params.text;\n\n if (text == null || (typeof text === 'string' && text.length === 0) || (Array.isArray(text) && text.length === 0)) {\n return;\n }\n\n span.setAttribute(GEN_AI_EMBEDDINGS_INPUT, stringify(text, String));\n return;\n }\n\n const src = params.messages ?? params.prompt;\n\n if (src == null || (Array.isArray(src) && src.length === 0)) {\n return;\n }\n\n const { systemInstructions, filteredMessages } = extractSystemInstructions(src);\n\n if (systemInstructions) {\n span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS, systemInstructions);\n }\n\n span.setAttribute(GEN_AI_INPUT_MESSAGES, stringify(filteredMessages));\n}\n\n/**\n * Record the response attributes (token usage, response text, tool calls) on the span.\n */\nexport function addResponseAttributes(\n span: Span,\n result: unknown,\n recordOutputs: boolean,\n operationName?: WorkersAiOperationName,\n): void {\n if (operationName === 'decide') {\n // The binding wraps the TypeSafe response as `{ state, result }`, but the docs show it unwrapped.\n const body = isObjectLike(result) && isObjectLike(result.result) ? result.result : result;\n addDecideResponseAttributes(span, body, recordOutputs);\n return;\n }\n\n if (operationName === 'extract') {\n addExtractResponseAttributes(span, result, recordOutputs);\n return;\n }\n\n if (\n !result ||\n typeof result !== 'object' ||\n // Raw `Response` objects (from `returnRawResponse`/`websocket`) cannot be introspected without consuming them.\n (typeof Response !== 'undefined' && result instanceof Response)\n ) {\n return;\n }\n\n const response = result as WorkersAiOutput;\n\n if (response.usage) {\n span.setAttributes(getTokenUsageAttributes(response.usage.prompt_tokens, response.usage.completion_tokens));\n }\n\n if (Array.isArray(response.choices)) {\n if (typeof response.id === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_ID, response.id);\n }\n if (typeof response.model === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, response.model);\n }\n addChoicesResponseAttributes(span, response.choices, recordOutputs);\n return;\n }\n\n if (recordOutputs) {\n let responseText: string | undefined;\n if (typeof response.response === 'string') {\n responseText = response.response;\n span.setAttribute(GEN_AI_RESPONSE_TEXT, response.response);\n } else if (response.response != null) {\n responseText = JSON.stringify(response.response);\n span.setAttribute(GEN_AI_RESPONSE_TEXT, responseText);\n }\n\n const toolCalls =\n Array.isArray(response.tool_calls) && response.tool_calls.length > 0 ? response.tool_calls : undefined;\n if (toolCalls) {\n span.setAttribute(GEN_AI_RESPONSE_TOOL_CALLS, JSON.stringify(toolCalls));\n }\n\n setOutputMessagesAttribute(span, { responseText, toolCalls });\n }\n}\n\nfunction addChoicesResponseAttributes(span: Span, choices: WorkersAiChoice[], recordOutputs: boolean): void {\n const finishReasons = choices\n .map(choice => choice.finish_reason)\n .filter((reason): reason is string => typeof reason === 'string');\n if (finishReasons.length > 0) {\n span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, JSON.stringify(finishReasons));\n }\n\n if (!recordOutputs) {\n return;\n }\n\n const messages = choices.map(({ message, finish_reason }) => ({\n responseText: typeof message?.content === 'string' ? message.content : undefined,\n toolCalls: message?.tool_calls,\n finishReason: typeof finish_reason === 'string' ? finish_reason : undefined,\n }));\n\n setOutputMessagesAttribute(span, messages);\n}\n\nfunction addExtractResponseAttributes(span: Span, body: unknown, recordOutputs: boolean): void {\n if (!isObjectLike(body)) {\n return;\n }\n\n const { model, usage, ...response } = body;\n\n if (typeof model === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, model);\n }\n\n if (isObjectLike(usage)) {\n span.setAttributes(\n getTokenUsageAttributes(\n typeof usage.input_tokens === 'number' ? usage.input_tokens : undefined,\n typeof usage.output_tokens === 'number' ? usage.output_tokens : undefined,\n ),\n );\n }\n\n if (recordOutputs) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, stringify([response]));\n }\n}\n","import type { Span } from '@sentry/core';\nimport type { GenAiSpanResult } from '../core/span-hooks';\nimport { getToolCallKey } from '../core/streaming-tool-calls';\nimport { endStreamSpan, getErrorStatus, type StreamResponseState } from '../core/utils';\nimport { recordTimeToFirstChunk } from '../core/time-to-first-chunk';\nimport type { WorkersAiUsage } from './types';\nimport { setOutputMessagesAttribute } from './utils';\n\ninterface WorkersAiStreamingToolCall {\n index?: number | null;\n id?: string;\n type?: string;\n function?: { name?: string; arguments?: string };\n // Some Workers AI models stream tool calls with the name/arguments at the top\n // level of the tool-call object instead of nested under `function`.\n name?: string;\n arguments?: string;\n}\n\ninterface WorkersAiStreamChunk {\n // Native Workers AI streaming shape (`env.AI.run` with `stream: true`).\n response?: unknown;\n tool_calls?: unknown[];\n // OpenAI-compatible streaming shape emitted for models routed through the\n // OpenAI-compatible endpoint (e.g. via `workers-ai-provider`).\n id?: unknown;\n model?: unknown;\n choices?: Array<{\n delta?: { content?: unknown; tool_calls?: WorkersAiStreamingToolCall[] };\n finish_reason?: unknown;\n }>;\n usage?: WorkersAiUsage & { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number };\n}\n\n/**\n * Tool calls accumulated from a stream, keyed in the order they were opened (so output order is arrival order).\n */\ninterface ToolCallAccumulator {\n calls: Map<string, WorkersAiStreamingToolCall>;\n /** Key of the latest call, which argument fragments with neither `index`, `id` nor name continue. */\n lastKey?: string;\n /** Key of the call currently open for a reported `index`, when a new `id` reused that index. */\n keyByIndex: Map<number, string>;\n}\n\n/**\n * Accumulate a fragmented OpenAI-compatible tool call (delivered across multiple\n * `choices[].delta.tool_calls` chunks) into the accumulator.\n */\nfunction accumulateStreamingToolCalls(toolCalls: WorkersAiStreamingToolCall[], accumulator: ToolCallAccumulator): void {\n for (const toolCall of toolCalls) {\n // Normalize both shapes: name/arguments nested under `function`, or at the top level.\n const name = toolCall.function?.name ?? toolCall.name;\n const args = toolCall.function?.arguments ?? toolCall.arguments;\n\n // A tool call must carry at least a name or argument fragment to be meaningful.\n if (name == null && args == null) {\n continue;\n }\n\n const key = getToolCallKey(toolCall, name, accumulator);\n const existing = accumulator.calls.get(key);\n\n if (!existing) {\n accumulator.calls.set(key, {\n index: toolCall.index,\n id: toolCall.id,\n type: toolCall.type,\n function: {\n name,\n arguments: args ?? '',\n },\n });\n } else if (existing.function) {\n if (name && !existing.function.name) {\n existing.function.name = name;\n }\n if (args) {\n existing.function.arguments = `${existing.function.arguments ?? ''}${args}`;\n }\n }\n accumulator.lastKey = key;\n }\n}\n\n/**\n * Parse a single SSE line (`data: {...}`) and accumulate its data into the streaming state.\n *\n * Handles both the native Workers AI shape (top-level `response`/`tool_calls`) and the\n * OpenAI-compatible shape (`choices[].delta.content`/`choices[].delta.tool_calls`), because\n * the same `run()` call transparently yields either format depending on the model.\n */\nfunction processLine(\n line: string,\n state: StreamResponseState,\n recordOutputs: boolean,\n toolCallAccumulator: ToolCallAccumulator,\n): void {\n const trimmed = line.trim();\n if (!trimmed.startsWith('data:')) {\n return;\n }\n\n const data = trimmed.slice('data:'.length).trim();\n if (!data || data === '[DONE]') {\n return;\n }\n\n let parsed: WorkersAiStreamChunk;\n try {\n parsed = JSON.parse(data) as WorkersAiStreamChunk;\n } catch {\n return;\n }\n\n if (parsed.usage) {\n if (typeof parsed.usage.prompt_tokens === 'number') {\n state.promptTokens = parsed.usage.prompt_tokens;\n }\n if (typeof parsed.usage.completion_tokens === 'number') {\n state.completionTokens = parsed.usage.completion_tokens;\n }\n if (typeof parsed.usage.total_tokens === 'number') {\n state.totalTokens = parsed.usage.total_tokens;\n }\n }\n\n if (recordOutputs && typeof parsed.response === 'string') {\n state.responseTexts.push(parsed.response);\n }\n\n if (recordOutputs && Array.isArray(parsed.tool_calls) && parsed.tool_calls.length > 0) {\n state.toolCalls.push(...parsed.tool_calls);\n }\n\n if (Array.isArray(parsed.choices)) {\n if (typeof parsed.id === 'string') {\n state.responseId = parsed.id;\n }\n if (typeof parsed.model === 'string') {\n state.responseModel = parsed.model;\n }\n\n for (const choice of parsed.choices) {\n if (recordOutputs && typeof choice.delta?.content === 'string' && choice.delta.content) {\n state.responseTexts.push(choice.delta.content);\n }\n if (recordOutputs && Array.isArray(choice.delta?.tool_calls)) {\n accumulateStreamingToolCalls(choice.delta.tool_calls, toolCallAccumulator);\n }\n if (typeof choice.finish_reason === 'string') {\n state.finishReasons.push(choice.finish_reason);\n }\n }\n }\n}\n\n/**\n * Wrap a Workers AI streaming response (a server-sent-events `ReadableStream`) so we can\n * accumulate the response text and token usage while passing the original bytes through untouched.\n *\n * The span is ended once the consumer finishes reading (or cancels) the stream.\n */\nexport function instrumentWorkersAiStream(\n stream: ReadableStream<Uint8Array>,\n span: Span,\n recordOutputs: boolean,\n abortSignal?: AbortSignal,\n beforeSpanEnd?: (result: GenAiSpanResult<never>) => void,\n): ReadableStream<Uint8Array> {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n\n const state: StreamResponseState = {\n responseId: '',\n responseModel: '',\n finishReasons: [],\n responseTexts: [],\n toolCalls: [],\n promptTokens: undefined,\n completionTokens: undefined,\n totalTokens: undefined,\n };\n\n // OpenAI-compatible tool calls arrive fragmented across chunks and are keyed by index;\n // accumulate them here and flatten into `state.toolCalls` once the stream ends.\n const toolCallAccumulator: ToolCallAccumulator = { calls: new Map(), keyByIndex: new Map() };\n\n let buffer = '';\n let spanEnded = false;\n\n const finish = (result: GenAiSpanResult<never> = {}): void => {\n if (spanEnded) {\n return;\n }\n spanEnded = true;\n\n if (recordOutputs) {\n const accumulatedToolCalls = [...toolCallAccumulator.calls.values()];\n if (accumulatedToolCalls.length > 0) {\n state.toolCalls.push(...accumulatedToolCalls);\n }\n\n // Set the authoritative `gen_ai.output.messages` alongside the deprecated response\n // attributes `endStreamSpan` writes, so tool calls survive Relay's lossy migration.\n setOutputMessagesAttribute(span, {\n responseText: state.responseTexts.join(''),\n toolCalls: state.toolCalls,\n finishReason: state.finishReasons[0],\n });\n }\n\n endStreamSpan(span, state, recordOutputs, () => beforeSpanEnd?.(result));\n };\n\n const flushBuffer = (isDone: boolean): void => {\n const lines = buffer.split('\\n');\n // Keep the last (potentially incomplete) line in the buffer unless the stream is done.\n buffer = isDone ? '' : (lines.pop() ?? '');\n for (const line of lines) {\n processLine(line, state, recordOutputs, toolCallAccumulator);\n }\n };\n\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n\n if (done) {\n buffer += decoder.decode();\n flushBuffer(true);\n finish();\n controller.close();\n return;\n }\n\n recordTimeToFirstChunk(span);\n buffer += decoder.decode(value, { stream: true });\n flushBuffer(false);\n controller.enqueue(value);\n } catch (error) {\n span.setStatus(getErrorStatus(abortSignal));\n finish({ error });\n controller.error(error);\n }\n },\n async cancel(reason) {\n finish();\n await reader.cancel(reason);\n },\n });\n}\n","import { SENTRY_OP } from '@sentry/conventions/attributes';\nimport { getClient, hasSpanStreamingEnabled, startSpan, startSpanManual } from '@sentry/core';\nimport type { Span } from '@sentry/core';\nimport { getErrorStatus, getRequestSignal, isReadableStream, resolveGenAiCallRecording } from '../core/utils';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport { shouldSkipAiProviderSpan } from '../pi-ai/providers';\nimport { WORKERS_AI_INTEGRATION_NAME } from './constants';\nimport { instrumentWorkersAiStream } from './streaming';\nimport type { WorkersAiCallInfo, WorkersAiOptions } from './types';\nimport {\n addRequestAttributes,\n addResponseAttributes,\n extractRequestAttributes,\n getOperationName,\n WORKERS_AI_OPERATION_SPAN_OPS,\n} from './utils';\n\nconst originalClients = new WeakMap<object, object>();\n\n/**\n * Wrap the `run` method of the Workers AI binding with Sentry tracing.\n */\nfunction instrumentRun(\n originalRun: (...args: unknown[]) => Promise<unknown>,\n context: unknown,\n options: WorkersAiOptions,\n): (...args: unknown[]) => Promise<unknown> {\n return function instrumentedRun(...args: unknown[]): Promise<unknown> {\n if (shouldSkipAiProviderSpan(WORKERS_AI_INTEGRATION_NAME)) {\n return originalRun.apply(context, args);\n }\n\n const [model, inputs, runOptions] = args as [unknown, unknown, Record<string, unknown> | undefined];\n\n const operationName = getOperationName(model, inputs);\n const call: WorkersAiCallInfo = { operation: operationName, model, inputs, options: runOptions };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n const requestAttributes = extractRequestAttributes(model, inputs, operationName);\n const modelName = typeof model === 'string' && model ? model : 'unknown';\n const abortSignal = getRequestSignal(runOptions);\n const client = getClient();\n\n const isStreamRequested =\n !!inputs && typeof inputs === 'object' && (inputs as { stream?: unknown }).stream === true;\n const returnsRawResponse =\n !!runOptions &&\n typeof runOptions === 'object' &&\n (runOptions.returnRawResponse === true || runOptions.websocket === true);\n\n const spanConfig = {\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name:\n modelName !== 'unknown' || !(client && hasSpanStreamingEnabled(client))\n ? `${operationName} ${modelName}`\n : operationName,\n attributes: {\n [SENTRY_OP]: WORKERS_AI_OPERATION_SPAN_OPS[operationName],\n ...requestAttributes,\n },\n };\n\n if (isStreamRequested && !returnsRawResponse) {\n return startSpanManual(spanConfig, (span: Span) => {\n // `startSpanManual` does not auto-end the span, so we must end it on every exit path,\n // including a synchronous throw from `run`.\n const handleError = (error: unknown): never => {\n span.setStatus(getErrorStatus(abortSignal));\n runGenAiSpanEnd(options, span, call, { error });\n span.end();\n throw error;\n };\n\n let originalResult: Promise<unknown>;\n\n try {\n originalResult = originalRun.apply(context, args) as Promise<unknown>;\n } catch (error) {\n return handleError(error);\n }\n\n if (recordInputs) {\n addRequestAttributes(span, inputs, operationName);\n }\n runGenAiSpanStart(options, span, call);\n\n return originalResult.then(result => {\n if (isReadableStream<Uint8Array>(result)) {\n return instrumentWorkersAiStream(result, span, recordOutputs, abortSignal, streamResult =>\n runGenAiSpanEnd(options, span, call, streamResult),\n );\n }\n\n // The model did not actually return a stream — finalize the span eagerly.\n addResponseAttributes(span, result, recordOutputs, operationName);\n runGenAiSpanEnd(options, span, call, { response: result });\n span.end();\n return result;\n }, handleError);\n });\n }\n\n return startSpan(spanConfig, (span: Span) => {\n const originalResult = originalRun.apply(context, args) as Promise<unknown>;\n\n if (recordInputs) {\n addRequestAttributes(span, inputs, operationName);\n }\n runGenAiSpanStart(options, span, call);\n\n return originalResult.then(\n result => {\n if (!returnsRawResponse) {\n addResponseAttributes(span, result, recordOutputs, operationName);\n }\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}\n\n/**\n * Instrument a Cloudflare Workers AI binding (`env.AI`) with Sentry tracing.\n *\n * This wraps the binding's `run` method to create `gen_ai` spans following the\n * Sentry AI Agents conventions. All other methods are passed through untouched.\n *\n * In `@sentry/cloudflare`, the `env.AI` binding is instrumented automatically —\n * wrapping manually is only needed to pass custom options.\n *\n * @example\n * ```javascript\n * const ai = Sentry.instrumentWorkersAiClient(env.AI, { recordInputs: true, recordOutputs: true });\n * const result = await ai.run('@cf/meta/llama-3.1-8b-instruct', { prompt: 'Hello' });\n * ```\n */\nexport function instrumentWorkersAiClient<T extends object>(client: T, options?: WorkersAiOptions): T {\n // `@sentry/cloudflare` already wraps `env.AI`. Wrapping that proxy again would nest a second span\n // that ignores these options, so wrap the original binding instead.\n const original = (originalClients.get(client) ?? client) as T;\n\n const instrumented = new Proxy(original, {\n get(target: object, prop: string | symbol, receiver: unknown): unknown {\n const value = Reflect.get(target, prop, receiver);\n\n if (prop === 'run' && typeof value === 'function') {\n return instrumentRun(value as (...args: unknown[]) => Promise<unknown>, target, options ?? {});\n }\n\n // Bind passed-through functions to the original target to preserve `this` (e.g. private fields).\n return typeof value === 'function' ? (value as (...args: unknown[]) => unknown).bind(target) : value;\n },\n }) as T;\n\n originalClients.set(instrumented, original);\n return instrumented;\n}\n","export const LANGCHAIN_INTEGRATION_NAME = 'LangChain' as const;\nexport const LANGCHAIN_ORIGIN = 'auto.ai.langchain';\n// Matches `MAX_TRACKED_FLUE_SPANS`: LangChain skips the end callbacks when a consumer abandons a stream.\nexport const MAX_TRACKED_LANGCHAIN_RUNS = 1000;\n\nexport const ROLE_MAP: Record<string, string> = {\n human: 'user',\n ai: 'assistant',\n assistant: 'assistant',\n system: 'system',\n function: 'function',\n tool: 'tool',\n};\n","/* eslint-disable max-lines */\n/* eslint-disable typescript-eslint/no-deprecated */\nimport { isObjectLike, stringify } from '@sentry/core';\nimport type { SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_AGENT_NAME,\n GEN_AI_CONVERSATION_ID,\n GEN_AI_INPUT_MESSAGES,\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_PRESENCE_PENALTY,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_REQUEST_TOP_P,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_REQUEST_STREAM_ATTRIBUTE, GEN_AI_RESPONSE_STOP_REASON_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport { extractSystemInstructions, getTokenUsageAttributes } from '../core/utils';\nimport type { GenAiOptions } from '../core/utils';\nimport { LANGCHAIN_ORIGIN, ROLE_MAP } from './constants';\nimport type { LangChainLLMResult, LangChainMessage, LangChainSerialized } from './types';\n\n/**\n * Assigns an attribute only when the value is neither `undefined` nor `null`.\n *\n * We keep this tiny helper because call sites are repetitive and easy to miswrite.\n * It also preserves falsy-but-valid values like `0` and `\"\"`.\n */\nconst setIfDefined = (target: Record<string, SpanAttributeValue | undefined>, key: string, value: unknown): void => {\n if (value != null) target[key] = value as SpanAttributeValue;\n};\n\n/**\n * Like `setIfDefined`, but converts the value with `Number()` and skips only when the\n * result is `NaN`. This ensures numeric 0 makes it through (unlike truthy checks).\n */\nconst setNumberIfDefined = (\n target: Record<string, SpanAttributeValue | undefined>,\n key: string,\n value: unknown,\n): void => {\n const n = Number(value);\n if (!Number.isNaN(n)) target[key] = n;\n};\n\n/**\n * Normalizes a single role token to our canonical set.\n *\n * @param role Incoming role value (free-form, any casing)\n * @returns Canonical role: 'user' | 'assistant' | 'system' | 'function' | 'tool' | <passthrough>\n */\nfunction normalizeMessageRole(role: string): string {\n const normalized = role.toLowerCase();\n return ROLE_MAP[normalized] ?? normalized;\n}\n\n/**\n * Infers a role from a LangChain message constructor name.\n *\n * Checks for substrings like \"System\", \"Human\", \"AI\", etc.\n */\nfunction normalizeRoleNameFromCtor(name: string): string {\n if (name.includes('System')) return 'system';\n if (name.includes('Human')) return 'user';\n if (name.includes('AI') || name.includes('Assistant')) return 'assistant';\n if (name.includes('Function')) return 'function';\n if (name.includes('Tool')) return 'tool';\n return 'user';\n}\n\n/**\n * Returns invocation params from a LangChain `tags` object.\n *\n * LangChain often passes runtime parameters (model, temperature, etc.) via the\n * `tags.invocation_params` bag. If `tags` is an array (LangChain sometimes uses\n * string tags), we return `undefined`.\n *\n * @param tags LangChain tags (string[] or record)\n * @returns The `invocation_params` object, if present\n */\nexport function getInvocationParams(tags?: string[] | Record<string, unknown>): Record<string, unknown> | undefined {\n if (!tags || Array.isArray(tags)) return undefined;\n return tags.invocation_params as Record<string, unknown> | undefined;\n}\n\n/**\n * Normalizes a heterogeneous set of LangChain messages to `{ role, content }`.\n *\n * Why so many branches? LangChain messages can arrive in several shapes:\n * - Message classes with `_getType()` (most reliable)\n * - Classes with meaningful constructor names (e.g. `SystemMessage`)\n * - Plain objects with `type`, or `{ role, content }`\n * - Serialized format with `{ lc: 1, id: [...], kwargs: { content } }`\n * We preserve the prioritization to minimize behavioral drift.\n *\n * @param messages Mixed LangChain messages\n * @returns Array of normalized `{ role, content }`\n */\nexport function normalizeLangChainMessages(\n messages: LangChainMessage[],\n): Array<{ role: string; content: string | undefined }> {\n return messages.map(message => {\n // 1) Prefer _getType() when present\n const maybeGetType = (message as { _getType?: () => string })._getType;\n if (typeof maybeGetType === 'function') {\n const messageType = maybeGetType.call(message);\n return {\n role: normalizeMessageRole(messageType),\n content: stringify(message.content, String),\n };\n }\n\n // 2) Serialized LangChain format (lc: 1) - check before constructor name\n // This is more reliable than constructor.name which can be lost during serialization\n if (message.lc === 1 && message.kwargs) {\n const id = message.id;\n const messageType = Array.isArray(id) && id.length > 0 ? id[id.length - 1] : '';\n const role = typeof messageType === 'string' ? normalizeRoleNameFromCtor(messageType) : 'user';\n\n return {\n role: normalizeMessageRole(role),\n content: stringify(message.kwargs?.content, String),\n };\n }\n\n // 3) Then objects with `type`\n if (message.type) {\n const role = String(message.type).toLowerCase();\n return {\n role: normalizeMessageRole(role),\n content: stringify(message.content, String),\n };\n }\n\n // 4) Then objects with `{ role, content }` - check before constructor name\n // Plain objects have constructor.name=\"Object\" which would incorrectly default to \"user\"\n if (message.role) {\n return {\n role: normalizeMessageRole(String(message.role)),\n content: stringify(message.content, String),\n };\n }\n\n // 5) Then try constructor name (SystemMessage / HumanMessage / ...)\n // Only use this if we haven't matched a more specific case\n const ctor = (message as { constructor?: { name?: string } }).constructor?.name;\n if (ctor && ctor !== 'Object') {\n return {\n role: normalizeMessageRole(normalizeRoleNameFromCtor(ctor)),\n content: stringify(message.content, String),\n };\n }\n\n // 6) Fallback: treat as user text\n return {\n role: 'user',\n content: stringify(message.content, String),\n };\n });\n}\n\n/**\n * Extracts request attributes common to both LLM and ChatModel invocations.\n *\n * Source precedence:\n * 1) `invocationParams` (highest)\n * 2) `langSmithMetadata`\n *\n * Numeric values are set even when 0 (e.g. `temperature: 0`), but skipped if `NaN`.\n */\nfunction extractCommonRequestAttributes(\n serialized: LangChainSerialized,\n invocationParams?: Record<string, unknown>,\n langSmithMetadata?: Record<string, unknown>,\n): Record<string, SpanAttributeValue> {\n const attrs: Record<string, SpanAttributeValue> = {};\n\n // Get kwargs if available (from constructor type)\n const kwargs = 'kwargs' in serialized ? serialized.kwargs : undefined;\n\n const temperature = invocationParams?.temperature ?? langSmithMetadata?.ls_temperature ?? kwargs?.temperature;\n setNumberIfDefined(attrs, GEN_AI_REQUEST_TEMPERATURE, temperature);\n\n const maxTokens = invocationParams?.max_tokens ?? langSmithMetadata?.ls_max_tokens ?? kwargs?.max_tokens;\n setNumberIfDefined(attrs, GEN_AI_REQUEST_MAX_TOKENS, maxTokens);\n\n const topP = invocationParams?.top_p ?? kwargs?.top_p;\n setNumberIfDefined(attrs, GEN_AI_REQUEST_TOP_P, topP);\n\n const frequencyPenalty = invocationParams?.frequency_penalty;\n setNumberIfDefined(attrs, GEN_AI_REQUEST_FREQUENCY_PENALTY, frequencyPenalty);\n\n const presencePenalty = invocationParams?.presence_penalty;\n setNumberIfDefined(attrs, GEN_AI_REQUEST_PRESENCE_PENALTY, presencePenalty);\n\n // LangChain uses `stream`. We only set the attribute if the key actually exists\n // (some callbacks report `false` even on streamed requests, this stems from LangChain's callback handler).\n if (invocationParams && 'stream' in invocationParams) {\n setIfDefined(attrs, GEN_AI_REQUEST_STREAM_ATTRIBUTE, Boolean(invocationParams.stream));\n }\n\n return attrs;\n}\n\n/**\n * Small helper to assemble boilerplate attributes shared by both request extractors.\n * Always uses 'chat' as the operation type for all LLM and chat model operations.\n */\nfunction baseRequestAttributes(\n system: unknown,\n modelName: unknown,\n serialized: LangChainSerialized,\n invocationParams?: Record<string, unknown>,\n langSmithMetadata?: Record<string, unknown>,\n): Record<string, SpanAttributeValue | undefined> {\n return {\n [GEN_AI_PROVIDER_NAME]: stringify(system ?? 'langchain', String),\n [GEN_AI_OPERATION_NAME]: 'chat',\n [GEN_AI_REQUEST_MODEL]: stringify(modelName, String),\n [SENTRY_ORIGIN]: LANGCHAIN_ORIGIN,\n ...extractCommonRequestAttributes(serialized, invocationParams, langSmithMetadata),\n };\n}\n\n/**\n * Extracts attributes for plain LLM invocations (string prompts).\n *\n * - Operation is tagged as `chat` following OpenTelemetry semantic conventions.\n * LangChain LLM operations are treated as chat operations.\n * - When `recordInputs` is true, string prompts are wrapped into `{role:\"user\"}`\n * messages to align with the chat schema used elsewhere.\n */\nexport function extractLLMRequestAttributes(\n llm: LangChainSerialized,\n prompts: string[],\n recordInputs: boolean,\n invocationParams?: Record<string, unknown>,\n langSmithMetadata?: Record<string, unknown>,\n): Record<string, SpanAttributeValue | undefined> {\n const system = langSmithMetadata?.ls_provider;\n const modelName = invocationParams?.model ?? langSmithMetadata?.ls_model_name ?? 'unknown';\n\n const attrs = baseRequestAttributes(system, modelName, llm, invocationParams, langSmithMetadata);\n\n if (recordInputs && Array.isArray(prompts) && prompts.length > 0) {\n const messages = prompts.map(p => ({ role: 'user', content: p }));\n setIfDefined(attrs, GEN_AI_INPUT_MESSAGES, stringify(messages));\n }\n\n return attrs;\n}\n\n/**\n * Extracts attributes for ChatModel invocations (array-of-arrays of messages).\n *\n * - Operation is tagged as `chat` following OpenTelemetry semantic conventions.\n * LangChain chat model operations are chat operations.\n * - We flatten LangChain's `LangChainMessage[][]` and normalize shapes into a\n * consistent `{ role, content }` array when `recordInputs` is true.\n * - Provider system value falls back to `serialized.id?.[2]`.\n */\nexport function extractChatModelRequestAttributes(\n llm: LangChainSerialized,\n langChainMessages: LangChainMessage[][],\n recordInputs: boolean,\n invocationParams?: Record<string, unknown>,\n langSmithMetadata?: Record<string, unknown>,\n): Record<string, SpanAttributeValue | undefined> {\n const system = langSmithMetadata?.ls_provider ?? llm.id?.[2];\n const modelName = invocationParams?.model ?? langSmithMetadata?.ls_model_name ?? 'unknown';\n\n const attrs = baseRequestAttributes(system, modelName, llm, invocationParams, langSmithMetadata);\n\n if (recordInputs && Array.isArray(langChainMessages) && langChainMessages.length > 0) {\n const normalized = normalizeLangChainMessages(langChainMessages.flat());\n\n const { systemInstructions, filteredMessages } = extractSystemInstructions(normalized);\n\n if (systemInstructions) {\n setIfDefined(attrs, GEN_AI_SYSTEM_INSTRUCTIONS, systemInstructions);\n }\n\n setIfDefined(attrs, GEN_AI_INPUT_MESSAGES, stringify(filteredMessages));\n }\n\n return attrs;\n}\n\n/**\n * Extracts tool calls from generations and records them on the span attributes.\n * Prefers message.tool_calls (LangChain's normalized format). Falls back to\n * scanning message.content for Anthropic-style tool_use items in older versions\n * where tool_calls may not be populated.\n */\nfunction addToolCallsAttributes(generations: LangChainMessage[][], attrs: Record<string, SpanAttributeValue>): void {\n const toolCalls: unknown[] = [];\n const flatGenerations = generations.flat();\n\n for (const gen of flatGenerations) {\n const msg = gen.message as Record<string, unknown> | undefined;\n const msgToolCalls = msg?.tool_calls as unknown[] | undefined;\n if (Array.isArray(msgToolCalls) && msgToolCalls.length > 0) {\n toolCalls.push(...msgToolCalls);\n } else {\n // Fallback for older LangChain versions: scan message.content for Anthropic-style tool_use\n const content = gen.message?.content;\n if (Array.isArray(content)) {\n for (const item of content) {\n const t = item as Record<string, unknown>;\n if (t.type === 'tool_use') toolCalls.push(t);\n }\n }\n }\n }\n\n if (toolCalls.length > 0) {\n setIfDefined(attrs, GEN_AI_RESPONSE_TOOL_CALLS, stringify(toolCalls, String));\n }\n}\n\nexport function extractMessageTokenUsageAttributes(message: LangChainMessage): Record<string, number> {\n const usage = message.usage_metadata;\n if (isObjectLike(usage)) {\n const details = isObjectLike(usage.input_token_details) ? usage.input_token_details : undefined;\n return getTokenUsageAttributes(\n usage.input_tokens,\n usage.output_tokens,\n details?.cache_creation,\n details?.cache_read,\n usage.total_tokens,\n );\n }\n\n const metadata = message.response_metadata;\n const tokenUsage = isObjectLike(metadata) && isObjectLike(metadata.tokenUsage) ? metadata.tokenUsage : undefined;\n return getTokenUsageAttributes(\n tokenUsage?.promptTokens,\n tokenUsage?.completionTokens,\n undefined,\n undefined,\n tokenUsage?.totalTokens,\n );\n}\n\nfunction addTokenUsageAttributes(llmResult: LangChainLLMResult, attrs: Record<string, SpanAttributeValue>): void {\n const normalizedUsage: Record<string, number> = {};\n const legacyMessageUsage: Record<string, number> = {};\n for (const generations of llmResult.generations ?? []) {\n // Candidate messages share the usage totals for their prompt.\n const message = generations[0]?.message;\n if (message) {\n const usage = isObjectLike(message.usage_metadata) ? normalizedUsage : legacyMessageUsage;\n for (const [key, value] of Object.entries(extractMessageTokenUsageAttributes(message))) {\n usage[key] = (usage[key] ?? 0) + value;\n }\n }\n }\n Object.assign(attrs, Object.keys(normalizedUsage).length > 0 ? normalizedUsage : legacyMessageUsage);\n\n const llmOutput = llmResult.llmOutput;\n if (!llmOutput) return;\n\n const tokenUsage = llmOutput.tokenUsage;\n const anthropicUsage = llmOutput.usage as\n | {\n input_tokens?: number;\n output_tokens?: number;\n cache_creation_input_tokens?: number;\n cache_read_input_tokens?: number;\n }\n | undefined;\n\n // llmOutput.tokenUsage can contain only the final stream chunk's counters.\n if (anthropicUsage && Object.keys(normalizedUsage).length === 0 && Object.keys(legacyMessageUsage).length === 0) {\n const { input_tokens, output_tokens, cache_creation_input_tokens, cache_read_input_tokens } = anthropicUsage;\n const hasInput =\n input_tokens !== undefined || cache_creation_input_tokens !== undefined || cache_read_input_tokens !== undefined;\n Object.assign(\n attrs,\n getTokenUsageAttributes(\n hasInput\n ? (input_tokens ?? 0) + (cache_creation_input_tokens ?? 0) + (cache_read_input_tokens ?? 0)\n : undefined,\n output_tokens,\n cache_creation_input_tokens,\n cache_read_input_tokens,\n ),\n );\n } else if (tokenUsage && Object.keys(normalizedUsage).length === 0 && Object.keys(legacyMessageUsage).length === 0) {\n Object.assign(\n attrs,\n getTokenUsageAttributes(\n tokenUsage.promptTokens,\n tokenUsage.completionTokens,\n undefined,\n undefined,\n tokenUsage.totalTokens,\n ),\n );\n }\n if (anthropicUsage) {\n if (\n typeof anthropicUsage.cache_creation_input_tokens === 'number' &&\n !(GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS in attrs)\n ) {\n attrs[GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS] = anthropicUsage.cache_creation_input_tokens;\n }\n if (\n typeof anthropicUsage.cache_read_input_tokens === 'number' &&\n !(GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS in attrs)\n ) {\n attrs[GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS] = anthropicUsage.cache_read_input_tokens;\n }\n }\n}\n\n/**\n * Extracts response-related attributes based on a `LangChainLLMResult`.\n *\n * - Records finish reasons when present on generations (e.g., OpenAI)\n * - When `recordOutputs` is true, captures textual response content and any\n * tool calls.\n * - Also propagates model name (`model_name` or `model`), response `id`, and\n * `stop_reason` (for providers that use it).\n */\nexport function extractLlmResponseAttributes(\n llmResult: LangChainLLMResult,\n recordOutputs: boolean,\n): Record<string, SpanAttributeValue> | undefined {\n if (!llmResult) return;\n\n const attrs: Record<string, SpanAttributeValue> = {};\n\n if (Array.isArray(llmResult.generations)) {\n const finishReasons = llmResult.generations\n .flat()\n .map(\n g =>\n // v1 uses generationInfo, v0.3+ uses generation_info. The OpenAI Responses API sets neither and only\n // reports it on the message.\n g.generationInfo?.finish_reason ||\n g.generation_info?.finish_reason ||\n g.message?.response_metadata?.finish_reason,\n )\n .filter((r): r is string => typeof r === 'string');\n\n if (finishReasons.length > 0) {\n setIfDefined(attrs, GEN_AI_RESPONSE_FINISH_REASONS, stringify(finishReasons, String));\n }\n\n // Tool calls metadata (names, IDs) are not PII, so capture them regardless of recordOutputs\n addToolCallsAttributes(llmResult.generations as LangChainMessage[][], attrs);\n\n if (recordOutputs) {\n const texts = llmResult.generations\n .flat()\n .map(gen => gen.text ?? gen.message?.content)\n .filter(t => typeof t === 'string');\n\n if (texts.length > 0) {\n setIfDefined(attrs, GEN_AI_RESPONSE_TEXT, stringify(texts, String));\n }\n }\n }\n\n addTokenUsageAttributes(llmResult, attrs);\n\n const llmOutput = llmResult.llmOutput;\n\n // Extract from v1 generations structure if available\n const firstGeneration = llmResult.generations?.[0]?.[0];\n const v1Message = firstGeneration?.message;\n\n // Provider model identifier: `model_name` (OpenAI-style) or `model` (others)\n // v1 stores this in message.response_metadata.model_name\n const modelName = llmOutput?.model_name ?? llmOutput?.model ?? v1Message?.response_metadata?.model_name;\n if (modelName) setIfDefined(attrs, GEN_AI_RESPONSE_MODEL, modelName);\n\n // Response ID: v1 stores this in message.id\n const responseId = llmOutput?.id ?? v1Message?.id;\n if (responseId) {\n setIfDefined(attrs, GEN_AI_RESPONSE_ID, responseId);\n }\n\n // Stop reason: v1 stores this in message.response_metadata.finish_reason\n const stopReason = llmOutput?.stop_reason ?? v1Message?.response_metadata?.finish_reason;\n if (stopReason) {\n setIfDefined(attrs, GEN_AI_RESPONSE_STOP_REASON_ATTRIBUTE, stringify(stopReason, String));\n }\n\n return attrs;\n}\n\nexport function getAgentNameFromMetadata(metadata?: Record<string, unknown>): Record<string, SpanAttributeValue> {\n const attrs: Record<string, SpanAttributeValue> = {};\n // lc_agent_name is injected by the langgraph invoke()/stream() wrappers (`prepareAgentSpan`)\n const agentName = metadata?.lc_agent_name;\n if (typeof agentName === 'string') {\n attrs[GEN_AI_AGENT_NAME] = agentName;\n }\n return attrs;\n}\n\n/**\n * Metadata keys under which LangChain apps carry a conversation id, in order of precedence.\n * `thread_id` is the LangGraph checkpointer key and one of the two keys LangSmith groups threads by,\n * `session_id` is the other, and `sessionId` is what `RunnableWithMessageHistory` requires in JS.\n */\nconst CONVERSATION_ID_METADATA_KEYS = ['thread_id', 'session_id', 'sessionId'] as const;\n\nfunction findConversationIdEntry(source?: Record<string, unknown>): [string, string | number] | undefined {\n for (const key of CONVERSATION_ID_METADATA_KEYS) {\n const value = source?.[key];\n if ((typeof value === 'string' && value) || (typeof value === 'number' && Number.isFinite(value))) {\n return [key, value];\n }\n }\n return undefined;\n}\n\n/**\n * The recording decision of the LangGraph graph run that `metadata` belongs to. The graph's `invoke()`/`stream()`\n * call decides once, and child runs inherit the decision through their metadata.\n */\nexport function getLangGraphRunRecording(metadata?: Record<string, unknown>): Required<GenAiOptions> | undefined {\n const recording = metadata?.__sentry_langgraph__;\n return isObjectLike(recording) ? (recording as Required<GenAiOptions>) : undefined;\n}\n\n/**\n * Derive `gen_ai.conversation.id` from run metadata, which child runs inherit from their parent.\n * An id from `Sentry.setConversationId()` still wins, since `conversationIdIntegration` applies it on `spanStart`.\n */\nexport function getConversationIdFromMetadata(metadata?: Record<string, unknown>): Record<string, SpanAttributeValue> {\n const entry = findConversationIdEntry(metadata);\n return entry ? { [GEN_AI_CONVERSATION_ID]: String(entry[1]) } : {};\n}\n\n/**\n * The conversation id entry from `config.configurable`, to spread under the run metadata.\n * `@langchain/core` >= 1.1.40 only copies `configurable` into metadata for LangSmith tracers, not for our handler.\n */\nexport function getConversationIdMetadataFromConfig(config: Record<string, unknown>): Record<string, unknown> {\n const entry = findConversationIdEntry(config.configurable as Record<string, unknown> | undefined);\n return entry ? { [entry[0]]: entry[1] } : {};\n}\n\nexport function extractToolDefinitions(extraParams?: Record<string, unknown>): string | undefined {\n const tools =\n (extraParams?.invocation_params as Record<string, unknown>)?.tools ??\n (extraParams?.options as Record<string, unknown>)?.tools;\n if (!Array.isArray(tools) || tools.length === 0) return undefined;\n const toolDefs = tools.map((tool: Record<string, unknown>) => {\n const fn = tool.function as Record<string, unknown> | undefined;\n return {\n type: 'function',\n name: tool.name ?? fn?.name ?? '',\n description: tool.description ?? fn?.description,\n };\n });\n return JSON.stringify(toolDefs);\n}\n\n// A run started without config inherits the parent run's config, which LangChain keeps in a global\n// AsyncLocalStorage. `ensureConfig` lets an explicit `callbacks` key replace the inherited one.\nconst LANGCHAIN_ALS_KEY = Symbol.for('ls:tracing_async_local_storage');\nconst LANGCHAIN_CHILD_CONFIG_KEY = Symbol.for('lc:child_config');\n\n/** The callbacks LangChain gives a run started without config: the ones of the parent run, if any. */\nexport function getInheritedLangChainCallbacks(): unknown {\n const storage = (globalThis as Record<symbol, unknown>)[LANGCHAIN_ALS_KEY] as\n | { getStore?: () => unknown }\n | undefined;\n const store = typeof storage?.getStore === 'function' ? storage.getStore() : undefined;\n const extra = isObjectLike(store) ? (store.extra as Record<symbol, unknown> | undefined) : undefined;\n const config = isObjectLike(extra) ? extra[LANGCHAIN_CHILD_CONFIG_KEY] : undefined;\n return isObjectLike(config) ? config.callbacks : undefined;\n}\n\n/** Duck-types a LangChain `CallbackManager` (avoids coupling to a specific `@langchain/core` resolution). */\nfunction isCallbackManager(value: unknown): value is {\n addHandler: (handler: unknown, inherit?: boolean) => void;\n copy: () => unknown;\n handlers?: unknown[];\n} {\n if (!value || typeof value !== 'object') {\n return false;\n }\n const candidate = value as { addHandler?: unknown; copy?: unknown };\n return typeof candidate.addHandler === 'function' && typeof candidate.copy === 'function';\n}\n\nfunction isSentryHandler(handler: unknown): boolean {\n return typeof handler === 'object' && (handler as Record<string, unknown>)?.name === 'SentryCallbackHandler';\n}\n\nfunction containsSentryHandler(handlers: unknown[]): boolean {\n return handlers.some(isSentryHandler);\n}\n\n/**\n * Merge `sentryHandler` into a given set of LangChain callbacks or callback manager.\n * @internal Exported for cross-package instrumentation.\n */\nexport function _INTERNAL_mergeLangChainCallbackHandler(existing: unknown, sentryHandler: unknown): unknown {\n const handlers = isCallbackManager(existing) ? (existing.handlers ?? []) : toHandlerArray(existing);\n return containsSentryHandler(handlers) ? existing : _INTERNAL_addLangChainCallbackHandler(existing, sentryHandler);\n}\n\n/**\n * Add `handler` to a given set of LangChain callbacks or callback manager, without deduplicating it.\n * A callback manager is copied rather than mutated.\n * @internal Exported for cross-package instrumentation.\n */\nexport function _INTERNAL_addLangChainCallbackHandler(existing: unknown, handler: unknown): unknown {\n if (!existing) {\n return [handler];\n }\n\n if (isCallbackManager(existing)) {\n const copied = existing.copy() as { addHandler: (handler: unknown, inherit?: boolean) => void };\n copied.addHandler(handler, true);\n return copied;\n }\n\n return [...toHandlerArray(existing), handler];\n}\n\nfunction toHandlerArray(existing: unknown): unknown[] {\n return Array.isArray(existing) ? existing : existing ? [existing] : [];\n}\n","import { SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport type { Span } from '@sentry/core';\nimport { isObjectLike } from '@sentry/core';\nimport { addResponseAttributes, startDecideSpan } from '../typesafe';\nimport { LANGCHAIN_ORIGIN } from './constants';\nimport { getAgentNameFromMetadata, getConversationIdFromMetadata } from './utils';\n\n// `TypeSafeClassifier` from `@langchain/typesafe` calls Jev with `fetch`, not through `@typesafe-ai/sdk`,\n// so the TypeSafe integration does not see it. Its serialized id is `[...lc_namespace, lc_name()]`; only\n// the class name is matched, as the namespace is the part that changes between versions.\nconst TYPESAFE_CLASSIFIER_NAME = 'TypeSafeClassifier';\n\n/** The package's default, used when the classifier is constructed without a `model`. */\nconst DEFAULT_TYPESAFE_CLASSIFIER_MODEL = 'jev-latest';\n\n// The `state` the classifier sends to Jev (messages rendered as transcript lines), keyed by the input\n// passed to `invoke()`. LangChain hands that same object to `handleChainStart`, so the span records what\n// Jev received rather than LangChain's serialized messages.\nconst wireStates = new WeakMap<object, unknown>();\n\n/** Record the `state` a `TypeSafeClassifier` sends for `input`, using the classifier's own serializer. */\nexport function recordTypeSafeClassifierState(classifier: unknown, input: unknown): void {\n // A string state is sent as is, so there is nothing to record.\n if (!isObjectLike(input) || !isObjectLike(classifier) || typeof classifier.payload !== 'function') {\n return;\n }\n\n try {\n const body: unknown = JSON.parse(classifier.payload(input));\n if (isObjectLike(body)) {\n wireStates.set(input, body.state);\n }\n } catch {\n // The classifier rejects the same input itself; the span keeps LangChain's form of it.\n }\n}\n\n// Typed loosely: LangChain's `Serialized` union does not match our handler's chain type.\nexport function isTypeSafeClassifier(chain: unknown): boolean {\n return isObjectLike(chain) && Array.isArray(chain.id) && chain.id[chain.id.length - 1] === TYPESAFE_CLASSIFIER_NAME;\n}\n\n/** Start a `decide` span for a `TypeSafeClassifier` run, from its serialized constructor arguments. */\nexport function startTypeSafeClassifierSpan(\n chain: unknown,\n inputs: Record<string, unknown>,\n metadata: Record<string, unknown> | undefined,\n recordInputs: boolean,\n): Span {\n const kwargs = isObjectLike(chain) && isObjectLike(chain.kwargs) ? chain.kwargs : {};\n const model = typeof kwargs.model === 'string' ? kwargs.model : DEFAULT_TYPESAFE_CLASSIFIER_MODEL;\n\n return startDecideSpan({ model, state: getState(inputs), questions: kwargs.questions }, undefined, recordInputs, {\n [SENTRY_ORIGIN]: LANGCHAIN_ORIGIN,\n ...getAgentNameFromMetadata(metadata),\n ...getConversationIdFromMetadata(metadata),\n });\n}\n\n/** The classifier result reports usage in camelCase, the TypeSafe helpers read the API's snake_case. */\nexport function addTypeSafeClassifierResponseAttributes(span: Span, outputs: unknown, recordOutputs: boolean): void {\n if (!isObjectLike(outputs)) {\n return;\n }\n\n const usage = isObjectLike(outputs.usage) ? outputs.usage : {};\n addResponseAttributes(\n span,\n {\n model: outputs.model,\n answers: outputs.answers,\n usage: { input_tokens: usage.inputTokens, output_tokens: usage.outputTokens },\n },\n recordOutputs,\n );\n}\n\nfunction getState(inputs: Record<string, unknown>): unknown {\n // LangChain hands a string or array input to callbacks wrapped as `{ input }`.\n const keys = Object.keys(inputs);\n const input = inputs.input;\n const state =\n keys.length === 1 && keys[0] === 'input' && (typeof input === 'string' || Array.isArray(input)) ? input : inputs;\n\n return isObjectLike(state) && wireStates.has(state) ? wireStates.get(state) : state;\n}\n","import { getClient, hasSpanStreamingEnabled, SPAN_STATUS_ERROR, startSpan, stringify } from '@sentry/core';\nimport type { SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_OPERATION_NAME,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_MODEL,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_EMBEDDINGS } from '@sentry/conventions/op';\nimport {\n GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE,\n GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE,\n} from '../core/gen-ai-attributes';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport { resolveGenAiCallRecording } from '../core/utils';\nimport { LANGCHAIN_ORIGIN } from './constants';\nimport type { LangChainEmbeddingsCallInfo, LangChainOptions } from './types';\n\n/**\n * Infers the AI provider system name from the embedding class instance.\n */\nfunction inferSystemFromInstance(instance: Record<string, unknown>): string {\n const name = (instance.constructor as { name?: string })?.name ?? '';\n if (name.includes('OpenAI')) return 'openai';\n if (name.includes('Google')) return 'google_genai';\n if (name.includes('Mistral')) return 'mistralai';\n if (name.includes('Vertex')) return 'google_vertexai';\n if (name.includes('Bedrock')) return 'aws_bedrock';\n if (name.includes('Ollama')) return 'ollama';\n if (name.includes('Cloudflare')) return 'cloudflare';\n if (name.includes('Cohere')) return 'cohere';\n return 'langchain';\n}\n\n/**\n * Extracts span attributes from a LangChain embedding class instance.\n */\nfunction extractEmbeddingAttributes(instance: unknown): Record<string, unknown> {\n const embeddingsInstance = (instance ?? {}) as Record<string, unknown>;\n\n const attributes: Record<string, unknown> = {\n [SENTRY_ORIGIN]: LANGCHAIN_ORIGIN,\n [SENTRY_OP]: GEN_AI_EMBEDDINGS,\n [GEN_AI_OPERATION_NAME]: 'embeddings',\n [GEN_AI_REQUEST_MODEL]: embeddingsInstance.model ?? 'unknown',\n };\n\n attributes[GEN_AI_PROVIDER_NAME] = inferSystemFromInstance(embeddingsInstance);\n if ('dimensions' in embeddingsInstance) {\n attributes[GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE] = embeddingsInstance.dimensions;\n }\n if ('encodingFormat' in embeddingsInstance) {\n attributes[GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE] = embeddingsInstance.encodingFormat;\n }\n\n return attributes;\n}\n\n/**\n * Builds the span options for a LangChain embedding call from the embeddings instance and input.\n *\n * @internal Exported so the diagnostics-channel (orchestrion) instrumentation can build the same\n * span as the prototype-patching path below.\n */\nexport function _INTERNAL_getLangChainEmbeddingsSpanOptions(\n instance: unknown,\n call: LangChainEmbeddingsCallInfo,\n options: LangChainOptions = {},\n): { name: string; attributes: Record<string, SpanAttributeValue> } {\n const { input } = call;\n const { recordInputs } = resolveGenAiCallRecording(options, call);\n const attributes = extractEmbeddingAttributes(instance);\n const modelName = attributes[GEN_AI_REQUEST_MODEL] || 'unknown';\n const client = getClient();\n\n if (recordInputs && input != null) {\n attributes[GEN_AI_EMBEDDINGS_INPUT] = stringify(input, String);\n }\n\n return {\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name:\n (typeof modelName === 'string' && modelName !== 'unknown') || !(client && hasSpanStreamingEnabled(client))\n ? `embeddings ${modelName}`\n : 'embeddings',\n attributes: attributes as Record<string, SpanAttributeValue>,\n };\n}\n\n/**\n * Wraps a LangChain embedding method (embedQuery or embedDocuments) to create Sentry spans.\n *\n * Used internally by the Node.js auto-instrumentation to patch embedding class prototypes.\n */\nexport function instrumentEmbeddingMethod(\n originalMethod: (...args: unknown[]) => Promise<unknown>,\n options: LangChainOptions = {},\n): (...args: unknown[]) => Promise<unknown> {\n return new Proxy(originalMethod, {\n apply(target, thisArg, args: unknown[]): Promise<unknown> {\n const call: LangChainEmbeddingsCallInfo = { operation: 'embeddings', input: args[0] };\n return startSpan(_INTERNAL_getLangChainEmbeddingsSpanOptions(thisArg, call, options), async span => {\n runGenAiSpanStart(options, span, call);\n try {\n const response = await Reflect.apply(target, thisArg, args);\n runGenAiSpanEnd(options, span, call, { response });\n return response;\n } catch (error) {\n // The error is rethrown to the caller, so we only mark the span failed and do not record it.\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n runGenAiSpanEnd(options, span, call, { error });\n throw error;\n }\n });\n },\n });\n}\n\n/**\n * Wraps a LangChain embeddings instance to create Sentry spans for `embedQuery` and `embedDocuments` calls.\n *\n * Use this in non-Node runtimes (Cloudflare, browser, etc.) where auto-instrumentation is not available.\n *\n * @example\n * ```javascript\n * import * as Sentry from '@sentry/cloudflare';\n * import { OpenAIEmbeddings } from '@langchain/openai';\n *\n * const embeddings = Sentry.instrumentLangChainEmbeddings(\n * new OpenAIEmbeddings({ model: 'text-embedding-3-small' })\n * );\n *\n * await embeddings.embedQuery('Hello world');\n * await embeddings.embedDocuments(['doc1', 'doc2']);\n * ```\n */\nexport function instrumentLangChainEmbeddings<T extends object>(instance: T, options?: LangChainOptions): T {\n const embeddingsInstance = instance as Record<string, unknown>;\n\n if (typeof embeddingsInstance.embedQuery === 'function') {\n embeddingsInstance.embedQuery = instrumentEmbeddingMethod(\n embeddingsInstance.embedQuery as (...args: unknown[]) => Promise<unknown>,\n options,\n );\n }\n\n if (typeof embeddingsInstance.embedDocuments === 'function') {\n embeddingsInstance.embedDocuments = instrumentEmbeddingMethod(\n embeddingsInstance.embedDocuments as (...args: unknown[]) => Promise<unknown>,\n options,\n );\n }\n\n return instance;\n}\n","/* eslint-disable max-lines */\nimport {\n debug,\n getActiveSpan,\n getClient,\n getRootSpan,\n hasSpanStreamingEnabled,\n LRUMap,\n SPAN_STATUS_ERROR,\n spanIsIgnored,\n spanToJSON,\n startInactiveSpan,\n stringify,\n withActiveSpan,\n} from '@sentry/core';\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_OPERATION_NAME,\n GEN_AI_PIPELINE_NAME,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DEFINITIONS,\n GEN_AI_TOOL_NAME,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_CHAT, GEN_AI_EXECUTE_TOOL, GEN_AI_INVOKE_AGENT } from '@sentry/conventions/op';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { GenAiSpanResult } from '../core/span-hooks';\nimport { resolveGenAiCallRecording } from '../core/utils';\nimport type { GenAiOptions } from '../core/utils';\nimport { recordTimeToFirstChunk } from '../core/time-to-first-chunk';\nimport { LANGCHAIN_ORIGIN, MAX_TRACKED_LANGCHAIN_RUNS } from './constants';\nimport {\n addTypeSafeClassifierResponseAttributes,\n isTypeSafeClassifier,\n startTypeSafeClassifierSpan,\n} from './typesafe-classifier';\nimport type {\n LangChainCallbackHandler,\n LangChainCallInfo,\n LangChainLLMResult,\n LangChainMessage,\n LangChainOptions,\n LangChainSerialized,\n} from './types';\nimport {\n extractChatModelRequestAttributes,\n extractLLMRequestAttributes,\n extractLlmResponseAttributes,\n extractToolDefinitions,\n getAgentNameFromMetadata,\n getConversationIdFromMetadata,\n getInvocationParams,\n getLangGraphRunRecording,\n} from './utils';\n\ntype LangChainRunCallInfo = Exclude<LangChainCallInfo, { operation: 'embeddings' }>;\n\ninterface LangChainRun {\n span: Span;\n call: LangChainRunCallInfo;\n // The span active when the run started, to tell whether a span was opened inside the run since.\n activeSpan?: Span;\n conversationId?: string;\n decide?: boolean;\n recordOutputs: boolean;\n}\n\n/**\n * Creates a Sentry callback handler for LangChain\n * Returns a plain object that LangChain will call via duck-typing\n *\n * This is a stateful handler that tracks spans across multiple LangChain executions.\n */\nexport function createLangChainCallbackHandler(options: LangChainOptions = {}): LangChainCallbackHandler {\n const resolveRecording = (call: LangChainRunCallInfo): Required<GenAiOptions> =>\n getLangGraphRunRecording(call.metadata) ?? resolveGenAiCallRecording(options, call);\n\n // Internal state - single instance tracks all spans\n const runs = new LRUMap<string, LangChainRun>(MAX_TRACKED_LANGCHAIN_RUNS);\n const getRun = (runId: string | undefined): LangChainRun | undefined => (runId ? runs.get(runId) : undefined);\n\n /**\n * Exit a span and clean up\n */\n const exitSpan = (runId: string, result: GenAiSpanResult<unknown> = {}): void => {\n const run = runs.remove(runId);\n if (run?.span.isRecording()) {\n runGenAiSpanEnd(options, run.span, run.call, result);\n run.span.end();\n }\n };\n\n // `LRUMap.set` would drop the oldest run without ending its span, so it is ended first, like Flue and Mastra.\n let warnedFull = false;\n const trackRun = (runId: string, run: LangChainRun): void => {\n if (runs.size >= MAX_TRACKED_LANGCHAIN_RUNS) {\n if (!warnedFull) {\n warnedFull = true;\n DEBUG_BUILD &&\n debug.warn(\n `[LangChain] More than ${MAX_TRACKED_LANGCHAIN_RUNS} runs are open, ending the oldest. Its span may be cut short.`,\n );\n }\n const oldestRunId = runs.keys()[0];\n if (oldestRunId !== undefined) {\n exitSpan(oldestRunId);\n }\n }\n runs.set(runId, run);\n };\n\n // Nearest first. `LRUMap.get()` marks each run recently used, so a long-running root run is not evicted while\n // its subtree is busy.\n const getAncestors = (parentRunId: string | undefined): LangChainRun[] => {\n const ancestors: LangChainRun[] = [];\n for (let run = getRun(parentRunId); run; run = getRun(run.call.parentRunId)) {\n ancestors.push(run);\n }\n return ancestors;\n };\n\n // LangChain never makes our run spans active, so a run starts under its nearest ancestor run span. Like core,\n // an ignored span only parents when it is a root, which drops its subtree. The active span stays the parent\n // if the ancestor run has no span, or if another span was opened since that run started.\n const getParentRunSpan = (ancestors: LangChainRun[], activeSpan: Span | undefined): Span | undefined => {\n for (const run of ancestors) {\n if (run.activeSpan !== activeSpan) {\n return undefined;\n }\n if (!spanIsIgnored(run.span) || getRootSpan(run.span) === run.span) {\n return run.span;\n }\n }\n return undefined;\n };\n\n const startRunSpan = (call: LangChainRunCallInfo, recordOutputs: boolean, start: () => Span): LangChainRun => {\n const { runId, parentRunId } = call;\n const ancestors = getAncestors(parentRunId);\n const activeSpan = getActiveSpan();\n const parentSpan = getParentRunSpan(ancestors, activeSpan);\n const span = parentSpan ? withActiveSpan(parentSpan, start) : start();\n\n // `@langchain/core` >= 1.1.40 keeps `configurable` out of run metadata, so often only the chat span knows\n // the conversation id. The own id is read off the span, since one from `Sentry.setConversationId()` is\n // only set there.\n const ownId = spanToJSON(span).attributes[GEN_AI_CONVERSATION_ID];\n const conversationId = typeof ownId === 'string' ? ownId : ancestors[0]?.conversationId;\n if (conversationId && conversationId !== ownId) {\n span.setAttribute(GEN_AI_CONVERSATION_ID, conversationId);\n }\n\n const run: LangChainRun = { span, call, activeSpan, conversationId, recordOutputs };\n trackRun(runId, run);\n if (conversationId) {\n for (const ancestor of ancestors) {\n if (ancestor.conversationId) {\n break;\n }\n ancestor.conversationId = conversationId;\n ancestor.span.setAttribute(GEN_AI_CONVERSATION_ID, conversationId);\n }\n }\n runGenAiSpanStart(options, span, call);\n return run;\n };\n\n /**\n * Handler for LLM Start\n * This handler will be called by LangChain's callback handler when an LLM event is detected.\n */\n const handler: LangChainCallbackHandler = {\n // Required LangChain BaseCallbackHandler properties\n lc_serializable: false,\n lc_namespace: ['langchain_core', 'callbacks', 'sentry'],\n lc_secrets: undefined,\n lc_attributes: undefined,\n lc_aliases: undefined,\n lc_serializable_keys: undefined,\n lc_id: ['langchain_core', 'callbacks', 'sentry'],\n lc_kwargs: {},\n name: 'SentryCallbackHandler',\n\n // BaseCallbackHandlerInput boolean flags\n ignoreLLM: false,\n ignoreChain: false,\n ignoreAgent: false,\n ignoreRetriever: false,\n ignoreCustomEvent: false,\n raiseError: false,\n awaitHandlers: true,\n\n handleLLMStart(\n llm: unknown,\n prompts: string[],\n runId: string,\n parentRunId?: string,\n extraParams?: Record<string, unknown>,\n tags?: string[],\n metadata?: Record<string, unknown>,\n _runName?: string,\n ) {\n const serialized = llm as LangChainSerialized;\n const call: LangChainRunCallInfo = {\n operation: 'chat',\n serialized,\n prompts,\n runId,\n parentRunId,\n extraParams,\n tags,\n metadata,\n };\n const { recordInputs, recordOutputs } = resolveRecording(call);\n const invocationParams = getInvocationParams(tags);\n const attributes = extractLLMRequestAttributes(serialized, prompts, recordInputs, invocationParams, metadata);\n const modelName = attributes[GEN_AI_REQUEST_MODEL] || 'unknown';\n const operationName =\n typeof attributes[GEN_AI_OPERATION_NAME] === 'string' ? attributes[GEN_AI_OPERATION_NAME] : 'unknown';\n const client = getClient();\n\n startRunSpan(call, recordOutputs, () =>\n startInactiveSpan({\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name:\n (typeof modelName === 'string' && modelName !== 'unknown') || !(client && hasSpanStreamingEnabled(client))\n ? `${operationName} ${modelName}`\n : operationName,\n attributes: {\n ...getAgentNameFromMetadata(metadata),\n ...getConversationIdFromMetadata(metadata),\n ...attributes,\n [SENTRY_OP]: GEN_AI_CHAT,\n },\n }),\n );\n },\n\n // Chat Model Start Handler\n handleChatModelStart(\n llm: unknown,\n messages: unknown,\n runId: string,\n parentRunId?: string,\n extraParams?: Record<string, unknown>,\n tags?: string[],\n metadata?: Record<string, unknown>,\n _runName?: string,\n ) {\n const serialized = llm as LangChainSerialized;\n const chatMessages = messages as LangChainMessage[][];\n const call: LangChainRunCallInfo = {\n operation: 'chat',\n serialized,\n messages: chatMessages,\n runId,\n parentRunId,\n extraParams,\n tags,\n metadata,\n };\n const { recordInputs, recordOutputs } = resolveRecording(call);\n const invocationParams = getInvocationParams(tags);\n const attributes = extractChatModelRequestAttributes(\n serialized,\n chatMessages,\n recordInputs,\n invocationParams,\n metadata,\n );\n\n const toolDefsJson = recordInputs ? extractToolDefinitions(extraParams) : undefined;\n if (toolDefsJson) {\n attributes[GEN_AI_TOOL_DEFINITIONS] = toolDefsJson;\n }\n\n const modelName = attributes[GEN_AI_REQUEST_MODEL] || 'unknown';\n const operationName =\n typeof attributes[GEN_AI_OPERATION_NAME] === 'string' ? attributes[GEN_AI_OPERATION_NAME] : 'unknown';\n const client = getClient();\n\n startRunSpan(call, recordOutputs, () =>\n startInactiveSpan({\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name:\n (typeof modelName === 'string' && modelName !== 'unknown') || !(client && hasSpanStreamingEnabled(client))\n ? `${operationName} ${modelName}`\n : operationName,\n attributes: {\n ...getAgentNameFromMetadata(metadata),\n ...getConversationIdFromMetadata(metadata),\n ...attributes,\n [SENTRY_OP]: GEN_AI_CHAT,\n },\n }),\n );\n },\n\n // Called for each streamed chunk.\n handleLLMNewToken(_token: string, _idx: unknown, runId: string) {\n const span = runs.get(runId)?.span;\n if (span) {\n recordTimeToFirstChunk(span);\n }\n },\n\n // LLM End Handler - note: handleLLMEnd with capital LLM (used by both LLMs and chat models!)\n handleLLMEnd(\n output: unknown,\n runId: string,\n _parentRunId?: string,\n _tags?: string[],\n _extraParams?: Record<string, unknown>,\n ) {\n const run = runs.get(runId);\n const span = run?.span;\n if (run && span?.isRecording()) {\n const attributes = extractLlmResponseAttributes(output as LangChainLLMResult, run.recordOutputs);\n if (attributes) {\n span.setAttributes(attributes);\n }\n }\n exitSpan(runId, { response: output });\n },\n\n // LLM Error Handler - note: handleLLMError with capital LLM\n handleLLMError(error: Error, runId: string) {\n // The error is surfaced to the caller (invoke() rejects), so we only mark the span failed and\n // do not record it.\n const span = runs.get(runId)?.span;\n if (span?.isRecording()) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n exitSpan(runId, { error });\n },\n\n // Chain Start Handler\n handleChainStart(\n chain: { name?: string },\n inputs: Record<string, unknown>,\n runId: string,\n parentRunId?: string,\n tags?: string[],\n metadata?: Record<string, unknown>,\n _runType?: string,\n runName?: string,\n ) {\n // A Jev call is a real model call, so it is recorded inside an agent too.\n if (isTypeSafeClassifier(chain)) {\n const call: LangChainRunCallInfo = {\n operation: 'decide',\n serialized: chain,\n inputs,\n runId,\n parentRunId,\n tags,\n metadata,\n };\n const { recordInputs, recordOutputs } = resolveRecording(call);\n startRunSpan(call, recordOutputs, () =>\n startTypeSafeClassifierSpan(chain, inputs, metadata, recordInputs),\n ).decide = true;\n return;\n }\n\n // Skip chain spans when inside an agent context (createReactAgent).\n // The agent already creates an invoke_agent span; internal chain steps\n // (ChannelWrite, Branch, prompt, etc.) are noise.\n if (metadata?.__sentry_langgraph__) {\n return;\n }\n\n const call: LangChainRunCallInfo = {\n operation: 'invoke_agent',\n serialized: chain,\n inputs,\n runId,\n parentRunId,\n tags,\n metadata,\n };\n const { recordInputs, recordOutputs } = resolveRecording(call);\n const chainName = runName || chain.name;\n const attributes: Record<string, SpanAttributeValue> = {\n ...getConversationIdFromMetadata(metadata),\n [SENTRY_ORIGIN]: 'auto.ai.langchain',\n [GEN_AI_OPERATION_NAME]: 'invoke_agent',\n };\n\n if (chainName) {\n attributes[GEN_AI_PIPELINE_NAME] = chainName;\n }\n\n if (recordInputs) {\n attributes['langchain.chain.inputs'] = JSON.stringify(inputs);\n }\n\n const client = getClient();\n\n startRunSpan(call, recordOutputs, () =>\n startInactiveSpan({\n // With span streaming, the name leads with the operation per the agent templates. The\n // chain name is bounded, so it stays; the `'unknown_chain'` sentinel is dropped instead.\n name: !(client && hasSpanStreamingEnabled(client))\n ? `chain ${chainName || 'unknown_chain'}`\n : chainName\n ? `invoke_agent ${chainName}`\n : 'invoke_agent',\n attributes: {\n ...attributes,\n [SENTRY_OP]: GEN_AI_INVOKE_AGENT,\n },\n }),\n );\n },\n\n // Chain End Handler\n handleChainEnd(outputs: unknown, runId: string) {\n const run = runs.get(runId);\n const span = run?.span;\n if (run && span?.isRecording()) {\n if (run.decide) {\n addTypeSafeClassifierResponseAttributes(span, outputs, run.recordOutputs);\n } else if (run.recordOutputs) {\n span.setAttributes({\n 'langchain.chain.outputs': JSON.stringify(outputs),\n });\n }\n }\n exitSpan(runId, { response: outputs });\n },\n\n // Chain Error Handler\n handleChainError(error: Error, runId: string) {\n // The error is surfaced to the caller (invoke() rejects), so we only mark the span failed and\n // do not record it.\n const span = runs.get(runId)?.span;\n if (span?.isRecording()) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n exitSpan(runId, { error });\n },\n\n // Tool Start Handler\n handleToolStart(\n tool: { name?: string },\n input: string,\n runId: string,\n parentRunId?: string,\n tags?: string[],\n metadata?: Record<string, unknown>,\n runName?: string,\n ) {\n // Skip tool spans when inside an agent context (createReactAgent).\n // Tool spans are created by wrapToolsWithSpans with richer attributes.\n if (metadata?.__sentry_langgraph__) {\n return;\n }\n\n const call: LangChainRunCallInfo = {\n operation: 'execute_tool',\n serialized: tool,\n input,\n runId,\n parentRunId,\n tags,\n metadata,\n };\n const { recordInputs, recordOutputs } = resolveRecording(call);\n // runName is set to tool.name by LangChain's StructuredTool.call()\n const toolName = runName || tool.name || 'unknown_tool';\n const attributes: Record<string, SpanAttributeValue> = {\n ...getAgentNameFromMetadata(metadata),\n ...getConversationIdFromMetadata(metadata),\n [SENTRY_ORIGIN]: LANGCHAIN_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'execute_tool',\n [GEN_AI_TOOL_NAME]: toolName,\n };\n\n if (recordInputs) {\n attributes[GEN_AI_TOOL_CALL_ARGUMENTS] = input;\n }\n\n startRunSpan(call, recordOutputs, () =>\n startInactiveSpan({\n name: `execute_tool ${toolName}`,\n attributes: {\n ...attributes,\n [SENTRY_OP]: GEN_AI_EXECUTE_TOOL,\n },\n }),\n );\n },\n\n // Tool End Handler\n handleToolEnd(output: unknown, runId: string) {\n const run = runs.get(runId);\n const span = run?.span;\n if (run && span?.isRecording()) {\n if (run.recordOutputs) {\n // LangChain tools may return ToolMessage objects — extract the content\n const outputObj = output as Record<string, unknown> | undefined;\n const content =\n outputObj && typeof outputObj === 'object' && 'content' in outputObj ? outputObj.content : output;\n span.setAttributes({\n [GEN_AI_TOOL_CALL_RESULT]: stringify(content, String),\n });\n }\n }\n exitSpan(runId, { response: output });\n },\n\n // Tool Error Handler\n handleToolError(error: Error, runId: string) {\n // The error is surfaced to the caller (invoke() rejects), so we only mark the span failed and\n // do not record it.\n const span = runs.get(runId)?.span;\n if (span?.isRecording()) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n exitSpan(runId, { error });\n },\n\n // LangChain BaseCallbackHandler required methods\n copy() {\n return handler;\n },\n\n toJSON() {\n return {\n lc: 1,\n type: 'not_implemented',\n id: handler.lc_id,\n };\n },\n\n toJSONNotImplemented() {\n return {\n lc: 1,\n type: 'not_implemented',\n id: handler.lc_id,\n };\n },\n };\n\n return handler;\n}\n\nexport { instrumentLangChainEmbeddings } from './embeddings';\n","export const LANGGRAPH_INTEGRATION_NAME = 'LangGraph' as const;\nexport const LANGGRAPH_ORIGIN = 'auto.ai.langgraph';\n","/* eslint-disable typescript-eslint/no-deprecated */\nimport { SPAN_STATUS_ERROR, startSpan, stringify } from '@sentry/core';\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport {\n GEN_AI_AGENT_NAME,\n GEN_AI_OPERATION_NAME,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DESCRIPTION,\n GEN_AI_TOOL_NAME,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_EXECUTE_TOOL } from '@sentry/conventions/op';\nimport { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport { resolveAIRecordingOptions, setOutputMessagesAttribute } from '../core/utils';\nimport type { GenAiOptions } from '../core/utils';\nimport type { BaseChatModel, LangChainMessage } from '../langchain/types';\nimport {\n extractMessageTokenUsageAttributes,\n getConversationIdFromMetadata,\n getLangGraphRunRecording,\n normalizeLangChainMessages,\n} from '../langchain/utils';\nimport { LANGGRAPH_ORIGIN } from './constants';\nimport type { CompiledGraph, LangGraphOptions, LangGraphTool } from './types';\n\n/**\n * Extract LLM model object from createReactAgent params\n */\nexport function extractLLMFromParams(args: unknown[]): BaseChatModel | null {\n const arg = args[0];\n if (typeof arg !== 'object' || !arg || !('llm' in arg) || !arg.llm || typeof arg.llm !== 'object') {\n return null;\n }\n const llm = arg.llm as BaseChatModel;\n if (typeof llm.modelName !== 'string' && typeof llm.model !== 'string') {\n return null;\n }\n return llm;\n}\n\n/**\n * Extract agent name from createReactAgent params\n */\nexport function extractAgentNameFromParams(args: unknown[]): string | null {\n const arg = args[0];\n if (typeof arg === 'object' && !!arg && 'name' in arg && typeof arg.name === 'string') {\n return arg.name;\n }\n return null;\n}\n\n/** The options that hold outside a graph run, where no `invoke()`/`stream()` call decided: a function needs the graph input. */\nexport function getBooleanRecordingOptions(options: LangGraphOptions): GenAiOptions {\n const { recordInputs, recordOutputs } = options;\n return {\n recordInputs: typeof recordInputs === 'boolean' ? recordInputs : undefined,\n recordOutputs: typeof recordOutputs === 'boolean' ? recordOutputs : undefined,\n };\n}\n\n/**\n * Wraps an array of LangChain tools so each invocation creates a gen_ai.execute_tool span.\n *\n * Wraps each tool's invoke() method in place. A marker prevents double-wrapping.\n */\nexport function wrapToolsWithSpans(tools: unknown[], options: LangGraphOptions, agentName?: string): unknown[] {\n const SENTRY_WRAPPED = '__sentry_tool_wrapped__';\n\n for (const tool of tools) {\n if (!tool || typeof tool !== 'object') {\n continue;\n }\n\n const t = tool as Record<string, unknown>;\n const originalInvoke = t.invoke;\n if (typeof originalInvoke !== 'function' || Object.prototype.hasOwnProperty.call(t, SENTRY_WRAPPED)) {\n continue;\n }\n\n const toolName = typeof t.name === 'string' ? t.name : 'unknown_tool';\n const toolDescription = typeof t.description === 'string' ? t.description : undefined;\n\n const wrappedInvoke = new Proxy(originalInvoke as (...args: unknown[]) => unknown, {\n apply(target, thisArg, args: unknown[]): unknown {\n const spanAttributes: SpanAttributes = {\n [SENTRY_ORIGIN]: LANGGRAPH_ORIGIN,\n [SENTRY_OP]: GEN_AI_EXECUTE_TOOL,\n [GEN_AI_OPERATION_NAME]: 'execute_tool',\n [GEN_AI_TOOL_NAME]: toolName,\n };\n\n // Read agent name from LangChain's propagated config metadata at call time,\n // so shared tools get the correct agent name for each invocation\n const callConfig = args[1] as Record<string, unknown> | undefined;\n const metadata = callConfig?.metadata as Record<string, unknown> | undefined;\n const { recordInputs, recordOutputs } =\n getLangGraphRunRecording(metadata) ?? resolveAIRecordingOptions(getBooleanRecordingOptions(options));\n const callAgentName = metadata?.lc_agent_name ?? agentName;\n if (typeof callAgentName === 'string') {\n spanAttributes[GEN_AI_AGENT_NAME] = callAgentName;\n }\n Object.assign(spanAttributes, getConversationIdFromMetadata(metadata));\n\n if (toolDescription) {\n spanAttributes[GEN_AI_TOOL_DESCRIPTION] = toolDescription;\n }\n\n // LangGraph ToolNode passes { name, args, id, type: \"tool_call\" }\n const input = args[0] as Record<string, unknown> | undefined;\n if (typeof input === 'object' && !!input) {\n if ('id' in input && typeof input.id === 'string') {\n spanAttributes[GEN_AI_TOOL_CALL_ID_ATTRIBUTE] = input.id;\n }\n\n if (recordInputs) {\n const toolArgs = 'args' in input && typeof input.args === 'object' ? input.args : input;\n try {\n spanAttributes[GEN_AI_TOOL_CALL_ARGUMENTS] = JSON.stringify(toolArgs);\n } catch {\n // skip if not serializable\n }\n }\n }\n\n return startSpan(\n {\n name: `execute_tool ${toolName}`,\n attributes: spanAttributes,\n },\n async span => {\n try {\n const result = await Reflect.apply(target, thisArg, args);\n\n if (recordOutputs) {\n try {\n // ToolMessage objects wrap the result in .content\n const resultObj = result as Record<string, unknown> | undefined;\n const content =\n resultObj && typeof resultObj === 'object' && 'content' in resultObj ? resultObj.content : result;\n span.setAttribute(\n GEN_AI_TOOL_CALL_RESULT,\n typeof content === 'string' ? content : JSON.stringify(content),\n );\n } catch {\n // skip if not serializable\n }\n }\n\n return result;\n } catch (error) {\n // The error is rethrown to the caller (invoke() rejects), so we only mark the span\n // failed and do not record it.\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n throw error;\n }\n },\n );\n },\n });\n\n t.invoke = wrappedInvoke;\n Object.defineProperty(t, SENTRY_WRAPPED, { value: true, enumerable: false });\n }\n\n return tools;\n}\n\n/**\n * Extract tool calls from messages\n */\nexport function extractToolCalls(messages: Array<Record<string, unknown>> | null): unknown[] | null {\n if (!messages || messages.length === 0) {\n return null;\n }\n\n const toolCalls: unknown[] = [];\n\n for (const message of messages) {\n if (message && typeof message === 'object') {\n const msgToolCalls = message.tool_calls;\n if (msgToolCalls && Array.isArray(msgToolCalls)) {\n toolCalls.push(...msgToolCalls);\n }\n }\n }\n\n return toolCalls.length > 0 ? toolCalls : null;\n}\n\n/**\n * Extract token usage from a message's usage_metadata or response_metadata\n * Returns token counts without setting span attributes\n */\nexport function extractTokenUsageFromMessage(message: LangChainMessage): {\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n cacheCreationInputTokens?: number;\n cacheReadInputTokens?: number;\n} {\n const attributes = extractMessageTokenUsageAttributes(message);\n return {\n inputTokens: attributes[GEN_AI_USAGE_INPUT_TOKENS] ?? 0,\n outputTokens: attributes[GEN_AI_USAGE_OUTPUT_TOKENS] ?? 0,\n totalTokens: attributes[GEN_AI_USAGE_TOTAL_TOKENS] ?? 0,\n cacheCreationInputTokens: attributes[GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS],\n cacheReadInputTokens: attributes[GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS],\n };\n}\n\n/**\n * Extract model and finish reason from a message's response_metadata\n */\nexport function extractModelMetadata(span: Span, message: LangChainMessage): void {\n const msg = message as Record<string, unknown>;\n\n if (msg.response_metadata && typeof msg.response_metadata === 'object') {\n const metadata = msg.response_metadata as Record<string, unknown>;\n\n if (metadata.model_name && typeof metadata.model_name === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, metadata.model_name);\n }\n\n if (metadata.finish_reason && typeof metadata.finish_reason === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, JSON.stringify([metadata.finish_reason]));\n }\n }\n}\n\n/**\n * Extract tools from compiled graph structure\n *\n * Tools are stored in: compiledGraph.builder.nodes.tools.runnable.tools\n */\nexport function extractToolsFromCompiledGraph(compiledGraph: CompiledGraph): unknown[] | null {\n if (!compiledGraph.builder?.nodes?.tools?.runnable?.tools) {\n return null;\n }\n\n const tools = compiledGraph.builder?.nodes?.tools?.runnable?.tools;\n\n if (!tools || !Array.isArray(tools) || tools.length === 0) {\n return null;\n }\n\n // Extract name, description, and schema from each tool's lc_kwargs\n return tools.map((tool: LangGraphTool) => ({\n name: tool.lc_kwargs?.name,\n description: tool.lc_kwargs?.description,\n schema: tool.lc_kwargs?.schema,\n }));\n}\n\n/**\n * Set response attributes on the span\n */\nexport function setResponseAttributes(span: Span, inputMessages: LangChainMessage[] | null, result: unknown): void {\n // Extract messages from result\n const resultObj = result as { messages?: LangChainMessage[] } | undefined;\n const outputMessages = resultObj?.messages;\n\n if (!outputMessages || !Array.isArray(outputMessages)) {\n // Custom state annotations have no `messages` array, the whole state is recorded instead.\n if (result && typeof result === 'object') {\n const serializedState = stringify(result);\n // `gen_ai.output.messages` is what the product reads first; `gen_ai.response.text` is kept for\n // back-compat (Relay still migrates it).\n setOutputMessagesAttribute(span, { responseText: serializedState });\n span.setAttribute(GEN_AI_RESPONSE_TEXT, stringify([{ role: 'assistant', content: serializedState }]));\n }\n return;\n }\n\n // Get new messages (delta between input and output)\n const inputCount = inputMessages?.length ?? 0;\n const newMessages = outputMessages.length > inputCount ? outputMessages.slice(inputCount) : [];\n\n if (newMessages.length === 0) {\n return;\n }\n\n // Extract and set tool calls from new messages BEFORE normalization\n // (normalization strips tool_calls, so we need to extract them first)\n const toolCalls = extractToolCalls(newMessages);\n if (toolCalls) {\n span.setAttribute(GEN_AI_RESPONSE_TOOL_CALLS, JSON.stringify(toolCalls));\n }\n\n // Normalize the new messages\n const normalizedNewMessages = normalizeLangChainMessages(newMessages);\n span.setAttribute(GEN_AI_RESPONSE_TEXT, JSON.stringify(normalizedNewMessages));\n\n // Accumulate token usage across all messages\n let totalInputTokens = 0;\n let totalOutputTokens = 0;\n let totalTokens = 0;\n let cacheCreationInputTokens: number | undefined;\n let cacheReadInputTokens: number | undefined;\n\n // Extract metadata from messages\n for (const message of newMessages) {\n // Accumulate token usage\n const tokens = extractTokenUsageFromMessage(message);\n totalInputTokens += tokens.inputTokens;\n totalOutputTokens += tokens.outputTokens;\n totalTokens += tokens.totalTokens;\n if (tokens.cacheCreationInputTokens !== undefined) {\n cacheCreationInputTokens = (cacheCreationInputTokens ?? 0) + tokens.cacheCreationInputTokens;\n }\n if (tokens.cacheReadInputTokens !== undefined) {\n cacheReadInputTokens = (cacheReadInputTokens ?? 0) + tokens.cacheReadInputTokens;\n }\n\n // Extract model metadata (last message's metadata wins for model/finish_reason)\n extractModelMetadata(span, message);\n }\n\n // Set accumulated token usage on span\n if (totalInputTokens > 0) {\n span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, totalInputTokens);\n }\n if (totalOutputTokens > 0) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, totalOutputTokens);\n }\n if (totalTokens > 0) {\n span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, totalTokens);\n }\n if (cacheCreationInputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cacheCreationInputTokens);\n }\n if (cacheReadInputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cacheReadInputTokens);\n }\n}\n","import { stringify } from '@sentry/core';\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport {\n GEN_AI_AGENT_NAME,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_PIPELINE_NAME,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_TOOL_DEFINITIONS,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_INVOKE_AGENT } from '@sentry/conventions/op';\nimport { extractSystemInstructions, resolveGenAiCallRecording } from '../core/utils';\nimport type { GenAiOptions } from '../core/utils';\nimport type { BaseChatModel, LangChainMessage } from '../langchain/types';\nimport {\n _INTERNAL_mergeLangChainCallbackHandler,\n getConversationIdFromMetadata,\n getConversationIdMetadataFromConfig,\n getInheritedLangChainCallbacks,\n normalizeLangChainMessages,\n} from '../langchain/utils';\nimport { LANGGRAPH_ORIGIN } from './constants';\nimport type { CompiledGraph, LangGraphCallInfo, LangGraphOptions } from './types';\nimport { extractToolsFromCompiledGraph } from './utils';\n\n// LangGraph's invoke() calls this.stream() before its first await, so a graph set only for that synchronous\n// stretch marks exactly invoke's own stream() call. A stream() started later in the run gets its own span.\nlet invokingGraph: object | undefined;\n\n/** Runs the original invoke() of `graph`, so its internal stream() call can be recognised. */\nexport function callInvoke<T>(graph: object, invoke: () => T): T {\n const previous = invokingGraph;\n invokingGraph = graph;\n try {\n return invoke();\n } finally {\n invokingGraph = previous;\n }\n}\n\n/** Whether this stream() call on `graph` is the one its invoke() makes internally. */\nexport function isInvokeInternalStream(graph: object): boolean {\n return invokingGraph === graph;\n}\n\n/** Name and initial attributes of an agent span, from the call's config. */\nexport function getAgentSpanOptions(\n args: unknown[],\n extraAttributes?: SpanAttributes,\n): { name: string; attributes: SpanAttributes } {\n const config = args.length > 1 ? (args[1] as Record<string, unknown> | undefined) : undefined;\n return {\n name: 'invoke_agent',\n attributes: {\n // Set before `spanStart`, so an id from `Sentry.setConversationId()` wins, as on the child spans\n ...getConversationIdFromMetadata(config?.configurable as Record<string, unknown> | undefined),\n [SENTRY_ORIGIN]: LANGGRAPH_ORIGIN,\n [SENTRY_OP]: GEN_AI_INVOKE_AGENT,\n [GEN_AI_OPERATION_NAME]: 'invoke_agent',\n ...extraAttributes,\n },\n };\n}\n\n/** Decides for one `invoke()`/`stream()` call, from its arguments as passed. */\nexport function resolveGraphCallRecording(\n options: LangGraphOptions,\n args: unknown[],\n): { call: LangGraphCallInfo; recording: Required<GenAiOptions> } {\n const call: LangGraphCallInfo = {\n operation: 'invoke_agent',\n input: args[0],\n config: args[1] as Record<string, unknown> | undefined,\n };\n return { call, recording: resolveGenAiCallRecording(options, call) };\n}\n\n/** Sets the request attributes on an agent span and injects the callback handler into the call's config. */\nexport function prepareAgentSpan(\n span: Span,\n args: unknown[],\n graphInstance: CompiledGraph,\n compileOptions: Record<string, unknown>,\n recording: Required<GenAiOptions>,\n llm: BaseChatModel | null | undefined,\n sentryCallbackHandler: unknown,\n): LangChainMessage[] | null {\n const graphName = compileOptions?.name;\n\n if (graphName && typeof graphName === 'string') {\n span.setAttribute(GEN_AI_PIPELINE_NAME, graphName);\n span.setAttribute(GEN_AI_AGENT_NAME, graphName);\n span.updateName(`invoke_agent ${graphName}`);\n }\n\n const modelName = llm?.modelName ?? llm?.model;\n if (modelName) {\n span.setAttribute(GEN_AI_REQUEST_MODEL, modelName);\n }\n\n // A copy, so nothing is written back to a config object the caller reuses for other calls.\n const config: Record<string, unknown> = { ...(args[1] as Record<string, unknown> | undefined) };\n args[1] = config;\n // Explicit callbacks replace the parent run's, which LangChain would otherwise inherit.\n const callbacks = config.callbacks ?? getInheritedLangChainCallbacks();\n if (callbacks) {\n config.callbacks = callbacks;\n }\n\n if (sentryCallbackHandler) {\n const existingMetadata = (config.metadata ?? {}) as Record<string, unknown>;\n config.metadata = {\n ...getConversationIdMetadataFromConfig(config),\n ...existingMetadata,\n // Child runs inherit the metadata, so their spans follow this call's decision.\n __sentry_langgraph__: recording,\n ...(typeof graphName === 'string' ? { lc_agent_name: graphName } : {}),\n };\n\n config.callbacks = _INTERNAL_mergeLangChainCallbackHandler(config.callbacks, sentryCallbackHandler);\n }\n\n const { recordInputs } = recording;\n\n const tools = recordInputs ? extractToolsFromCompiledGraph(graphInstance) : null;\n if (tools) {\n span.setAttribute(GEN_AI_TOOL_DEFINITIONS, JSON.stringify(tools));\n }\n\n // Custom state annotations have no `messages` array, the whole state is recorded instead.\n const inputState = args[0] as { messages?: LangChainMessage[]; lg_name?: string } | null | undefined;\n const inputMessages = Array.isArray(inputState?.messages) ? inputState.messages : null;\n // `new Command({ resume })` resumes an interrupted run and carries no user turn (LangGraph\n // tags it `lg_name: 'Command'`), so skip it like a `null` resume rather than recording the\n // control object as a message nobody wrote.\n const isResumeCommand = inputState?.lg_name === 'Command';\n\n if (recordInputs) {\n if (inputMessages) {\n const normalizedMessages = normalizeLangChainMessages(inputMessages);\n const { systemInstructions, filteredMessages } = extractSystemInstructions(normalizedMessages);\n\n if (systemInstructions) {\n span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS, systemInstructions);\n }\n\n span.setAttributes({\n [GEN_AI_INPUT_MESSAGES]: stringify(filteredMessages),\n });\n } else if (inputState && typeof inputState === 'object' && !isResumeCommand) {\n span.setAttribute(GEN_AI_INPUT_MESSAGES, stringify([{ role: 'user', content: stringify(inputState) }]));\n }\n }\n\n return inputMessages;\n}\n","import { SPAN_STATUS_ERROR, startSpanManual } from '@sentry/core';\nimport { GEN_AI_RESPONSE_STREAMING } from '@sentry/conventions/attributes';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { BaseChatModel, LangChainMessage } from '../langchain/types';\nimport { _INTERNAL_addLangChainCallbackHandler } from '../langchain/utils';\nimport { getAgentSpanOptions, isInvokeInternalStream, prepareAgentSpan, resolveGraphCallRecording } from './agent-span';\nimport type { CompiledGraph, LangGraphOptions } from './types';\nimport { setResponseAttributes } from './utils';\n\n/**\n * Instruments CompiledGraph's stream method with a `gen_ai.invoke_agent` span that lasts for the graph run.\n *\n * LangGraph runs the graph as soon as `stream()` is called, whether or not the stream is read, so the span\n * ends on the run's own end or error callback rather than when the stream is consumed.\n */\nexport function instrumentCompiledGraphStream(\n originalStream: (...args: unknown[]) => Promise<unknown>,\n graphInstance: CompiledGraph,\n compileOptions: Record<string, unknown>,\n options: LangGraphOptions,\n llm?: BaseChatModel | null,\n sentryCallbackHandler?: unknown,\n): (...args: unknown[]) => Promise<unknown> {\n return new Proxy(originalStream, {\n apply(target, thisArg, args: unknown[]): Promise<unknown> {\n if (isInvokeInternalStream(graphInstance)) {\n return Reflect.apply(target, thisArg, args);\n }\n\n const { call, recording } = resolveGraphCallRecording(options, args);\n return startSpanManual(getAgentSpanOptions(args, { [GEN_AI_RESPONSE_STREAMING]: true }), async span => {\n let inputMessages: LangChainMessage[] | null = null;\n let stream: { signal?: AbortSignal } | undefined;\n let ended = false;\n const finish = (outcome?: { outputs: unknown } | { error: unknown }): void => {\n if (ended) {\n return;\n }\n ended = true;\n try {\n if (outcome && 'error' in outcome) {\n // A cancel or abort by the caller is not a failed run. LangGraph reports both, and step\n // timeouts too, as `Error('Abort')`, so only the signals tell them apart.\n if (!stream?.signal?.aborted && !(args[1] as { signal?: AbortSignal } | undefined)?.signal?.aborted) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n } else if (outcome && recording.recordOutputs) {\n setResponseAttributes(span, inputMessages, outcome.outputs);\n }\n } catch {\n // Recording must never change the outcome of the run.\n }\n runGenAiSpanEnd(\n options,\n span,\n call,\n outcome && 'error' in outcome ? { error: outcome.error } : { response: outcome?.outputs },\n );\n span.end();\n inputMessages = null;\n };\n\n // The root run starts before any of its children, so it is the first run this per-call listener sees.\n let rootRunId: string | undefined;\n const listener = {\n name: 'SentryLangGraphStreamListener',\n awaitHandlers: true,\n handleChainStart(_chain: unknown, _inputs: unknown, runId: string): void {\n rootRunId ??= runId;\n },\n handleChainEnd(outputs: unknown, runId: string): void {\n if (runId === rootRunId) {\n finish({ outputs });\n }\n },\n handleChainError(error: unknown, runId: string): void {\n if (runId === rootRunId) {\n finish({ error });\n }\n },\n copy() {\n return listener;\n },\n };\n\n try {\n inputMessages = prepareAgentSpan(\n span,\n args,\n graphInstance,\n compileOptions,\n recording,\n llm,\n sentryCallbackHandler,\n );\n runGenAiSpanStart(options, span, call);\n // `prepareAgentSpan` gave the call its own copy of the config, so the listener stays on this call.\n const config = args[1] as Record<string, unknown>;\n config.callbacks = _INTERNAL_addLangChainCallbackHandler(config.callbacks, listener);\n stream = (await Reflect.apply(target, thisArg, args)) as typeof stream;\n } catch (error) {\n finish({ error });\n throw error;\n }\n\n if (rootRunId === undefined) {\n // Not a LangGraph run we can follow, so don't leave the span open.\n finish();\n } else {\n endOnEarlyExit(stream, finish);\n }\n return stream;\n });\n },\n });\n}\n\n// After a `break`, LangGraph keeps running the graph but never reports the run's end, so the span ends when\n// the caller stops. Nodes still running at that point start spans after the agent span ended.\nfunction endOnEarlyExit(stream: unknown, finish: () => void): void {\n if (!stream || typeof stream !== 'object') {\n return;\n }\n const target = stream as { return?: (...args: unknown[]) => unknown; cancel?: (...args: unknown[]) => unknown };\n const { return: originalReturn, cancel: originalCancel } = target;\n try {\n if (typeof originalReturn === 'function') {\n target.return = function (this: unknown, ...args: unknown[]): unknown {\n try {\n return originalReturn.apply(this, args);\n } finally {\n finish();\n }\n };\n }\n if (typeof originalCancel === 'function') {\n target.cancel = function (this: unknown, ...args: unknown[]): unknown {\n const result = originalCancel.apply(this, args);\n Promise.resolve(result).then(\n () => finish(),\n () => undefined,\n );\n return result;\n };\n }\n } catch {\n finish();\n }\n}\n","import { SPAN_STATUS_ERROR, startSpan } from '@sentry/core';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport { createLangChainCallbackHandler } from '../langchain';\nimport type { BaseChatModel } from '../langchain/types';\nimport { callInvoke, getAgentSpanOptions, prepareAgentSpan, resolveGraphCallRecording } from './agent-span';\nimport { instrumentCompiledGraphStream } from './stream';\nimport type { CompiledGraph, LangGraphOptions } from './types';\nimport {\n extractAgentNameFromParams,\n extractLLMFromParams,\n getBooleanRecordingOptions,\n setResponseAttributes,\n wrapToolsWithSpans,\n} from './utils';\n\n// Set while a manual wrapper runs the original `compile`/`createReactAgent`. The integration's channel hooks\n// fire synchronously inside that call, and skip the graph so the options passed explicitly win.\nlet _insideManualInstrumentation = false;\n\nconst SENTRY_PATCHED = '__sentry_patched__';\nconst INSTRUMENTED_GRAPHS = new WeakSet<object>();\n\n/** Whether manual `instrumentStateGraph()`/`instrumentCreateReactAgent()` is creating a graph right now. */\nexport function isInsideManualLangGraphInstrumentation(): boolean {\n return _insideManualInstrumentation;\n}\n\nfunction runManually<T>(callback: () => T): T {\n const previous = _insideManualInstrumentation;\n _insideManualInstrumentation = true;\n try {\n return callback();\n } finally {\n _insideManualInstrumentation = previous;\n }\n}\n\n/**\n * Instruments StateGraph's compile method to wrap the returned compiled graph's invoke() and stream() with a\n * `gen_ai.invoke_agent` span.\n */\nexport function instrumentStateGraphCompile(\n originalCompile: (...args: unknown[]) => CompiledGraph,\n options: LangGraphOptions,\n): (...args: unknown[]) => CompiledGraph {\n if (Object.prototype.hasOwnProperty.call(originalCompile, SENTRY_PATCHED)) {\n return originalCompile;\n }\n\n const sentryHandler = createLangChainCallbackHandler(getBooleanRecordingOptions(options));\n\n const wrapped = new Proxy(originalCompile, {\n apply(target, thisArg, args: unknown[]): CompiledGraph {\n // The createReactAgent wrapper instruments the graph it compiles internally, with the agent's name and model.\n if (_insideManualInstrumentation) {\n return Reflect.apply(target, thisArg, args);\n }\n\n const compiledGraph = runManually(() => Reflect.apply(target, thisArg, args));\n const compileOptions = args.length > 0 ? (args[0] as Record<string, unknown>) : {};\n instrumentCompiledGraph(compiledGraph, compileOptions, options, undefined, sentryHandler);\n\n return compiledGraph;\n },\n });\n\n Object.defineProperty(wrapped, SENTRY_PATCHED, { value: true, enumerable: false });\n return wrapped;\n}\n\n/**\n * Wraps a compiled graph's `invoke()` and `stream()` with `gen_ai.invoke_agent` spans, once per graph.\n */\nexport function instrumentCompiledGraph(\n graph: unknown,\n compileOptions: Record<string, unknown>,\n options: LangGraphOptions,\n llm: BaseChatModel | null | undefined,\n sentryCallbackHandler: unknown,\n): void {\n if (!graph || typeof graph !== 'object' || INSTRUMENTED_GRAPHS.has(graph)) {\n return;\n }\n INSTRUMENTED_GRAPHS.add(graph);\n\n const compiledGraph = graph as CompiledGraph;\n const { invoke, stream } = compiledGraph;\n if (typeof invoke === 'function') {\n compiledGraph.invoke = instrumentCompiledGraphInvoke(\n invoke.bind(compiledGraph),\n compiledGraph,\n compileOptions,\n options,\n llm,\n sentryCallbackHandler,\n );\n }\n if (typeof stream === 'function') {\n compiledGraph.stream = instrumentCompiledGraphStream(\n stream.bind(compiledGraph),\n compiledGraph,\n compileOptions,\n options,\n llm,\n sentryCallbackHandler,\n );\n }\n}\n\n/**\n * Instruments CompiledGraph's invoke method to create spans for agent invocation\n *\n * Creates a `gen_ai.invoke_agent` span when invoke() is called\n */\nexport function instrumentCompiledGraphInvoke(\n originalInvoke: (...args: unknown[]) => Promise<unknown>,\n graphInstance: CompiledGraph,\n compileOptions: Record<string, unknown>,\n options: LangGraphOptions,\n llm?: BaseChatModel | null,\n sentryCallbackHandler?: unknown,\n): (...args: unknown[]) => Promise<unknown> {\n return new Proxy(originalInvoke, {\n apply(target, thisArg, args: unknown[]): Promise<unknown> {\n const { call, recording } = resolveGraphCallRecording(options, args);\n return startSpan(getAgentSpanOptions(args), async span => {\n try {\n const inputMessages = prepareAgentSpan(\n span,\n args,\n graphInstance,\n compileOptions,\n recording,\n llm,\n sentryCallbackHandler,\n );\n runGenAiSpanStart(options, span, call);\n const result = await callInvoke(graphInstance, () => Reflect.apply(target, thisArg, args));\n\n if (recording.recordOutputs) {\n setResponseAttributes(span, inputMessages, result);\n }\n runGenAiSpanEnd(options, span, call, { response: result });\n\n return result;\n } catch (error) {\n // The error is rethrown to the caller (invoke() rejects), so we only mark the span failed\n // and do not record it.\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n runGenAiSpanEnd(options, span, call, { error });\n throw error;\n }\n });\n },\n });\n}\n\n/**\n * Instruments createReactAgent to create invoke_agent and execute_tool spans.\n */\nexport function instrumentCreateReactAgent(\n originalCreateReactAgent: (...args: unknown[]) => CompiledGraph,\n options: LangGraphOptions = {},\n): (...args: unknown[]) => CompiledGraph {\n if (Object.prototype.hasOwnProperty.call(originalCreateReactAgent, SENTRY_PATCHED)) {\n return originalCreateReactAgent;\n }\n\n const sentryHandler = createLangChainCallbackHandler(getBooleanRecordingOptions(options));\n\n const wrapped = new Proxy(originalCreateReactAgent, {\n apply(target, thisArg, args: unknown[]): CompiledGraph {\n const llm = extractLLMFromParams(args);\n const agentName = extractAgentNameFromParams(args);\n\n // Wrap tools with execute_tool spans (direct access gives us name, type, description)\n const params = args[0] as Record<string, unknown> | undefined;\n if (params && Array.isArray(params.tools) && params.tools.length > 0) {\n wrapToolsWithSpans(params.tools, options, agentName ?? undefined);\n }\n\n const compiledGraph = runManually(() => Reflect.apply(target, thisArg, args));\n\n const compileOptions: Record<string, unknown> = agentName ? { name: agentName } : {};\n instrumentCompiledGraph(compiledGraph, compileOptions, options, llm, sentryHandler);\n\n return compiledGraph;\n },\n });\n\n Object.defineProperty(wrapped, SENTRY_PATCHED, { value: true, enumerable: false });\n return wrapped;\n}\n\n/**\n * Directly instruments a StateGraph instance to add tracing spans\n *\n * This function can be used to manually instrument LangGraph StateGraph instances\n * in environments where automatic instrumentation is not available or desired.\n *\n * @param stateGraph - The StateGraph instance to instrument\n * @param options - Optional configuration for recording inputs/outputs\n *\n * @example\n * ```typescript\n * import { instrumentStateGraph } from '@sentry/cloudflare';\n * import { StateGraph } from '@langchain/langgraph';\n *\n * const graph = new StateGraph(MessagesAnnotation)\n * .addNode('agent', mockLlm)\n * .addEdge(START, 'agent')\n * .addEdge('agent', END);\n *\n * instrumentStateGraph(graph, { recordInputs: true, recordOutputs: true });\n * const compiled = graph.compile({ name: 'my_agent' });\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function instrumentStateGraph<T extends { compile: (...args: any[]) => any }>(\n stateGraph: T,\n options: LangGraphOptions = {},\n): T {\n stateGraph.compile = instrumentStateGraphCompile(stateGraph.compile, options);\n\n return stateGraph;\n}\n","import {\n GEN_AI_CHAT,\n GEN_AI_DECIDE,\n GEN_AI_EMBEDDINGS,\n GEN_AI_EXECUTE_TOOL,\n GEN_AI_INVOKE_AGENT,\n} from '@sentry/conventions/op';\nimport type { MastraSpanType } from './types';\n\nexport const MASTRA_INTEGRATION_NAME = 'Mastra' as const;\n\n/** Cap on tracked spans, matching `MAX_TRACKED_PRISMA_SPANS`. Spans that never end would otherwise leak. */\nexport const MAX_TRACKED_MASTRA_SPANS = 1000;\n\nexport const MASTRA_ORIGIN = 'auto.ai.mastra';\n\n/** Not `sentry` — that is the community `@mastra/sentry` exporter name. */\nexport const MASTRA_EXPORTER_NAME = 'sentry-sdk';\n\n/** Name used by the community `@mastra/sentry` package. */\nexport const COMMUNITY_MASTRA_SENTRY_EXPORTER_NAME = 'sentry';\n\n/**\n * Distinguishes our exporter from the community one. `Symbol.for` so the check still matches if\n * two copies of `@sentry/server-utils` are loaded (`instanceof` would not).\n */\nexport const MASTRA_EXPORTER_BRAND = Symbol.for('sentry.mastra.exporter');\n\n/**\n * Only conventional `gen_ai` ops. Unmapped Mastra types (workflow steps, processors, scorers, …)\n * are dropped; their children re-parent onto the nearest mapped ancestor.\n *\n * `op` comes from `@sentry/conventions/op`. `operationName` is a `gen_ai.operation.name` literal —\n * the conventions package has no constants for those.\n */\nexport const SPAN_TYPE_OPS: Readonly<Record<string, { op: string; operationName: string }>> = {\n agent_run: { op: GEN_AI_INVOKE_AGENT, operationName: 'invoke_agent' },\n workflow_run: { op: GEN_AI_INVOKE_AGENT, operationName: 'invoke_agent' },\n model_generation: { op: GEN_AI_CHAT, operationName: 'chat' },\n tool_call: { op: GEN_AI_EXECUTE_TOOL, operationName: 'execute_tool' },\n mcp_tool_call: { op: GEN_AI_EXECUTE_TOOL, operationName: 'execute_tool' },\n provider_tool_call: { op: GEN_AI_EXECUTE_TOOL, operationName: 'execute_tool' },\n client_tool_call: { op: GEN_AI_EXECUTE_TOOL, operationName: 'execute_tool' },\n rag_embedding: { op: GEN_AI_EMBEDDINGS, operationName: 'embeddings' },\n classifier_evaluation: { op: GEN_AI_DECIDE, operationName: 'decide' },\n};\n\nexport const TOOL_SPAN_TYPES: ReadonlySet<string> = new Set<MastraSpanType>([\n 'tool_call',\n 'mcp_tool_call',\n 'provider_tool_call',\n 'client_tool_call',\n]);\n\n/**\n * `model_inference` is omitted: Mastra nests `model_generation > model_step > model_inference`,\n * and the inference span repeats the generation — mapping both to `gen_ai.chat` duplicates it.\n */\nexport const MODEL_SPAN_TYPES: ReadonlySet<string> = new Set<MastraSpanType>(['model_generation']);\n\nexport const AGENT_SPAN_TYPES: ReadonlySet<string> = new Set<MastraSpanType>(['agent_run', 'workflow_run']);\n","import type { SpanAttributeValue } from '@sentry/core';\nimport { stringify } from '@sentry/core';\nimport {\n ERROR_TYPE,\n GEN_AI_AGENT_NAME,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_OUTPUT_MESSAGES,\n GEN_AI_PIPELINE_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_PRESENCE_PENALTY,\n GEN_AI_REQUEST_SEED,\n GEN_AI_REQUEST_STOP_SEQUENCES,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_REQUEST_TOP_K,\n GEN_AI_REQUEST_TOP_P,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_STREAMING,\n GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DEFINITIONS,\n GEN_AI_TOOL_DESCRIPTION,\n GEN_AI_TOOL_NAME,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n} from '@sentry/conventions/attributes';\nimport { AGENT_SPAN_TYPES, MODEL_SPAN_TYPES, SPAN_TYPE_OPS, TOOL_SPAN_TYPES } from './constants';\nimport type { MastraExportedSpan, MastraSpanType, MastraUsageStats } from './types';\n\nexport interface AttributeRecordingOptions {\n recordInputs: boolean;\n recordOutputs: boolean;\n}\n\nexport type SpanAttributes = Record<string, SpanAttributeValue | undefined>;\n\nexport function isExportedSpanType(spanType: MastraSpanType): boolean {\n // `in` would also match inherited keys like `constructor` or `toString`.\n return Object.prototype.hasOwnProperty.call(SPAN_TYPE_OPS, spanType);\n}\n\nexport function getOperation(spanType: MastraSpanType): { op: string; operationName: string } | undefined {\n return SPAN_TYPE_OPS[spanType];\n}\n\n/**\n * `{operation} {identifier}` per the gen_ai name templates. Mastra's own span name is never used.\n * https://conventions.sentry.dev/names/\n */\nexport function getSpanName(span: MastraExportedSpan): string {\n const operationName = getOperation(span.type)?.operationName ?? span.type;\n const identifier = getSpanIdentifier(span);\n\n return identifier ? `${operationName} ${identifier}` : operationName;\n}\n\nfunction getSpanIdentifier(span: MastraExportedSpan): string | undefined {\n if (span.type === 'classifier_evaluation') {\n return span.attributes?.modelId;\n }\n if (MODEL_SPAN_TYPES.has(span.type) || span.type === 'rag_embedding') {\n return span.attributes?.model;\n }\n return span.entityName ?? span.entityId;\n}\n\nfunction serialize(value: unknown): string | undefined {\n if (value === undefined || value === null) {\n return undefined;\n }\n return typeof value === 'string' ? value : stringify(value);\n}\n\nfunction positive(value: number | undefined): number | undefined {\n return value !== undefined && value > 0 ? value : undefined;\n}\n\nexport function getUsageAttributes(usage: MastraUsageStats | undefined): SpanAttributes {\n if (!usage) {\n return {};\n }\n\n const inputTokens = usage.inputTokens;\n const outputTokens = usage.outputTokens;\n // Mastra only reports `totalTokens` for some providers, so derive it when both halves are known.\n const totalTokens =\n usage.totalTokens ??\n (inputTokens !== undefined || outputTokens !== undefined ? (inputTokens ?? 0) + (outputTokens ?? 0) : undefined);\n\n return {\n [GEN_AI_USAGE_INPUT_TOKENS]: inputTokens,\n [GEN_AI_USAGE_OUTPUT_TOKENS]: outputTokens,\n [GEN_AI_USAGE_TOTAL_TOKENS]: totalTokens,\n // Mastra reports these as 0 for providers that don't cache or reason.\n [GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]: positive(usage.inputDetails?.cacheRead),\n [GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]: positive(usage.inputDetails?.cacheWrite),\n [GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]: positive(usage.outputDetails?.reasoning),\n };\n}\n\nconst USAGE_ATTRIBUTE_KEYS = [\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n] as const;\n\nfunction addTokenCounts(\n left: SpanAttributeValue | undefined,\n right: SpanAttributeValue | undefined,\n): number | undefined {\n const a = typeof left === 'number' ? left : undefined;\n const b = typeof right === 'number' ? right : undefined;\n if (a === undefined && b === undefined) {\n return undefined;\n }\n return (a ?? 0) + (b ?? 0);\n}\n\n/** Sum usage across generations. `setAttributes(undefined)` would drop the previous total. */\nexport function mergeUsageAttributes(existing: SpanAttributes, incoming: SpanAttributes): SpanAttributes {\n const merged: SpanAttributes = {};\n for (const key of USAGE_ATTRIBUTE_KEYS) {\n const value = addTokenCounts(existing[key], incoming[key]);\n if (value !== undefined) {\n merged[key] = value;\n }\n }\n return merged;\n}\n\n/** Convention attributes only. Called on start and end — Mastra fills fields progressively. */\nexport function getSpanAttributes(span: MastraExportedSpan, options: AttributeRecordingOptions): SpanAttributes {\n const operationName = getOperation(span.type)?.operationName;\n\n const attributes: SpanAttributes = {\n [GEN_AI_OPERATION_NAME]: operationName,\n };\n\n if (AGENT_SPAN_TYPES.has(span.type)) {\n addAgentAttributes(attributes, span, options);\n }\n\n if (MODEL_SPAN_TYPES.has(span.type) || span.type === 'rag_embedding') {\n addModelAttributes(attributes, span, options);\n }\n\n if (TOOL_SPAN_TYPES.has(span.type)) {\n addToolAttributes(attributes, span, options);\n }\n\n if (span.type === 'classifier_evaluation') {\n addEvaluationAttributes(attributes, span);\n }\n\n if (span.errorInfo) {\n attributes[ERROR_TYPE] = span.errorInfo.name ?? span.errorInfo.id;\n }\n\n return attributes;\n}\n\nfunction addAgentAttributes(\n attributes: SpanAttributes,\n span: MastraExportedSpan,\n options: AttributeRecordingOptions,\n): void {\n const attrs = span.attributes ?? {};\n const name = span.entityName ?? span.entityId;\n\n attributes[GEN_AI_AGENT_NAME] = name;\n attributes[GEN_AI_PIPELINE_NAME] = name;\n attributes[GEN_AI_TOOL_DEFINITIONS] = serialize(attrs.availableTools);\n\n if (options.recordInputs) {\n // `prompt` is Mastra's legacy alias for the system prompt.\n attributes[GEN_AI_SYSTEM_INSTRUCTIONS] = attrs.instructions ?? attrs.prompt;\n attributes[GEN_AI_INPUT_MESSAGES] = serialize(span.input);\n }\n if (options.recordOutputs) {\n attributes[GEN_AI_OUTPUT_MESSAGES] = serialize(span.output);\n // oxlint-disable-next-line typescript/no-deprecated -- still emitted by the other AI integrations\n attributes[GEN_AI_RESPONSE_TEXT] = responseText(span.output);\n }\n}\n\nfunction addModelAttributes(\n attributes: SpanAttributes,\n span: MastraExportedSpan,\n options: AttributeRecordingOptions,\n): void {\n const attrs = span.attributes ?? {};\n const parameters = attrs.parameters ?? {};\n\n attributes[GEN_AI_REQUEST_MODEL] = attrs.model;\n attributes[GEN_AI_PROVIDER_NAME] = attrs.provider;\n attributes[GEN_AI_RESPONSE_MODEL] = attrs.responseModel;\n attributes[GEN_AI_RESPONSE_ID] = attrs.responseId;\n attributes[GEN_AI_RESPONSE_STREAMING] = attrs.streaming;\n attributes[GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK] = attrs.completionStartTime\n ? (attrs.completionStartTime.getTime() - span.startTime.getTime()) / 1000\n : undefined;\n attributes[GEN_AI_RESPONSE_FINISH_REASONS] = attrs.finishReason ? JSON.stringify([attrs.finishReason]) : undefined;\n attributes[GEN_AI_AGENT_NAME] = span.entityName;\n\n attributes[GEN_AI_REQUEST_TEMPERATURE] = parameters.temperature;\n attributes[GEN_AI_REQUEST_MAX_TOKENS] = parameters.maxOutputTokens;\n attributes[GEN_AI_REQUEST_TOP_P] = parameters.topP;\n attributes[GEN_AI_REQUEST_TOP_K] = parameters.topK;\n attributes[GEN_AI_REQUEST_PRESENCE_PENALTY] = parameters.presencePenalty;\n attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY] = parameters.frequencyPenalty;\n attributes[GEN_AI_REQUEST_SEED] = parameters.seed;\n attributes[GEN_AI_REQUEST_STOP_SEQUENCES] = parameters.stopSequences;\n\n Object.assign(attributes, getUsageAttributes(attrs.usage));\n\n if (options.recordInputs) {\n attributes[GEN_AI_INPUT_MESSAGES] = serialize(span.input);\n }\n if (options.recordOutputs) {\n attributes[GEN_AI_OUTPUT_MESSAGES] = serialize(span.output);\n // oxlint-disable-next-line typescript/no-deprecated -- still emitted by the other AI integrations\n attributes[GEN_AI_RESPONSE_TEXT] = responseText(span.output);\n }\n}\n\nfunction addToolAttributes(\n attributes: SpanAttributes,\n span: MastraExportedSpan,\n options: AttributeRecordingOptions,\n): void {\n const attrs = span.attributes ?? {};\n\n attributes[GEN_AI_TOOL_NAME] = span.entityName ?? span.entityId;\n attributes[GEN_AI_TOOL_DESCRIPTION] = attrs.toolDescription;\n\n if (options.recordInputs) {\n attributes[GEN_AI_TOOL_CALL_ARGUMENTS] = serialize(span.input);\n }\n if (options.recordOutputs) {\n attributes[GEN_AI_TOOL_CALL_RESULT] = serialize(span.output);\n }\n}\n\n/** Mastra's `Classifier` sets no input or output on this span, so only the model and usage are known. */\nfunction addEvaluationAttributes(attributes: SpanAttributes, span: MastraExportedSpan): void {\n const attrs = span.attributes ?? {};\n\n attributes[GEN_AI_REQUEST_MODEL] = attrs.modelId;\n attributes[GEN_AI_PROVIDER_NAME] = attrs.provider;\n Object.assign(attributes, getUsageAttributes(attrs.usage));\n}\n\nfunction responseText(output: unknown): string | undefined {\n if (typeof output === 'string') {\n return output;\n }\n if (output && typeof output === 'object' && 'text' in output && typeof output.text === 'string') {\n return output.text;\n }\n return undefined;\n}\n","import type { Span } from '@sentry/core';\nimport type { MastraExportedSpan, MastraSpanOutputProcessor } from './types';\n\n/**\n * Links a `Classifier.evaluate()` call to the Sentry span the exporter opens for its\n * `classifier_evaluation` span. Mastra's span carries no input or output, so the integration adds\n * them from the call. Mastra ends its span before `evaluate()` returns the answers, so the exporter\n * leaves the Sentry span open and the integration ends it once the call settles.\n */\nexport interface ClassifierEvaluationCall {\n span?: Span;\n /** Mastra's span and the processors of its observability instance, to filter the call's data. */\n mastraSpan?: MastraExportedSpan;\n spanOutputProcessors?: MastraSpanOutputProcessor[];\n /** The recording options of the exporter that opened the span, so the call's data follows them. */\n recordInputs?: boolean;\n recordOutputs?: boolean;\n /** Ends the span at Mastra's end time, set when Mastra ended its span before the call settled. */\n end?: () => void;\n settled?: boolean;\n}\n\n// Mastra emits `span_started` synchronously inside `evaluate()`, before its first `await`, so at\n// most one call is ever in this window.\nlet startingCall: ClassifierEvaluationCall | undefined;\n\nexport function setStartingClassifierEvaluation(call: ClassifierEvaluationCall | undefined): void {\n startingCall = call;\n}\n\nexport function takeStartingClassifierEvaluation(): ClassifierEvaluationCall | undefined {\n const call = startingCall;\n startingCall = undefined;\n return call;\n}\n\n/**\n * Run the call's data through Mastra's span output processors (for example its default\n * `SensitiveDataFilter`), as Mastra does for the input and output of its own spans. Returns `undefined`\n * when a processor drops the span or throws, so unfiltered data is never recorded.\n */\nexport function processClassifierEvaluationData(\n call: ClassifierEvaluationCall,\n data: { input?: unknown; output?: unknown },\n): { input?: unknown; output?: unknown } | undefined {\n let span: MastraExportedSpan | undefined = { ...call.mastraSpan, ...data } as MastraExportedSpan;\n for (const processor of call.spanOutputProcessors ?? []) {\n try {\n span = processor.process(span);\n } catch {\n return undefined;\n }\n if (!span) {\n return undefined;\n }\n }\n return span;\n}\n","import type { Span } from '@sentry/core';\nimport { LRUMap } from '@sentry/core';\nimport { MAX_TRACKED_MASTRA_SPANS } from './constants';\n\n/**\n * Maps a Mastra span id to the Sentry span the exporter opened for it, so the `executeWithContext`\n * channel subscriber can make that span active for the operation's work (see `integrations/mastra.ts`).\n *\n * Keyed by Mastra span id (globally unique), so it works across multiple `Mastra` instances / exporters\n * — each registers and unregisters its own spans. It's an `LRUMap` rather than a plain `Map` so the\n * process-wide table stays bounded even if an `unregister` is ever missed (a dropped entry only means a\n * nested span won't reparent — it degrades, it can't leak).\n */\nconst spansByMastraId = new LRUMap<string, Span>(MAX_TRACKED_MASTRA_SPANS);\n\nexport function registerMastraSpan(mastraId: string, span: Span): void {\n spansByMastraId.set(mastraId, span);\n}\n\nexport function unregisterMastraSpan(mastraId: string): void {\n spansByMastraId.remove(mastraId);\n}\n\nexport function getSentrySpanForMastraId(mastraId: string): Span | undefined {\n return spansByMastraId.get(mastraId);\n}\n","import type { Span, SpanTimeInput } from '@sentry/core';\nimport {\n debug,\n flush as sentryFlush,\n getActiveSpan,\n getClient,\n LRUMap,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n timestampInSeconds,\n} from '@sentry/core';\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_RESPONSE_MODEL,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type { GenAiSpanHooks, GenAiSpanResult } from '../core/span-hooks';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { GenAiCallOptions } from '../core/utils';\nimport { resolveGenAiCallRecording } from '../core/utils';\nimport {\n getOperation,\n getSpanAttributes,\n getSpanName,\n getUsageAttributes,\n isExportedSpanType,\n mergeUsageAttributes,\n type AttributeRecordingOptions,\n type SpanAttributes,\n} from './utils';\nimport {\n AGENT_SPAN_TYPES,\n MASTRA_EXPORTER_BRAND,\n MASTRA_EXPORTER_NAME,\n MASTRA_ORIGIN,\n MAX_TRACKED_MASTRA_SPANS,\n MODEL_SPAN_TYPES,\n} from './constants';\nimport type { ClassifierEvaluationCall } from './classifier-evaluation';\nimport { takeStartingClassifierEvaluation } from './classifier-evaluation';\nimport { registerMastraSpan, unregisterMastraSpan } from './span-registry';\nimport type {\n MastraExportedSpan,\n MastraExporterInitOptions,\n MastraObservabilityExporter,\n MastraSpanOutputProcessor,\n MastraSpanType,\n MastraTracingEvent,\n} from './types';\n\n/** The span that `recordInputs`/`recordOutputs` decide on, and that the span hooks get. */\nexport interface MastraCallInfo {\n /** The Mastra span as exported, when it starts. */\n span: MastraExportedSpan;\n}\n\n/**\n * `recordInputs`/`recordOutputs` and `onSpanStart` run when the exporter receives the start of a Mastra\n * span, and `onSpanEnd` when it receives its end, not in the async context of the code that started it.\n * `onSpanEnd` gets the Mastra span as exported when it ends, with its output, unless it failed or the\n * exporter ended it early, on shutdown or when too many spans are open at once.\n */\nexport type MastraExporterOptions = GenAiCallOptions<MastraCallInfo> &\n GenAiSpanHooks<MastraCallInfo, MastraExportedSpan>;\n\ninterface TrackedSpan {\n span: Span;\n call: MastraCallInfo;\n spanType: MastraSpanType;\n usage: SpanAttributes;\n recordingOptions: AttributeRecordingOptions;\n evaluation?: ClassifierEvaluationCall;\n}\n\nconst FLUSH_TIMEOUT_MS = 2000;\n\n/** Bound on the skipped-span parent walk; a cyclic chain from Mastra would otherwise hang the process. */\nconst MAX_PARENT_WALK_DEPTH = 100;\n\n/**\n * Mastra `ObservabilityExporter` that turns tracing events into Sentry spans.\n *\n * Never calls `Sentry.init()` / `Sentry.close()` — the community `@mastra/sentry` package does both\n * and replaces the app's client. No `@mastra/*` or `node:` imports.\n */\nexport class SentryMastraExporter implements MastraObservabilityExporter {\n public name = MASTRA_EXPORTER_NAME;\n\n public readonly [MASTRA_EXPORTER_BRAND] = true;\n\n private readonly _spans = new LRUMap<string, TrackedSpan>(MAX_TRACKED_MASTRA_SPANS);\n /**\n * Dropped span id -> parent id, for re-parenting descendants. A dropped span with no parent maps to\n * its own id: `LRUMap.remove` only deletes truthy values, so an empty-string sentinel would never be\n * evicted and would eventually fill the map, while a self-reference can never be a real parent id.\n */\n private readonly _skipped = new LRUMap<string, string>(MAX_TRACKED_MASTRA_SPANS);\n private readonly _options: MastraExporterOptions;\n private _spanOutputProcessors: MastraSpanOutputProcessor[] = [];\n\n public constructor(options: MastraExporterOptions = {}) {\n this._options = options;\n }\n\n /** Called by Mastra with the config of the observability instance this exporter belongs to. */\n public init(options: MastraExporterInitOptions): void {\n this._spanOutputProcessors = options.config?.spanOutputProcessors ?? [];\n }\n\n /** Mastra's interface is async; the work is synchronous. */\n public async exportTracingEvent(event: MastraTracingEvent): Promise<void> {\n if (!getClient()) {\n return;\n }\n\n try {\n this._handleEvent(event);\n } catch (error) {\n DEBUG_BUILD && debug.error('[Mastra] failed to export tracing event', error);\n }\n }\n\n /** Flush without closing the client — the app still owns it. */\n public async flush(): Promise<void> {\n await sentryFlush(FLUSH_TIMEOUT_MS);\n }\n\n /** End open spans, then flush. Does not close the Sentry client. */\n public async shutdown(): Promise<void> {\n for (const id of this._spans.keys()) {\n unregisterMastraSpan(id);\n }\n for (const tracked of this._spans.values()) {\n this._endSpan(tracked, {});\n }\n this._spans.clear();\n this._skipped.clear();\n await this.flush();\n }\n\n private _handleEvent(event: MastraTracingEvent): void {\n const span = event.exportedSpan;\n\n if (span.isEvent) {\n return;\n }\n\n // Unmapped types are recorded so children re-parent onto a surviving ancestor.\n if (!isExportedSpanType(span.type)) {\n if (event.type === 'span_started') {\n this._skipped.set(span.id, span.parentSpanId ?? span.id);\n } else if (event.type === 'span_ended') {\n this._skipped.remove(span.id);\n }\n return;\n }\n\n switch (event.type) {\n case 'span_started':\n this._onSpanStarted(span);\n break;\n case 'span_updated':\n this._onSpanUpdated(span);\n break;\n case 'span_ended':\n this._onSpanEnded(span);\n break;\n }\n }\n\n private _onSpanStarted(span: MastraExportedSpan): void {\n // Per span, not in the constructor: the exporter can be constructed before `Sentry.init()`, when\n // `dataCollection.genAI` does not exist yet.\n const call: MastraCallInfo = { span };\n const recordingOptions = resolveGenAiCallRecording(this._options, call);\n const parentId = this._resolveParentId(span.parentSpanId);\n const parentSpan = parentId ? this._spans.get(parentId)?.span : undefined;\n const activeSpan = getActiveSpan();\n\n const sentrySpan = startInactiveSpan({\n name: getSpanName(span),\n startTime: span.startTime,\n // Prefer the Mastra parent so the tree stays together; else the active request span.\n parentSpan: parentSpan ?? activeSpan,\n attributes: {\n ...getSpanAttributes(span, recordingOptions),\n // Only on start, so the id from `Sentry.setConversationId()`, applied on `spanStart`, is kept.\n [GEN_AI_CONVERSATION_ID]: span.attributes?.conversationId ?? span.metadata?.threadId,\n [SENTRY_OP]: getOperation(span.type)?.op,\n [SENTRY_ORIGIN]: MASTRA_ORIGIN,\n },\n });\n runGenAiSpanStart(this._options, sentrySpan, call);\n\n const evaluation = span.type === 'classifier_evaluation' ? takeStartingClassifierEvaluation() : undefined;\n if (evaluation) {\n Object.assign(evaluation, {\n span: sentrySpan,\n mastraSpan: span,\n spanOutputProcessors: this._spanOutputProcessors,\n recordInputs: recordingOptions.recordInputs,\n recordOutputs: recordingOptions.recordOutputs,\n });\n }\n\n this._trackSpan(span.id, { span: sentrySpan, call, spanType: span.type, usage: {}, recordingOptions, evaluation });\n }\n\n /** Track a started span, ending any Sentry span that would otherwise be dropped without `end()`. */\n private _trackSpan(id: string, tracked: TrackedSpan): void {\n // A duplicate `span_started` would otherwise overwrite the entry and leak its Sentry span.\n this._endTracked(id);\n\n // `LRUMap.set` evicts the oldest entry once the map is full, dropping that span without ending it.\n if (this._spans.size >= MAX_TRACKED_MASTRA_SPANS) {\n const oldestId = this._spans.keys()[0];\n if (oldestId !== undefined) {\n this._endTracked(oldestId);\n }\n }\n\n this._spans.set(id, tracked);\n // Let the `executeWithContext` channel subscriber find this Sentry span by Mastra span id.\n registerMastraSpan(id, tracked.span);\n }\n\n private _endTracked(id: string): void {\n const tracked = this._removeTracked(id);\n if (tracked) {\n this._endSpan(tracked, {});\n }\n }\n\n private _endSpan(tracked: TrackedSpan, result: GenAiSpanResult<MastraExportedSpan>, endTime?: SpanTimeInput): void {\n runGenAiSpanEnd(this._options, tracked.span, tracked.call, result);\n tracked.span.end(endTime);\n }\n\n /** Remove a tracked span and keep the id→span registry in lockstep. */\n private _removeTracked(id: string): TrackedSpan | undefined {\n unregisterMastraSpan(id);\n return this._spans.remove(id);\n }\n\n private _onSpanUpdated(span: MastraExportedSpan): void {\n const tracked = this._spans.get(span.id);\n if (tracked) {\n tracked.span.setAttributes(getSpanAttributes(span, tracked.recordingOptions));\n }\n }\n\n private _onSpanEnded(span: MastraExportedSpan): void {\n const tracked = this._spans.get(span.id);\n if (!tracked) {\n DEBUG_BUILD && debug.warn(`[Mastra] no Sentry span open for ended span ${span.id} (${span.name})`);\n return;\n }\n\n const { span: sentrySpan, recordingOptions } = tracked;\n sentrySpan.setAttributes(getSpanAttributes(span, recordingOptions));\n sentrySpan.updateName(getSpanName(span));\n\n if (MODEL_SPAN_TYPES.has(span.type)) {\n this._rollUpToParentAgent(span);\n }\n\n if (span.errorInfo) {\n // Status only — capturing here would duplicate the app's own report with a worse stack.\n sentrySpan.setStatus({ code: SPAN_STATUS_ERROR, message: span.errorInfo.message });\n }\n\n const result = span.errorInfo ? { error: span.errorInfo } : { response: span };\n const { evaluation } = tracked;\n if (evaluation && !evaluation.settled) {\n // The integration adds the call's input and answers once `evaluate()` settles, then ends the span.\n const endTime = span.endTime ?? timestampInSeconds();\n evaluation.end = () => this._endSpan(tracked, result, endTime);\n } else {\n this._endSpan(tracked, result, span.endTime);\n }\n this._removeTracked(span.id);\n }\n\n /** Copy model/usage onto the parent agent so the AI Agents view shows totals. */\n private _rollUpToParentAgent(span: MastraExportedSpan): void {\n const parentId = this._resolveParentId(span.parentSpanId);\n const parent = parentId ? this._spans.get(parentId) : undefined;\n if (!parent || !AGENT_SPAN_TYPES.has(parent.spanType)) {\n return;\n }\n\n const attrs = span.attributes ?? {};\n const rolled = mergeUsageAttributes(parent.usage, getUsageAttributes(attrs.usage));\n parent.usage = rolled;\n const model = attrs.responseModel ?? attrs.model;\n if (model !== undefined) {\n rolled[GEN_AI_RESPONSE_MODEL] = model;\n }\n parent.span.setAttributes(rolled);\n }\n\n /** Nearest exported ancestor of a dropped span. */\n private _resolveParentId(parentSpanId: string | undefined): string | undefined {\n let current = parentSpanId;\n for (let depth = 0; current; depth++) {\n const parentOfSkipped = this._skipped.get(current);\n if (parentOfSkipped === undefined) {\n return current;\n }\n if (depth >= MAX_PARENT_WALK_DEPTH) {\n DEBUG_BUILD && debug.warn('[Mastra] gave up walking a parent chain that is too deep or cyclic');\n return undefined;\n }\n // Self-reference marks a dropped span with no parent; stop and fall back to the active span.\n current = parentOfSkipped === current ? undefined : parentOfSkipped;\n }\n return undefined;\n }\n}\n","import { GLOBAL_OBJ } from '@sentry/core';\n\ntype GlobalWithRuntimes = typeof GLOBAL_OBJ & { Bun?: unknown; Deno?: unknown };\n\n/** Whether the SDK runs in Bun. */\nexport function isBun(): boolean {\n return typeof (GLOBAL_OBJ as GlobalWithRuntimes).Bun !== 'undefined';\n}\n\n/** Whether the SDK runs in Deno. */\nexport function isDeno(): boolean {\n return typeof (GLOBAL_OBJ as GlobalWithRuntimes).Deno !== 'undefined';\n}\n\n/** Whether the SDK runs in Cloudflare Workers. */\nexport function isCloudflareWorkers(): boolean {\n return GLOBAL_OBJ.navigator?.userAgent === 'Cloudflare-Workers';\n}\n","import { consoleSandbox, debug, GLOBAL_OBJ } from '@sentry/core';\nimport { isBun } from '../utils/runtime';\n\n/**\n * The module names (e.g. `mysql`, `@hapi/hapi`) orchestrion has already injected\n * into this process — from the runtime `--import` hook (`runtime`) and/or the\n * snippets a bundler transform spliced into each transformed module (`bundler`).\n * Channel-based integrations use it to decide whether to subscribe now (their\n * module is already loaded) or wait for the module-injected event.\n *\n * The `instanceof Set` guard is runtime safety, not typing: a banner from\n * another SDK copy or version may have written a non-Set flag here.\n */\nexport function getOrchestrionInjectedModules(): string[] {\n const { runtime, bundler } = GLOBAL_OBJ.__SENTRY_ORCHESTRION__ ?? {};\n return [...(runtime ?? []), ...(bundler instanceof Set ? bundler : [])];\n}\n\n/**\n * Verifies that the diagnostics channels have been injected either by the\n * runtime `--import` hook (or init-time registration), a bundler plugin, or\n * both, and warns if not. When at least one injector is active, logs for each\n * mechanism whether it hooked (a defined list, even empty, means it did) and\n * which libraries it injected. For the bundler path, the entry banner ensures\n * an empty `Set` at boot; module names arrive as each transformed module is\n * evaluated, so an empty set can also just mean none has loaded yet.\n *\n * Both injectors being active at once is fine: they operate on disjoint module\n * sets (a module is either loaded through Node's loader and transformed by the\n * runtime hook, or inlined by the bundler and transformed by the plugin), so\n * a single module can't be double-wrapped. A hybrid setup, with some deps\n * external and runtime-instrumented, others bundled and plugin-instrumented,\n * is fine.\n */\nexport function detectOrchestrionSetup(): void {\n const marker = GLOBAL_OBJ.__SENTRY_ORCHESTRION__ ?? {};\n const { runtime, bundler, channelIntegrations } = marker;\n\n if (!runtime && !bundler) {\n if (channelIntegrations && isBun()) {\n if (!marker.warnedBunRunNotInjected) {\n marker.warnedBunRunNotInjected = true;\n consoleSandbox(() => {\n // oxlint-disable-next-line no-console\n console.warn(\n '[Sentry] No diagnostics-channel injection detected. Channel-based integrations will not record ' +\n 'spans or capture errors. On Bun 1.4.6 or later, run your app with `bun --preload @sentry/bun/import`. ' +\n 'Or build your app with `@sentry/bun/plugin`.',\n );\n });\n }\n return;\n }\n\n debug.warn(\n '[Sentry] No diagnostics-channel injection detected. Channel-based integrations ' +\n 'will not record spans. Make sure the diagnostics channels are injected ' +\n 'via the runtime `--import` hook or a bundler plugin before the instrumented modules load.',\n );\n return;\n }\n\n debug.log(\n runtime\n ? `[Sentry] Runtime hook registered, injected libraries=${JSON.stringify(runtime)}`\n : '[Sentry] Runtime hook not registered',\n );\n debug.log(\n bundler\n ? `[Sentry] Bundler plugin ran, injected libraries=${JSON.stringify(\n bundler instanceof Set ? [...bundler] : bundler,\n )}`\n : '[Sentry] Bundler plugin did not run',\n );\n}\n","import type { Scope, Span } from '@sentry/core';\nimport { getCurrentScope } from '@sentry/core';\nimport type { GenAiSpanHooks, GenAiSpanResult } from '../core/span-hooks';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { GenAiCallOptions, GenAiOptions } from '../core/utils';\nimport { resolveGenAiCallRecording, resolveRecordingOption } from '../core/utils';\nimport type { PiAiCallInfo, PiAssistantMessage } from './types';\n\nconst DRIVER_KEY = 'piAiDriver';\n\n/** The options of the integration driving pi-ai, bound to its call info. */\nexport interface PiAiDriver {\n recording: () => GenAiOptions;\n onSpanStart: (span: Span) => void;\n onSpanEnd: (span: Span, result: GenAiSpanResult<PiAssistantMessage>) => void;\n}\n\n/**\n * Apply the recording options and span hooks of an integration that sends its model calls through\n * pi-ai, such as Flue, to the `gen_ai.chat` spans of the requests sent under `scope`. Options and\n * hooks that are functions get `call`.\n */\nexport function setPiAiDriverOptions<TCall>(\n scope: Scope,\n options: GenAiCallOptions<TCall> & GenAiSpanHooks<TCall, PiAssistantMessage>,\n call: TCall,\n): void {\n const driver: PiAiDriver = {\n recording: () => ({\n recordInputs: resolveRecordingOption(options.recordInputs, call),\n recordOutputs: resolveRecordingOption(options.recordOutputs, call),\n }),\n onSpanStart: span => runGenAiSpanStart(options, span, call),\n onSpanEnd: (span, result) => runGenAiSpanEnd(options, span, call, result),\n };\n scope.setSDKProcessingMetadata({ [DRIVER_KEY]: driver });\n}\n\n/** The integration driving the pi-ai requests sent from the current scope, if any. */\nexport function getPiAiDriver(): PiAiDriver | undefined {\n return getCurrentScope().getScopeData().sdkProcessingMetadata[DRIVER_KEY] as PiAiDriver | undefined;\n}\n\n/**\n * The recording options of a pi-ai request, read when it starts: its response can settle outside the\n * scope it was sent from. An explicit `false` on either integration, or from either one's function,\n * keeps the content out, since an opt-out must not depend on which integration it was set on.\n * Otherwise the integration driving pi-ai comes first, then `piAiIntegration`, then\n * `dataCollection.genAI`.\n */\nexport function resolvePiAiRecordingOptions(\n options: GenAiCallOptions<PiAiCallInfo>,\n call: PiAiCallInfo,\n driver = getPiAiDriver(),\n): Required<GenAiOptions> {\n const driverRecording = driver?.recording();\n const own = {\n recordInputs: resolveRecordingOption(options.recordInputs, call),\n recordOutputs: resolveRecordingOption(options.recordOutputs, call),\n };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(own, call);\n return {\n recordInputs: own.recordInputs !== false && (driverRecording?.recordInputs ?? recordInputs),\n recordOutputs: own.recordOutputs !== false && (driverRecording?.recordOutputs ?? recordOutputs),\n };\n}\n","export const FLUE_INTEGRATION_NAME = 'Flue' as const;\n\nexport const FLUE_MODULE_NAME = '@flue/runtime';\n\nexport const FLUE_ORIGIN = 'auto.ai.flue';\n\n/**\n * Identifies our registration in Flue's keyed instrumentation registry.\n *\n * `key` is optional, but without one there is no protection against registering twice: Flue\n * deduplicates on object identity, and `createFlueInstrumentation()` returns a new object each\n * call, so a second `instrument()` would silently add a second observer and interceptor and\n * duplicate every span.\n *\n * With a key, Flue handles the repeat itself — it throws `InstrumentationAlreadyInstalledError` in\n * production, and in dev disposes the previous registration and swaps in the new one, which is what\n * stops `vite dev` from stacking observers across reloads.\n */\nexport const FLUE_INSTRUMENTATION_KEY = Symbol.for('sentry.flue.instrumentation');\n\n/**\n * The Flue execution operations we act on.\n *\n * Only `AGENT` is spanned from the interceptor, and only at the outermost depth: its operation nests\n * inside itself once per submission. `TOOL` is intercepted to make the tool span `observe` opened\n * active, and `MODEL` to hand the conversation to the pi-ai integration, which spans the model call.\n */\nexport const FLUE_OPERATION = {\n AGENT: 'agent',\n MODEL: 'model',\n TOOL: 'tool',\n} as const;\n\n/**\n * Cap on tracked tool spans and admissions, matching `MAX_TRACKED_MASTRA_SPANS`. Both maps are keyed\n * off an id that is only removed when the matching end observation arrives; a run that is abandoned\n * mid-turn never emits one, so without a cap the map grows for the lifetime of the process.\n */\nexport const MAX_TRACKED_FLUE_SPANS = 1000;\n","import { isObjectLike, stringify } from '@sentry/core';\nimport type { GenAiMessage, GenAiMessagePart } from '../types';\n\n/**\n * Map pi-ai messages (`@earendil-works/pi-ai`, which Flue and pi-durable send) to the gen_ai\n * conventions. Sentry renders neither pi-ai's `toolResult` role nor its `toolCall` parts.\n *\n * System messages are left out: their prompt belongs in `gen_ai.system_instructions`. Messages with\n * a role the conventions do not have are left out too.\n */\nexport function piAiMessagesToGenAiMessages(messages: unknown): GenAiMessage[] {\n if (!Array.isArray(messages)) {\n return [];\n }\n\n const mapped: GenAiMessage[] = [];\n for (const message of messages) {\n if (\n !isObjectLike(message) ||\n (message.role !== 'user' && message.role !== 'assistant' && message.role !== 'toolResult')\n ) {\n continue;\n }\n\n if (message.role === 'toolResult') {\n mapped.push({\n role: 'tool',\n parts: [\n {\n type: 'tool_call_response',\n id: message.toolCallId,\n name: message.toolName,\n result: piAiContentToString(message.content),\n },\n ],\n });\n continue;\n }\n\n const parts = piAiContentToParts(message.content);\n if (parts.length) {\n mapped.push({ role: message.role, parts });\n }\n }\n return mapped;\n}\n\n/** The `gen_ai.output.messages` entry of a pi-ai assistant message, or `undefined` when it has no content. */\nexport function piAiAssistantMessageToGenAiMessage(message: unknown, finishReason?: string): GenAiMessage | undefined {\n const parts = isObjectLike(message) ? piAiContentToParts(message.content) : [];\n if (!parts.length) {\n return undefined;\n }\n return { role: 'assistant', parts, ...(finishReason ? { finish_reason: finishReason } : {}) };\n}\n\n/** pi-ai names a tool-calling stop `toolUse`; the conventions call it `tool_call`. */\nexport function piAiFinishReason(stopReason: unknown): string | undefined {\n if (typeof stopReason !== 'string' || !stopReason) {\n return undefined;\n }\n return stopReason === 'toolUse' ? 'tool_call' : stopReason;\n}\n\n/** The request fields of a pi-ai `Context` that carry the system prompt and the tools. */\nexport interface PiAiContext {\n systemPrompt?: string;\n messages?: unknown;\n tools?: unknown;\n}\n\n/**\n * The system prompt a pi-ai request sends. pi-durable sends it as positional system messages with\n * `sections` instead of `systemPrompt`, so the messages are replayed like pi-ai's own\n * `getCurrentSystemPrompt` does: `content` is appended, `sections` are patched by name.\n */\nexport function piAiSystemInstructions(context: PiAiContext): string | undefined {\n const content: string[] = [];\n const sections = new Map<string, string>();\n for (const message of piAiSystemMessages(context)) {\n const text = piAiContentText(message.content);\n if (text) {\n content.push(text);\n }\n if (isObjectLike(message.sections)) {\n for (const [name, value] of Object.entries(message.sections)) {\n if (value === null) {\n sections.delete(name);\n } else if (typeof value === 'string') {\n sections.set(name, value);\n }\n }\n }\n }\n return [content.join('\\n\\n'), ...sections.values()].filter(Boolean).join('\\n\\n') || undefined;\n}\n\n/** The tools a pi-ai request offers, with `toolsAdded` and `toolsRemoved` replayed like pi-ai's `getCurrentTools`. */\nexport function piAiToolDefinitions(context: PiAiContext): unknown[] {\n const tools = new Map<string, unknown>();\n for (const message of piAiSystemMessages(context)) {\n for (const tool of Array.isArray(message.toolsRemoved) ? message.toolsRemoved : []) {\n if (isObjectLike(tool) && typeof tool.name === 'string') {\n tools.delete(tool.name);\n }\n }\n for (const tool of Array.isArray(message.toolsAdded) ? message.toolsAdded : []) {\n if (isObjectLike(tool) && typeof tool.name === 'string') {\n tools.set(tool.name, tool);\n }\n }\n }\n return [...tools.values()];\n}\n\n/** The system messages pi-ai sends, led by the one it builds from `systemPrompt` and `tools`. */\nfunction piAiSystemMessages(context: PiAiContext): Record<string, unknown>[] {\n const hasTools = Array.isArray(context.tools) && context.tools.length > 0;\n const leading =\n context.systemPrompt || hasTools\n ? [{ role: 'system', content: context.systemPrompt ?? '', toolsAdded: context.tools }]\n : [];\n const messages = Array.isArray(context.messages) ? context.messages : [];\n return [...leading, ...messages].filter(\n (message): message is Record<string, unknown> => isObjectLike(message) && message.role === 'system',\n );\n}\n\nfunction piAiContentText(content: unknown): string {\n if (typeof content === 'string') {\n return content;\n }\n return piAiContentToParts(content)\n .filter(part => part.type === 'text')\n .map(part => part.content)\n .join('\\n');\n}\n\n/** Text-only content as its text, joined the way pi-ai joins it; anything else as its mapped parts. */\nexport function piAiContentToString(content: unknown): string | undefined {\n const parts = piAiContentToParts(content);\n return parts.every(part => part.type === 'text') ? parts.map(part => part.content).join('\\n') : stringify(parts);\n}\n\nfunction piAiContentToParts(content: unknown): GenAiMessagePart[] {\n if (typeof content === 'string') {\n return content ? [{ type: 'text', content }] : [];\n }\n if (!Array.isArray(content)) {\n return [];\n }\n return content.map(piAiPartToGenAiPart).filter((part): part is GenAiMessagePart => part !== undefined);\n}\n\n/** An image is reported by its media type only: its `data` is base64, which the conventions require to be dropped. */\nfunction piAiPartToGenAiPart(part: unknown): GenAiMessagePart | undefined {\n if (!isObjectLike(part)) {\n return undefined;\n }\n\n switch (part.type) {\n case 'text':\n // An empty text block makes Sentry render the message as \"(no value)\" instead of its tool calls.\n return typeof part.text === 'string' && part.text.trim() ? { type: 'text', content: part.text } : undefined;\n case 'thinking':\n // A redacted thinking block carries an encrypted payload, not text.\n return typeof part.thinking === 'string' && part.thinking && !part.redacted\n ? { type: 'reasoning', content: part.thinking }\n : undefined;\n case 'toolCall':\n return { type: 'tool_call', id: part.id, name: part.name, arguments: stringify(part.arguments ?? {}, String) };\n case 'image':\n return { type: 'blob', mime_type: part.mimeType };\n default:\n // Part kinds we don't know yet render as JSON rather than disappearing.\n return { type: 'object', content: part };\n }\n}\n","import type { LRUMap, Span } from '@sentry/core';\nimport {\n captureException,\n isObjectLike,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n stringify,\n withActiveSpan,\n} from '@sentry/core';\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_OPERATION_NAME,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_NAME,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport type { GenAiSpanHooks } from '../core/span-hooks';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { GenAiCallOptions } from '../core/utils';\nimport { getGenAiSpanOp, resolveGenAiCallRecording } from '../core/utils';\nimport { piAiContentToString } from '../pi-ai/messages';\nimport { FLUE_ORIGIN, MAX_TRACKED_FLUE_SPANS } from './constants';\nimport type { FlueCallInfo, FlueErrorInfo, FlueEventContext, FlueObservation } from './types';\n\n/**\n * Turn and tool spans, keyed by the id of the work they cover. Bounded, because the key is only\n * removed when the matching end observation arrives and an abandoned stream never emits one.\n */\nexport type SpanTracker = LRUMap<string, Span>;\n\nconst TOOL_SPANS_RECORDING_OUTPUTS = new WeakSet<Span>();\nconst TOOL_SPAN_END_HOOKS = new WeakMap<Span, (observation: FlueObservation) => void>();\n\n/**\n * Store a span under `key`. Callers only reach this with a key the tracker does not hold, so the\n * one span at risk of being dropped without `end()` is the oldest entry, which `LRUMap.set` silently\n * evicts once the tracker is full.\n */\nfunction trackSpan(tracker: SpanTracker, key: string, span: Span): void {\n if (tracker.size >= MAX_TRACKED_FLUE_SPANS) {\n const oldestKey = tracker.keys()[0];\n if (oldestKey !== undefined) {\n tracker.remove(oldestKey)?.end();\n }\n }\n\n tracker.set(key, span);\n}\n\n/**\n * Report a failed tool as an error event.\n *\n * Flue catches whatever the tool threw and hands it back to the model as a tool result, so nothing\n * propagates for the SDK's global handlers to see: without this a throwing tool produces an errored\n * span and no issue at all. `errorInfo` carries the original name, message and stack, so rebuild an\n * `Error` from it rather than capturing the serialized shape.\n *\n * Tools only. A failed turn carries no `errorInfo` — a provider auth failure produces an errored\n * `chat` span and nothing to rebuild from — so there is no turn equivalent to capture.\n */\nfunction captureToolError(span: Span, errorInfo: FlueErrorInfo | undefined): void {\n if (!errorInfo) {\n return;\n }\n\n const error = new Error(errorInfo.message ?? 'Flue tool failed');\n error.name = errorInfo.name ?? errorInfo.type ?? 'Error';\n if (errorInfo.stack) {\n error.stack = errorInfo.stack;\n }\n\n // Captured under the operation's own span so the issue lands on the right trace, matching how the\n // Mastra integration attaches its captures.\n withActiveSpan(span, () => {\n // Handled: this is not a rejection observed on a tracing channel, where the handled state is\n // unknowable. Flue caught the throw and returned it to the model as a tool result, so it is\n // definitively handled and no global hook will ever see it.\n captureException(error, { mechanism: { handled: true, type: FLUE_ORIGIN } });\n });\n}\n\n/**\n * Tool spans hang off the agent invocation rather than the turn, matching how Flue's own\n * OpenTelemetry adapter projects them: siblings of `chat`, correlated to model output by tool call\n * id. Keyed by `toolCallId` so concurrent tool calls in one turn cannot cross-attribute.\n */\nexport function startToolSpan(\n observation: FlueObservation,\n context: FlueEventContext,\n toolSpans: SpanTracker,\n options: GenAiCallOptions<FlueCallInfo> & GenAiSpanHooks<FlueCallInfo, FlueObservation>,\n): void {\n const { toolCallId, toolName } = observation;\n if (!toolCallId || toolSpans.get(toolCallId)) {\n return;\n }\n\n const call: FlueCallInfo = { operation: 'execute_tool', observation, context };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n const span = startInactiveSpan({\n name: `execute_tool ${toolName ?? 'unknown'}`,\n op: getGenAiSpanOp('execute_tool'),\n attributes: {\n [SENTRY_ORIGIN]: FLUE_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'execute_tool',\n [GEN_AI_TOOL_NAME]: toolName,\n [GEN_AI_CONVERSATION_ID]: observation.conversationId,\n ...(recordInputs && observation.args !== undefined\n ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(observation.args) }\n : {}),\n },\n });\n // Again after start, so the Flue id wins over one from `Sentry.setConversationId()`, as on the agent and chat spans.\n if (observation.conversationId) {\n span.setAttribute(GEN_AI_CONVERSATION_ID, observation.conversationId);\n }\n if (recordOutputs) {\n TOOL_SPANS_RECORDING_OUTPUTS.add(span);\n }\n runGenAiSpanStart(options, span, call);\n TOOL_SPAN_END_HOOKS.set(span, end =>\n runGenAiSpanEnd(options, span, call, end.isError ? { response: end, error: end.errorInfo } : { response: end }),\n );\n trackSpan(toolSpans, toolCallId, span);\n}\n\nexport function endToolSpan(observation: FlueObservation, toolSpans: SpanTracker): void {\n const { toolCallId } = observation;\n const span = toolCallId ? toolSpans.get(toolCallId) : undefined;\n if (!span || !toolCallId) {\n return;\n }\n toolSpans.remove(toolCallId);\n\n if (TOOL_SPANS_RECORDING_OUTPUTS.has(span)) {\n const result = toolResultForModel(observation);\n if (result !== undefined) {\n span.setAttribute(GEN_AI_TOOL_CALL_RESULT, result);\n }\n }\n\n if (observation.isError) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n captureToolError(span, observation.errorInfo);\n }\n TOOL_SPAN_END_HOOKS.get(span)?.(observation);\n span.end();\n}\n\n/**\n * The result the model receives: Flue's `effectiveResult` when it has one, else the content blocks\n * of its harness-level `result` (`{ content, details }`, whose `details` payload is tool-specific).\n */\nfunction toolResultForModel(observation: FlueObservation): string | undefined {\n const { effectiveResult } = observation;\n if (effectiveResult !== undefined) {\n if (typeof effectiveResult === 'string') {\n return effectiveResult;\n }\n return Array.isArray(effectiveResult) ? piAiContentToString(effectiveResult) : stringify(effectiveResult);\n }\n const { result } = observation;\n if (isObjectLike(result) && Array.isArray(result.content)) {\n return piAiContentToString(result.content);\n }\n return result === undefined ? undefined : stringify(result);\n}\n","import type { Scope, Span } from '@sentry/core';\nimport {\n consoleSandbox,\n continueTrace,\n getActiveSpan,\n getDefaultIsolationScope,\n getIsolationScope,\n LRUMap,\n sentryTraceFromTraceparent,\n startNewTrace,\n startSpan,\n withActiveSpan,\n withScope,\n} from '@sentry/core';\nimport {\n GEN_AI_AGENT_NAME,\n GEN_AI_CONVERSATION_ID,\n GEN_AI_OPERATION_NAME,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport type { GenAiSpanHooks } from '../core/span-hooks';\nimport type { GenAiCallOptions } from '../core/utils';\nimport { getGenAiSpanOp } from '../core/utils';\nimport { getOrchestrionInjectedModules } from '../../orchestrion/detect';\nimport { piAiModuleNames } from '../../orchestrion/config/pi-ai';\nimport { setPiAiDriverOptions } from '../pi-ai/recording';\nimport type { PiAssistantMessage } from '../pi-ai/types';\nimport { isBun, isCloudflareWorkers, isDeno } from '../../utils/runtime';\nimport { withCleanScopes } from '../../utils/withCleanScopes';\nimport { FLUE_INSTRUMENTATION_KEY, FLUE_OPERATION, FLUE_ORIGIN, MAX_TRACKED_FLUE_SPANS } from './constants';\nimport type { SpanTracker } from './utils';\nimport { endToolSpan, startToolSpan } from './utils';\nimport type { FlueCallInfo, FlueInstrumentation, FlueObservation } from './types';\n\n/**\n * The span hooks run for the `gen_ai.chat` spans of the model calls, which pi-ai reports, and for the\n * tool spans. `onSpanEnd` gets the `AssistantMessage` of a model call, and the `tool` observation of a\n * tool call, whose `errorInfo` is also the `error` of a failed tool. A tool call that never ends, whose\n * span is ended when the tracker evicts it or Flue disposes the instrumentation, does not run `onSpanEnd`.\n */\nexport type FlueOptions = GenAiCallOptions<FlueCallInfo> &\n GenAiSpanHooks<FlueCallInfo, PiAssistantMessage | FlueObservation>;\n\ninterface Admission {\n isolationScope: Scope;\n span: Span | undefined;\n}\n\nlet checkedPiAiInstrumentation = false;\n\n/**\n * `instrument()` works without Sentry's module hook or bundler plugin, but the pi-ai integration that\n * spans Flue's model calls doesn't. Checked on the first model call, once pi-ai has loaded.\n */\nfunction warnIfPiAiNotInstrumented(): void {\n if (checkedPiAiInstrumentation) {\n return;\n }\n checkedPiAiInstrumentation = true;\n\n const injected = getOrchestrionInjectedModules();\n if (piAiModuleNames.some(name => injected.includes(name))) {\n return;\n }\n\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn(\n '[Sentry] Flue model calls are not being traced: `@earendil-works/pi-ai` was not instrumented, so ' +\n `Flue agents record agent and tool spans but no \\`gen_ai.chat\\` spans. ${getPiAiInstrumentationHint()}`,\n );\n });\n}\n\nfunction getPiAiInstrumentationHint(): string {\n if (isBun()) {\n return 'On Bun 1.4.6 or later, run your app with `bun --preload @sentry/bun/import app.ts`. Or build it with `sentryBunPlugin()` from `@sentry/bun/plugin`.';\n }\n if (isDeno()) {\n return 'Run your app with `deno run --preload=npm:@sentry/deno/import app.ts`.';\n }\n if (isCloudflareWorkers()) {\n return 'Add `sentryCloudflareVitePlugin()` from `@sentry/cloudflare/vite` to your Vite config.';\n }\n return 'Load Sentry with `--import`, for example `node --import ./instrument.mjs app.mjs`.';\n}\n\n/**\n * Flue's Node coordinator runs every submission from one long-lived claim loop, started by the\n * first admission and keeping that call's async context for the life of the process. Left alone,\n * every agent run lands in the trace of whichever request admitted the first one\n * (https://github.com/withastro/flue/issues/813).\n */\nfunction runInAdmissionContext<T>(admission: Admission | undefined, next: () => T): T {\n // Cloudflare runs each turn from a Durable Object alarm, which already starts a trace of its own,\n // so there is no leaked context to undo there.\n if (isCloudflareWorkers()) {\n return next();\n }\n if (!admission) {\n // Admitted by another process, replayed by idempotency key, or evicted: there is nothing to\n // restore, but the loop's context still belongs to an unrelated request.\n return withCleanScopes(getDefaultIsolationScope().clone(), () => startNewTrace(next));\n }\n return withCleanScopes(admission.isolationScope, () =>\n admission.span ? withActiveSpan(admission.span, next) : startNewTrace(next),\n );\n}\n\n/**\n * Build the object to hand to `instrument()` from `@flue/runtime`.\n *\n * The two callbacks own different halves of the result:\n *\n * - `interceptor` wraps agent execution, so the agent span is *active* for its duration and every\n * span opened underneath parents correctly.\n * - `observe` opens and closes the tool spans, and names the agent span.\n *\n * Model calls get no span here: Flue sends them through pi-ai, whose integration reports each one\n * as a `gen_ai.chat` span under the agent span.\n *\n * Tool arguments and results are gated on `recordInputs`/`recordOutputs`, which fall back to the\n * current client's `dataCollection.genAI` settings and are decided when each tool span starts. The\n * same options apply to the message content of the `gen_ai.chat` spans.\n */\nexport function createFlueInstrumentation(options: FlueOptions = {}): FlueInstrumentation {\n // Keyed by the agent operation's own id, which is what the observations carry. That keeps\n // concurrent runs apart and gives a delegated subagent its own span: Flue nests a second `agent`\n // operation inside the parent's for `task` delegation, and the nesting is not bounded at two.\n // A plain map: the entry is removed in a `finally`, so it is bounded by concurrent agent runs.\n const agentSpans = new Map<string, Span>();\n // Capped, unlike the above: these are keyed off ids that only a matching end observation removes.\n const toolSpans: SpanTracker = new LRUMap(MAX_TRACKED_FLUE_SPANS);\n // Capped: a submission admitted here but run by another process never settles here.\n const admissions = new LRUMap<string, Admission>(MAX_TRACKED_FLUE_SPANS);\n\n return {\n key: FLUE_INSTRUMENTATION_KEY,\n\n interceptor: async (operation, ctx, next) => {\n // `observe` has already opened the tool span; make it active for the duration so whatever the\n // tool does lands inside it rather than beside it.\n if (operation?.type === FLUE_OPERATION.TOOL) {\n const toolSpan = operation.toolCallId ? toolSpans.get(operation.toolCallId) : undefined;\n return toolSpan ? withActiveSpan(toolSpan, next) : next();\n }\n // The `gen_ai.chat` span of the model call comes from the pi-ai integration, which reads the\n // conversation and the recording options from the scope.\n if (operation?.type === FLUE_OPERATION.MODEL) {\n warnIfPiAiNotInstrumented();\n const { conversationId } = ctx;\n return withScope(scope => {\n if (conversationId) {\n scope.setConversationId(conversationId);\n }\n setPiAiDriverOptions(scope, options, { operation: 'chat', execution: operation, context: ctx });\n return next();\n });\n }\n\n if (operation?.type !== FLUE_OPERATION.AGENT) {\n return next();\n }\n\n // A submission opens with a wrapper operation whose id *is* the submission id; the run it\n // wraps gets its own operation id, and that is the one the observations reference. Spanning\n // the wrapper too would double-count every agent invocation, but it is the outermost point of\n // every attempt, so it is where the admitting context goes back in.\n const operationId = operation.operationId;\n if (operationId && operationId === ctx.submissionId) {\n return runInAdmissionContext(admissions.get(operationId), next);\n }\n if (!operationId || agentSpans.has(operationId)) {\n return next();\n }\n\n const openAgentSpan = () =>\n startSpan(\n {\n name: `invoke_agent ${ctx.agentName ?? 'agent'}`,\n op: getGenAiSpanOp('invoke_agent'),\n attributes: {\n [SENTRY_ORIGIN]: FLUE_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'invoke_agent',\n [GEN_AI_AGENT_NAME]: ctx.agentName,\n [GEN_AI_CONVERSATION_ID]: ctx.conversationId,\n },\n },\n async (span: Span) => {\n agentSpans.set(operationId, span);\n try {\n return await next();\n } finally {\n agentSpans.delete(operationId);\n }\n },\n );\n\n // A durable or dispatched submission is run later by the coordinator, possibly in another\n // isolate or process, where nothing links it back to the request that enqueued it. Flue\n // replays that request's `traceparent` here, so continue from it — but only when no trace is\n // already active, so an in-process dispatch keeps the trace it is genuinely part of.\n const sentryTrace = ctx.traceCarrier?.traceparent\n ? sentryTraceFromTraceparent(ctx.traceCarrier.traceparent)\n : undefined;\n\n return sentryTrace && !getActiveSpan()\n ? continueTrace({ sentryTrace, baggage: undefined }, openAgentSpan)\n : openAgentSpan();\n },\n\n observe: (observation, ctx) => {\n // Observations are emitted synchronously from inside the agent operation, so the active span\n // here is the agent span the interceptor opened — tool spans parent off it without any\n // bookkeeping.\n //\n // The agent operation that gets the span is the one the observations reference, and it knows\n // neither the agent's name nor the conversation: the submission wrapper carries the name, the\n // re-entry carries the conversation, and neither opens a span. Both arrive here instead.\n const agentSpan = observation.operationId ? agentSpans.get(observation.operationId) : undefined;\n if (agentSpan) {\n if (observation.conversationId) {\n agentSpan.setAttribute(GEN_AI_CONVERSATION_ID, observation.conversationId);\n }\n if (observation.agentName) {\n agentSpan.setAttribute(GEN_AI_AGENT_NAME, observation.agentName);\n agentSpan.updateName(`invoke_agent ${observation.agentName}`);\n }\n }\n\n switch (observation.type) {\n // Emitted synchronously from inside the admitting call, so the active context is its own.\n case 'submission_queued':\n if (observation.submissionId && !isCloudflareWorkers()) {\n admissions.set(observation.submissionId, {\n isolationScope: getIsolationScope(),\n span: getActiveSpan(),\n });\n }\n return;\n case 'submission_settled':\n if (observation.submissionId) {\n admissions.remove(observation.submissionId);\n }\n return;\n case 'tool_start':\n startToolSpan(observation, ctx, toolSpans, options);\n return;\n case 'tool':\n endToolSpan(observation, toolSpans);\n return;\n default:\n return;\n }\n },\n\n // Only the tool spans are ended here. They come from `startInactiveSpan`, so nothing else will.\n // The agent spans come from `startSpan`, which ends them when its callback settles — ending them\n // here would stamp an early end time on work that is still running, and the later `end()` would\n // be ignored.\n dispose: () => {\n for (const span of toolSpans.values()) {\n span.end();\n }\n agentSpans.clear();\n admissions.clear();\n toolSpans.clear();\n },\n };\n}\n","/* eslint-disable max-lines */\nimport {\n DB_NAMESPACE,\n DB_OPERATION_NAME,\n DB_QUERY_SUMMARY,\n DB_QUERY_TEXT,\n DB_SYSTEM_NAME,\n} from '@sentry/conventions/attributes';\nimport type { SpanAttributes } from '@sentry/core';\nimport { getClient, hasSpanStreamingEnabled } from '@sentry/core';\n\nconst MAX_SUMMARY_LENGTH = 255;\n\n// A single identifier: quoted (`\"...\"`, `'...'`, or MySQL backticks) or bare. The quoted forms have\n// to be matched as a unit, otherwise an identifier containing a space or a dot is cut in half.\nconst IDENTIFIER = '(?:\"[^\"]*\"|\\'[^\\']*\\'|`[^`]*`|[^\\\\s(,;).\\'\"`]+)';\n\n// A table reference can be schema-qualified (`\"public\".\"User\"`, `db.schema.table`), with each part\n// quoted independently. The whole qualified name is the summary target, since the schema is what\n// distinguishes two same-named tables.\nconst TABLE_NAME = `${IDENTIFIER}(?:\\\\.${IDENTIFIER})*`;\n\nconst DDL_RE = new RegExp(\n `^\\\\s*(?<operation>(?:CREATE|DROP)\\\\s+(?:TABLE|INDEX)|ALTER\\\\s+TABLE)(?:\\\\s+IF\\\\s+(?:NOT\\\\s+)?EXISTS)?\\\\s+(?<table>${TABLE_NAME})`,\n 'i',\n);\n\n// SQLite upserts insert an optional conflict clause between operation and INTO\n// (`INSERT OR REPLACE INTO`, https://sqlite.org/lang_insert.html), with `REPLACE INTO` as the\n// standalone shorthand. The clause is filler like INTO — stripping it keeps upserts on the same\n// low-cardinality summary as plain inserts.\nconst INSERT_RE = new RegExp(\n `^\\\\s*(?<operation>INSERT|REPLACE)(?:\\\\s+OR\\\\s+(?:ROLLBACK|ABORT|FAIL|IGNORE|REPLACE))?\\\\s+INTO(?:\\\\s+TABLE)?\\\\s+(?<table>${TABLE_NAME})`,\n 'i',\n);\nconst UPDATE_RE = new RegExp(\n `^\\\\s*(?<operation>UPDATE)(?:\\\\s+OR\\\\s+(?:ROLLBACK|ABORT|FAIL|IGNORE|REPLACE))?\\\\s+(?<table>${TABLE_NAME})`,\n 'i',\n);\nconst DELETE_RE = new RegExp(`^\\\\s*(?<operation>DELETE)\\\\s+FROM\\\\s+(?<table>${TABLE_NAME})`, 'i');\n\nconst SELECT_RE = /^\\s*(?:\\(\\s*)?(?<operation>SELECT)\\b/i;\n\nconst PRAGMA_RE = /^\\s*(?<operation>PRAGMA)\\s+(?<command>\\S+)/i;\n\nconst TOKEN_RE = /\\b(?:FROM|JOIN)\\s+|\\(\\s*(SELECT)\\b|\\b(?:UNION|INTERSECT|EXCEPT|MINUS)\\s+(?:ALL\\s+)?(SELECT)\\b/gi;\nconst TABLE_REF_RE = new RegExp(`^${TABLE_NAME}`);\nconst COMMA_TABLE_RE = new RegExp(`^\\\\s*,\\\\s*(${TABLE_NAME})`);\nconst SUBQUERY_SELECT_RE = /^\\(\\s*(SELECT)\\b/i;\n\n/**\n * Derives a low-cardinality summary from a SQL query for use as `db.query.summary`.\n *\n * Conforms to the OTEL semantic convention for generating query summaries:\n * - Preserves original case of operations and identifiers (no normalization)\n * - Uses format: `{operation} {target1} {target2} ...`\n * - Strips filler words (INTO, FROM) from the operation\n * - Captures multiple table targets (JOINs)\n * - Handles INSERT...SELECT with both targets\n * - Truncates to 255 characters without splitting mid-value\n *\n * @see https://opentelemetry.io/docs/specs/semconv/database/database-spans/#generating-a-summary-of-the-query\n */\nexport function getSqlQuerySummary(query: string | undefined): string | undefined {\n if (!query) {\n return undefined;\n }\n\n const pragmaMatch = PRAGMA_RE.exec(query);\n if (pragmaMatch?.groups?.['operation'] && pragmaMatch.groups['command']) {\n const operation = pragmaMatch.groups['operation'];\n const command = pragmaMatch.groups['command'];\n const parenIdx = command.indexOf('(');\n return truncate(`${operation} ${parenIdx >= 0 ? command.substring(0, parenIdx) : command}`);\n }\n\n const ddlMatch = DDL_RE.exec(query);\n if (ddlMatch?.groups?.['operation'] && ddlMatch.groups['table']) {\n return truncate(`${ddlMatch.groups['operation']} ${ddlMatch.groups['table']}`);\n }\n\n const insertMatch = INSERT_RE.exec(query);\n if (insertMatch?.groups?.['operation'] && insertMatch.groups['table']) {\n const parts = [insertMatch.groups['operation'], insertMatch.groups['table']];\n const rest = query.slice(insertMatch[0].length);\n const subSelect = /\\b(SELECT)\\b/i.exec(rest);\n if (subSelect?.[1]) {\n parts.push(subSelect[1]);\n const selectTables = extractTableNames(rest.slice(subSelect.index));\n parts.push(...selectTables);\n }\n return truncate(parts.join(' '));\n }\n\n const updateMatch = UPDATE_RE.exec(query);\n if (updateMatch?.groups?.['operation'] && updateMatch.groups['table']) {\n return truncate(`${updateMatch.groups['operation']} ${updateMatch.groups['table']}`);\n }\n\n const deleteMatch = DELETE_RE.exec(query);\n if (deleteMatch?.groups?.['operation'] && deleteMatch.groups['table']) {\n return truncate(`${deleteMatch.groups['operation']} ${deleteMatch.groups['table']}`);\n }\n\n const selectMatch = SELECT_RE.exec(query);\n if (selectMatch?.groups?.['operation']) {\n const tables = extractTableNames(query.slice(selectMatch[0].length));\n if (tables.length > 0) {\n return truncate(`${selectMatch.groups['operation']} ${tables.join(' ')}`);\n }\n return selectMatch.groups['operation'];\n }\n\n return truncate(query.trim().split(/\\s+/)[0] ?? query);\n}\n\nconst LEADING_KEYWORD_RE = /^\\s*(?:\\(\\s*)*([A-Za-z]+)\\b/;\nconst CTE_MAIN_STATEMENT_RE = /\\(|\\)|\\b(SELECT|INSERT|UPDATE|DELETE|MERGE|VALUES|TABLE)\\b/gi;\n\n/**\n * Derives `db.operation.name` from a SQL query: the first operation keyword, in its original case.\n *\n * @see https://opentelemetry.io/docs/specs/semconv/registry/attributes/db/#db-operation-name\n */\nexport function getSqlOperationName(query: string | undefined): string | undefined {\n const match = query ? LEADING_KEYWORD_RE.exec(query) : null;\n const keyword = match?.[1];\n if (!query || !match || !keyword) {\n return undefined;\n }\n // Scanned from after `WITH`, so parentheses wrapping the whole query don't shift the depth.\n return keyword.toUpperCase() === 'WITH' ? getCteMainOperationName(query.slice(match[0].length)) : keyword;\n}\n\n/**\n * The operation of a `WITH` query is its main statement: the first operation keyword outside the\n * CTE bodies, which are all parenthesized. Counting parentheses is safe on a sanitized query, which\n * has no literals or comments left.\n */\nfunction getCteMainOperationName(query: string): string | undefined {\n let depth = 0;\n for (const match of query.matchAll(CTE_MAIN_STATEMENT_RE)) {\n if (match[0] === '(') {\n depth++;\n } else if (match[0] === ')') {\n depth--;\n } else if (depth === 0) {\n return match[1];\n }\n }\n return undefined;\n}\n\nfunction extractTableNames(sql: string): string[] {\n const tables: string[] = [];\n TOKEN_RE.lastIndex = 0;\n let match: RegExpExecArray | null;\n\n while ((match = TOKEN_RE.exec(sql)) !== null) {\n const table = match[1] || match[2];\n if (table) {\n tables.push(table);\n continue;\n }\n\n const rest = sql.slice(match.index + match[0].length);\n\n const subqueryMatch = SUBQUERY_SELECT_RE.exec(rest);\n if (subqueryMatch?.[1]) {\n tables.push(subqueryMatch[1]);\n TOKEN_RE.lastIndex = match.index + match[0].length + subqueryMatch[0].length;\n continue;\n }\n\n const tableMatch = TABLE_REF_RE.exec(rest);\n if (!tableMatch) continue;\n tables.push(tableMatch[0]);\n\n let afterTable = rest.slice(tableMatch[0].length);\n let commaMatch: RegExpExecArray | null;\n while ((commaMatch = COMMA_TABLE_RE.exec(afterTable)) !== null) {\n if (!commaMatch[1]) break;\n tables.push(commaMatch[1]);\n afterTable = afterTable.slice(commaMatch[0].length);\n }\n }\n\n return tables;\n}\n\nfunction truncate(summary: string): string {\n if (summary.length <= MAX_SUMMARY_LENGTH) {\n return summary;\n }\n const truncated = summary.substring(0, MAX_SUMMARY_LENGTH);\n const lastSpace = truncated.lastIndexOf(' ');\n return lastSpace > 0 ? truncated.substring(0, lastSpace) : truncated;\n}\n\nlet integerLiteralRE: RegExp | undefined;\nlet mssqlIntegerLiteralRE: RegExp | undefined;\n\n/**\n * The lookbehind keeps `$n` and `?n` parameter placeholders out of the match. T-SQL has neither,\n * and `$1000` there is a money literal, so `$` only guards a placeholder outside `mssql`.\n *\n * Lazy init: constructing a lookbehind at module scope evaluates it on import and crashes\n * Safari <16.4 browser bundles that reach this file via the core barrel.\n */\nfunction getIntegerLiteralRE(dialect: SqlDialect | SqlLexerRules): RegExp {\n if (dialect === 'mssql') {\n if (!mssqlIntegerLiteralRE) {\n mssqlIntegerLiteralRE = new RegExp('(?<!\\\\?)-?\\\\b\\\\d+\\\\b', 'g');\n }\n return mssqlIntegerLiteralRE;\n }\n if (!integerLiteralRE) {\n integerLiteralRE = new RegExp('(?<![$?])-?\\\\b\\\\d+\\\\b', 'g');\n }\n return integerLiteralRE;\n}\n\n/**\n * SQL dialect variants that matter for finding the end of a string literal:\n * - `standard` (PostgreSQL, SQLite): `\"` quotes identifiers, `''` is the only in-string escape,\n * and PostgreSQL's `$$…$$` dollar quoting opens a literal.\n * - `mysql`: `\"` quotes a string literal unless `ANSI_QUOTES` is set, and `\\` escapes the next\n * character unless `NO_BACKSLASH_ESCAPES` is set. Both default to off, and mysql/mysql2 escape\n * inlined values with backslashes, so this is the mode their statements arrive in.\n * - `mssql`: `[...]` quotes an identifier, so a `'` inside one is part of the name. `\"` quotes\n * one too, unless the connection sets `QUOTED_IDENTIFIER OFF`, which tedious leaves on.\n *\n * An engine with other rules passes {@link SqlLexerRules} instead.\n */\nexport type SqlDialect = 'standard' | 'mysql' | 'mssql';\n\n/**\n * Lexer rules for an engine that no {@link SqlDialect} covers. They apply on top of `standard`. The\n * integration of that engine defines them, so a bundle without that integration does not contain them.\n */\nexport interface SqlLexerRules {\n /** Whether `#` starts a line comment. */\n hashComments?: boolean;\n /** Whether a block comment can contain other block comments. */\n nestedComments?: boolean;\n /** Whether `\\` escapes the next character in a string literal or a quoted identifier. */\n backslashEscapes?: boolean;\n /** Sticky pattern for the opening tag of a dollar-quoted literal. Defaults to the PostgreSQL tag. */\n dollarQuote?: RegExp;\n /** Returns the length of the engine-specific literal at `start`, which the lexer replaces with `?`. */\n matchLiteral?: (sql: string, start: number) => number;\n /**\n * Returns true when inline data starts at `start`. The lexer drops the query text from `start` to the\n * end, because data cannot be sanitized as SQL. `out` holds the sanitized text before `start`.\n */\n isInlineData?: (sql: string, start: number, out: string[]) => boolean;\n}\n\n/**\n * Maps a driver or `db.system.name` value to the dialect its statements are written in. Callers\n * report different spellings for one engine: knex uses the driver name, Prisma the provider name,\n * and OTel the semantic-convention name. An engine we do not know about is lexed as `standard`.\n */\nexport function toSqlDialect(system: unknown): SqlDialect {\n if (system === 'mysql' || system === 'mysql2' || system === 'mariadb') {\n return 'mysql';\n }\n if (system === 'mssql' || system === 'sqlserver' || system === 'microsoft.sql_server') {\n return 'mssql';\n }\n return 'standard';\n}\n\nconst NO_RULES: SqlLexerRules = {};\n\n// Sticky, so the scanner can test one position without slicing the query on every `$`.\nconst DOLLAR_QUOTE_RE = /\\$(?:[A-Za-z_]\\w*)?\\$/y;\n\n/**\n * Returns the index just past the run's closing `delimiter`, or -1 if the run never closes. The\n * caller cannot derive that from the index alone: a query ending in `[a]]` consumed a doubled\n * delimiter, not a closing one.\n *\n * A doubled delimiter (`''`) escapes itself in every dialect; backslash escapes are dialect- and\n * context-dependent, so the caller decides.\n */\nfunction findQuotedRunEnd(sql: string, start: number, delimiter: string, backslashEscapes: boolean): number {\n for (let i = start + 1; i < sql.length; i++) {\n const char = sql[i];\n if (backslashEscapes && char === '\\\\') {\n i++;\n } else if (char === delimiter) {\n if (sql[i + 1] !== delimiter) {\n return i + 1;\n }\n i++;\n }\n }\n return -1;\n}\n\n// An unterminated comment consumes the rest of the query.\nfunction findBlockCommentEnd(sql: string, start: number, nested: boolean): number {\n let depth = 1;\n let i = start + 2;\n while (i < sql.length && depth > 0) {\n if (sql[i] === '*' && sql[i + 1] === '/') {\n depth--;\n i += 2;\n } else if (nested && sql[i] === '/' && sql[i + 1] === '*') {\n depth++;\n i += 2;\n } else {\n i++;\n }\n }\n return i;\n}\n\n/**\n * Replaces every string literal with `?` and drops every comment, in one pass.\n *\n * Doing this by scanning rather than by regex is what keeps quote state and comment state from\n * being decided independently: a regex for `'...'` cannot see that the quote it stopped at was\n * backslash-escaped, and a regex for `--...` cannot see that the `--` sits inside a literal. Both\n * mistakes end with user data surviving into `db.query.text` and `db.query.summary`.\n *\n * Quoted identifiers are preserved — they are the table and column names the query summary is\n * built from.\n */\nfunction stripLiteralsAndComments(sql: string, dialect: SqlDialect | SqlLexerRules): string {\n const [base, rules]: [SqlDialect, SqlLexerRules] =\n typeof dialect === 'string' ? [dialect, NO_RULES] : ['standard', dialect];\n const isMysql = base === 'mysql';\n const backslashEscapes = !!rules.backslashEscapes;\n const out: string[] = [];\n let i = 0;\n\n while (i < sql.length) {\n const char = sql.charAt(i);\n const next = sql[i + 1];\n\n if ((char === '-' && next === '-') || ((isMysql || rules.hashComments) && char === '#')) {\n const lineEnd = sql.indexOf('\\n', i);\n i = lineEnd === -1 ? sql.length : lineEnd;\n continue;\n }\n\n if (char === '/' && next === '*') {\n i = findBlockCommentEnd(sql, i, !!rules.nestedComments);\n continue;\n }\n\n // In a dollar-quoted body (`$$body$$`, `$tag$body$tag$`) nothing has syntax meaning. Read the\n // previous character from the query, not from `out`, where a dropped comment would leave `$$`\n // looking like part of an identifier. Of the `standard` engines only PostgreSQL has dollar\n // quoting. SQLite `$name` parameters do not match the tag pattern, apart from the rare `$a$b`.\n if (base === 'standard' && char === '$' && !isIdentifierChar(sql[i - 1])) {\n const tag = matchDollarQuoteTag(sql, i, rules.dollarQuote);\n if (tag) {\n const bodyEnd = sql.indexOf(tag, i + tag.length);\n i = bodyEnd === -1 ? sql.length : bodyEnd + tag.length;\n out.push('?');\n continue;\n }\n }\n\n const identifierCloser = getIdentifierCloser(char, base);\n if (identifierCloser) {\n const runEnd = findQuotedRunEnd(sql, i, identifierCloser, backslashEscapes);\n // A run that never closes is not an identifier, so it collapses instead of being copied out.\n // Copying would carry every literal in the rest of the statement through unlexed.\n out.push(runEnd === -1 ? '?' : sql.slice(i, runEnd));\n i = runEnd === -1 ? sql.length : runEnd;\n continue;\n }\n\n if (char === \"'\" || (char === '\"' && isMysql)) {\n // A prefix like `X'1A'`, `B'01'`, `N'…'` or PostgreSQL's `E'a\\nb'` is part of the literal, so it has\n // to collapse into the same `?` instead of being left behind as a bare identifier.\n const prefix = char === \"'\" ? getLiteralPrefix(out, base) : undefined;\n if (prefix) {\n out.pop();\n }\n const runEnd = findQuotedRunEnd(sql, i, char, isMysql || backslashEscapes || prefix === 'E');\n i = runEnd === -1 ? sql.length : runEnd;\n out.push('?');\n continue;\n }\n\n const literalLength = rules.matchLiteral?.(sql, i);\n if (literalLength) {\n out.push('?');\n i += literalLength;\n continue;\n }\n if (rules.isInlineData?.(sql, i, out)) {\n break;\n }\n out.push(char);\n i++;\n }\n\n return out.join('');\n}\n\n/**\n * Returns the character that closes an identifier opened by `char`, or undefined if `char` opens\n * none. SQL Server brackets close on `]`, and `]]` escapes a `]` inside the name, which is the same\n * doubling rule `findQuotedRunEnd` applies to quotes.\n */\nfunction getIdentifierCloser(char: string, dialect: SqlDialect): string | undefined {\n if (char === '`') {\n return '`';\n }\n if (char === '\"' && dialect !== 'mysql') {\n return '\"';\n }\n return char === '[' && dialect === 'mssql' ? ']' : undefined;\n}\n\n/** Whether `char` can appear inside an identifier. `undefined` (start of query) counts as a break. */\nexport function isIdentifierChar(char: string | undefined): boolean {\n return char !== undefined && /[\\w$]/.test(char);\n}\n\n/** Returns the opening dollar-quote tag at `start` (`$$` or `$tag$`), or undefined if there is none. */\nfunction matchDollarQuoteTag(sql: string, start: number, pattern = DOLLAR_QUOTE_RE): string | undefined {\n pattern.lastIndex = start;\n return pattern.exec(sql)?.[0];\n}\n\n/**\n * Returns the literal-prefix character immediately before a `'`, if there is one: `X`/`B` for\n * hex/binary literals, `N` for a national-character literal (SQL Server, MySQL), or `E` for a\n * PostgreSQL escape string (which honors backslash escapes).\n */\nfunction getLiteralPrefix(out: string[], dialect: SqlDialect): 'X' | 'B' | 'N' | 'E' | undefined {\n const last = out[out.length - 1];\n // A prefix only counts when it stands alone — the `X` in `MAX'...'` belongs to the identifier\n if (last?.length !== 1 || isIdentifierChar(out[out.length - 2]?.slice(-1))) {\n return undefined;\n }\n\n const prefix = last.toUpperCase();\n if (prefix === 'X' || prefix === 'B' || prefix === 'N') {\n return prefix;\n }\n return prefix === 'E' && dialect === 'standard' ? 'E' : undefined;\n}\n\n/**\n * Sanitize SQL query as per the OTEL semantic conventions\n * https://opentelemetry.io/docs/specs/semconv/database/database-spans/#sanitization-of-dbquerytext\n *\n * Parameter placeholders survive: PostgreSQL `$n`, SQLite `?n`, and named forms like `:name` and\n * `@name`. Per the OTEL spec they mark a parameterized query, so only values (strings, numbers,\n * booleans) are sanitized.\n *\n * Pass `dialect` when the statement comes from a driver whose literals are not standard-quoted;\n * see {@link SqlDialect} and {@link SqlLexerRules}.\n */\nexport function sanitizeSqlQuery(\n sqlQuery: string | undefined,\n dialect: SqlDialect | SqlLexerRules = 'standard',\n): string {\n if (!sqlQuery) {\n return 'Unknown SQL Query';\n }\n\n return (\n // Strip comments and string literals first: everything below is a regex that cannot tell\n // whether it is looking at SQL syntax or at a user-supplied value.\n stripLiteralsAndComments(sqlQuery, dialect)\n .replace(/;\\s*$/, '') // Remove trailing semicolons\n .replace(/^[\\s;]+/, '') // Remove leading semicolons (T-SQL's `;WITH`)\n // Collapse whitespace to a single space (after removing comments)\n .replace(/\\s+/g, ' ')\n .trim() // Remove extra spaces and trim\n // Sanitize hex numbers\n .replace(/\\b0x[0-9A-Fa-f]+/gi, '?')\n // Sanitize boolean literals\n .replace(/\\b(?:TRUE|FALSE)\\b/gi, '?')\n // Sanitize numeric literals (preserve $n placeholders via negative lookbehind)\n .replace(/-?\\b\\d+\\.?\\d*[eE][+-]?\\d+\\b/g, '?') // Scientific notation\n .replace(/-?\\b\\d+\\.\\d+\\b/g, '?') // Decimals\n .replace(/-?\\.\\d+\\b/g, '?') // Decimals starting with dot\n .replace(getIntegerLiteralRE(dialect), '?') // Integers (NOT parameter placeholders)\n // Collapse IN clauses for cardinality (both ? and $n variants)\n .replace(/\\bIN\\b\\s*\\(\\s*\\?(?:\\s*,\\s*\\?)*\\s*\\)/gi, 'IN (?)')\n .replace(/\\bIN\\b\\s*\\(\\s*\\$\\d+(?:\\s*,\\s*\\$\\d+)*\\s*\\)/gi, 'IN ($?)')\n );\n}\n\nexport interface SqlQueryAttributes {\n [DB_QUERY_TEXT]: string | undefined;\n [DB_QUERY_SUMMARY]: string | undefined;\n [DB_OPERATION_NAME]: string | undefined;\n}\n\n/**\n * Sanitizes a collected SQL statement into the query attributes the SQL integrations attach to\n * their spans: `db.query.text`, `db.query.summary` and `db.operation.name`. All are `undefined`\n * when there is no statement, so an empty query omits the attributes instead of reporting the\n * sanitizer's fallback text.\n */\nexport function getSqlQueryAttributes(\n sqlQuery: string | undefined,\n dialect?: SqlDialect | SqlLexerRules,\n): SqlQueryAttributes {\n const queryText = (sqlQuery && sanitizeSqlQuery(sqlQuery, dialect)) || undefined;\n return {\n [DB_QUERY_TEXT]: queryText,\n [DB_QUERY_SUMMARY]: getSqlQuerySummary(queryText),\n [DB_OPERATION_NAME]: getSqlOperationName(queryText),\n };\n}\n\n/**\n * Names a SQL span with a low-cardinality name: `db.query.summary`, falling back to `db.namespace`\n * and then `db.system.name`. `fallback` is the integration's name for a span with none of those.\n *\n * New SQL integrations should name their spans with this regardless of span streaming.\n */\nexport function getLowCardinalitySqlSpanName(attributes: SpanAttributes, fallback: string): string {\n return toSpanName(attributes[DB_QUERY_SUMMARY] || attributes[DB_NAMESPACE] || attributes[DB_SYSTEM_NAME], fallback);\n}\n\n/**\n * Names a SQL span from its attributes. Streamed span names have to be low cardinality (see\n * {@link getLowCardinalitySqlSpanName}); otherwise the sanitized `db.query.text` is used, which\n * existing integrations keep for spans that aren't streamed.\n */\nexport function getSqlSpanName(attributes: SpanAttributes, fallback: string): string {\n const client = getClient();\n if (client && hasSpanStreamingEnabled(client)) {\n return getLowCardinalitySqlSpanName(attributes, fallback);\n }\n return toSpanName(attributes[DB_QUERY_TEXT], fallback);\n}\n\nfunction toSpanName(value: unknown, fallback: string): string {\n return typeof value === 'string' && value ? value : fallback;\n}\n","type ModuleInfo = Record<string, string>;\ninterface PackageJson {\n name?: string;\n version?: string;\n dependencies?: ModuleInfo;\n devDependencies?: ModuleInfo;\n}\n\nconst NODE_MODULES = '/node_modules/';\n\n/**\n * Returns the app's packages: the dependencies declared in its `package.json`, plus loaded packages. Each gets the exact\n * version that a bare import from the app resolves through `node_modules`, or its declared range otherwise.\n */\nexport function collectInstalledModules({\n readFile,\n entryPath,\n cwd,\n loadedFiles = [],\n}: {\n readFile: (path: string) => string | undefined;\n entryPath?: string;\n cwd?: string;\n /**\n * Paths of files the process has already loaded, such as the keys of the CommonJS module cache. Packages these files\n * belong to are added too, which covers transitive dependencies that are not in `package.json`.\n */\n loadedFiles?: string[];\n}): ModuleInfo {\n const read = (dir: string): PackageJson | undefined => {\n try {\n return JSON.parse(readFile(join(dir, 'package.json')) || 'null') || undefined;\n } catch {\n return undefined;\n }\n };\n\n const entryDir = entryPath && dirname(toPosix(entryPath));\n const cwdDir = cwd && toPosix(cwd);\n // An entry file outside cwd usually belongs to a launcher, such as the AWS Lambda runtime.\n const appRoot = findAppRoot(\n read,\n entryDir && cwdDir && !isIn(entryDir, cwdDir) ? [cwdDir, entryDir] : [entryDir, cwdDir],\n );\n\n const resolveFrom =\n entryDir && appRoot && isIn(entryDir, appRoot) && !inNodeModules(entryDir)\n ? entryDir\n : appRoot || entryDir || cwdDir;\n const nodeModulesDirs = resolveFrom ? ancestors(resolveFrom).map(dir => join(dir, 'node_modules')) : [];\n const resolve = (name: string): string | undefined => {\n for (const dir of nodeModulesDirs) {\n const version = read(join(dir, name))?.version;\n if (version) {\n return version;\n }\n }\n return undefined;\n };\n\n const pkg = appRoot ? read(appRoot) : undefined;\n const declared: ModuleInfo = { ...pkg?.dependencies, ...pkg?.devDependencies };\n const installed: ModuleInfo = {};\n const seen = new Set<string>();\n\n for (const file of loadedFiles) {\n const path = toPosix(file);\n const start = path.lastIndexOf(NODE_MODULES) + NODE_MODULES.length;\n const [first = '', second] = path.slice(start).split('/');\n const name = first.startsWith('@') ? `${first}/${second}` : first;\n const dir = path.slice(0, start) + name;\n if (start < NODE_MODULES.length || seen.has(dir) || !nodeModulesDirs.some(d => isIn(path, d))) {\n continue;\n }\n seen.add(dir);\n const version = read(dir)?.version;\n if (version && installed[name] !== version) {\n // pnpm and Bun stores can hold several versions of a package; prefer the one the app resolves.\n installed[name] = (name in installed && resolve(name)) || installed[name] || version;\n }\n }\n\n for (const name of Object.keys(declared)) {\n const version = resolve(name);\n if (version) {\n installed[name] = version;\n }\n }\n\n return { ...declared, ...installed };\n}\n\n/** Skips start dirs inside `node_modules` and `package.json` files that only set fields like `\"type\"`. */\nfunction findAppRoot(\n read: (dir: string) => PackageJson | undefined,\n startDirs: Array<string | undefined>,\n): string | undefined {\n for (const startDir of startDirs) {\n const root =\n startDir && !inNodeModules(startDir)\n ? ancestors(startDir).find(dir => {\n const pkg = read(dir);\n return pkg && (pkg.name || pkg.dependencies || pkg.devDependencies);\n })\n : undefined;\n if (root) {\n return root;\n }\n }\n return undefined;\n}\n\nfunction inNodeModules(dir: string): boolean {\n return `${dir}/`.includes(NODE_MODULES);\n}\n\n/** `dir` and its parents, up to the root. */\nfunction ancestors(dir: string): string[] {\n const dirs = [dir];\n for (let parent = dirname(dir); parent !== dirs[dirs.length - 1]; parent = dirname(parent)) {\n dirs.push(parent);\n }\n return dirs;\n}\n\n// Minimal POSIX helpers: all paths are converted with `toPosix` first.\nfunction dirname(path: string): string {\n const index = path.lastIndexOf('/');\n return index > 0 ? path.slice(0, index) : index === 0 ? '/' : path;\n}\n\nfunction join(dir: string, name: string): string {\n return dir.endsWith('/') ? dir + name : `${dir}/${name}`;\n}\n\nfunction isIn(path: string, dir: string): boolean {\n return path === dir || path.startsWith(dir.endsWith('/') ? dir : `${dir}/`);\n}\n\nfunction toPosix(path: string): string {\n return path.replace(/\\\\/g, '/');\n}\n","// Portable instrumentation for https://github.com/porsager/postgres\n// This can be used in any environment (Node.js, Cloudflare Workers, etc.)\n// without depending on OpenTelemetry module hooking.\n/* eslint-disable max-lines */\n\nimport {\n addNonEnumerableProperty,\n debug,\n getActiveSpan,\n isObjectLike,\n type Span,\n type SpanAttributes,\n SPAN_STATUS_ERROR,\n startSpanManual,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { getSqlQueryAttributes, getSqlSpanName } from '../utils/sql';\nimport {\n DB_NAMESPACE,\n DB_OPERATION_NAME,\n DB_QUERY_TEXT,\n DB_SYSTEM_NAME,\n SENTRY_OP,\n SENTRY_ORIGIN,\n SERVER_ADDRESS,\n SERVER_PORT,\n DB_RESPONSE_STATUS_CODE,\n ERROR_TYPE,\n} from '@sentry/conventions/attributes';\nimport { DB } from '@sentry/conventions/op';\n\n/** The callbacks postgres.js calls on a `Query` when it settles. */\nexport interface PostgresQuerySettlement {\n resolve?: (...args: unknown[]) => unknown;\n reject?: (...args: unknown[]) => unknown;\n}\n\nexport type PostgresConnectionContext = {\n ATTR_DB_NAMESPACE?: string;\n ATTR_SERVER_ADDRESS?: string;\n ATTR_SERVER_PORT?: string;\n};\n\nexport interface PostgresJsSqlInstrumentationOptions {\n /**\n * Whether to require a parent span for the instrumentation.\n * If set to true, the instrumentation will only create spans if there is a parent span\n * available in the current scope.\n * @default true\n */\n requireParentSpan?: boolean;\n /**\n * Hook to modify the span before it is started.\n * This can be used to set additional attributes or modify the span in any way.\n */\n requestHook?: (span: Span, sanitizedSqlQuery: string, postgresConnectionContext?: PostgresConnectionContext) => void;\n}\n\nconst CONNECTION_CONTEXT_SYMBOL = Symbol('sentryPostgresConnectionContext');\n\n// Use the same Symbol.for() markers as the Node.js OTel instrumentation\n// so that both approaches recognize each other and prevent double-wrapping.\nconst INSTRUMENTED_MARKER = Symbol.for('sentry.instrumented.postgresjs');\n// Marker to track if a query was created from an instrumented sql instance.\n// This prevents double-spanning when both the wrapper and the Node.js Query.prototype\n// fallback patch are active simultaneously.\nconst QUERY_FROM_INSTRUMENTED_SQL = Symbol.for('sentry.query.from.instrumented.sql');\n// postgres >= 4 publishes `postgres:query` without exposing the `Query`, so the native channel\n// subscriber can't read QUERY_FROM_INSTRUMENTED_SQL. It checks this marker on the active span instead.\nconst POSTGRESJS_WRAPPER_SPAN = Symbol.for('sentry.postgresjs.wrapper.span');\n\n/**\n * Instruments a postgres.js `sql` instance with Sentry tracing.\n *\n * This is a portable instrumentation function that works in any environment\n * (Node.js, Cloudflare Workers, etc.) without depending on OpenTelemetry.\n *\n * @example\n * ```javascript\n * import postgres from 'postgres';\n * import * as Sentry from '@sentry/cloudflare'; // or '@sentry/deno'\n *\n * const sql = Sentry.instrumentPostgresJsSql(\n * postgres({ host: 'localhost', database: 'mydb' })\n * );\n *\n * // All queries now create Sentry spans\n * await sql`SELECT * FROM users WHERE id = ${userId}`;\n * ```\n */\nexport function instrumentPostgresJsSql<T>(sql: T, options?: PostgresJsSqlInstrumentationOptions): T {\n if (!sql || typeof sql !== 'function') {\n DEBUG_BUILD && debug.warn('instrumentPostgresJsSql: provided value is not a valid postgres.js sql instance');\n return sql;\n }\n\n return _instrumentSqlInstance(sql, { requireParentSpan: true, ...options }) as T;\n}\n\n/**\n * Instruments a sql instance by wrapping its query execution methods.\n */\nfunction _instrumentSqlInstance(\n sql: unknown,\n options: PostgresJsSqlInstrumentationOptions,\n parentConnectionContext?: PostgresConnectionContext,\n): unknown {\n // Check if already instrumented to prevent double-wrapping\n // Using Symbol.for() ensures the marker survives proxying\n if ((sql as Record<symbol, unknown>)[INSTRUMENTED_MARKER]) {\n return sql;\n }\n\n // Wrap the sql function to intercept query creation\n const proxiedSql: unknown = new Proxy(sql as (...args: unknown[]) => unknown, {\n apply(target, thisArg, argumentsList: unknown[]) {\n const query = Reflect.apply(target, thisArg, argumentsList);\n\n if (isObjectLike(query) && 'handle' in query) {\n _wrapSingleQueryHandle(query as { handle: unknown; strings?: string[] }, proxiedSql, options);\n }\n\n return query;\n },\n get(target, prop) {\n const original = (target as unknown as Record<string | symbol, unknown>)[prop];\n\n if (typeof prop !== 'string' || typeof original !== 'function') {\n return original;\n }\n\n // Wrap methods that return PendingQuery objects (unsafe, file)\n if (prop === 'unsafe' || prop === 'file') {\n return _wrapQueryMethod(original as (...args: unknown[]) => unknown, target, proxiedSql, options);\n }\n\n // Wrap begin and reserve (not savepoint to avoid duplicate spans)\n if (prop === 'begin' || prop === 'reserve') {\n return _wrapCallbackMethod(original as (...args: unknown[]) => unknown, target, proxiedSql, options);\n }\n\n return original;\n },\n });\n\n // Use provided parent context if available, otherwise extract from sql.options\n if (parentConnectionContext) {\n (proxiedSql as Record<symbol, unknown>)[CONNECTION_CONTEXT_SYMBOL] = parentConnectionContext;\n } else {\n _attachConnectionContext(sql, proxiedSql as Record<symbol, unknown>);\n }\n\n // Mark both the original and proxy as instrumented to prevent double-wrapping\n (sql as Record<symbol, unknown>)[INSTRUMENTED_MARKER] = true;\n (proxiedSql as Record<symbol, unknown>)[INSTRUMENTED_MARKER] = true;\n\n return proxiedSql;\n}\n\n/**\n * Wraps query-returning methods (unsafe, file) to ensure their queries are instrumented.\n */\nfunction _wrapQueryMethod(\n original: (...args: unknown[]) => unknown,\n target: unknown,\n proxiedSql: unknown,\n options: PostgresJsSqlInstrumentationOptions,\n): (...args: unknown[]) => unknown {\n return function (this: unknown, ...args: unknown[]): unknown {\n const query = Reflect.apply(original, target, args);\n\n if (isObjectLike(query) && 'handle' in query) {\n _wrapSingleQueryHandle(query as { handle: unknown; strings?: string[] }, proxiedSql, options);\n }\n\n return query;\n };\n}\n\n/**\n * Wraps callback-based methods (begin, reserve) to recursively instrument Sql instances.\n * Note: These methods can also be used as tagged templates, which we pass through unchanged.\n *\n * Savepoint is not wrapped to avoid complex nested transaction instrumentation issues.\n * Queries within savepoint callbacks are still instrumented through the parent transaction's Sql instance.\n */\nfunction _wrapCallbackMethod(\n original: (...args: unknown[]) => unknown,\n target: unknown,\n parentSqlInstance: unknown,\n options: PostgresJsSqlInstrumentationOptions,\n): (...args: unknown[]) => unknown {\n return function (this: unknown, ...args: unknown[]): unknown {\n // Extract parent context to propagate to child instances\n const parentContext = (parentSqlInstance as Record<symbol, unknown>)[CONNECTION_CONTEXT_SYMBOL] as\n | PostgresConnectionContext\n | undefined;\n\n // Check if this is a callback-based call by verifying the last argument is a function\n const isCallbackBased = typeof args[args.length - 1] === 'function';\n\n if (!isCallbackBased) {\n // Not a callback-based call - could be tagged template or promise-based\n const result = Reflect.apply(original, target, args);\n // If result is a Promise (e.g., reserve() without callback), instrument the resolved Sql instance\n if (result && typeof (result as Promise<unknown>).then === 'function') {\n return (result as Promise<unknown>).then((sqlInstance: unknown) => {\n return _instrumentSqlInstance(sqlInstance, options, parentContext);\n });\n }\n return result;\n }\n\n // Callback-based call: wrap the callback to instrument the Sql instance\n const callback = (args.length === 1 ? args[0] : args[1]) as (sql: unknown) => unknown;\n const wrappedCallback = function (sqlInstance: unknown): unknown {\n const instrumentedSql = _instrumentSqlInstance(sqlInstance, options, parentContext);\n return callback(instrumentedSql);\n };\n\n const newArgs = args.length === 1 ? [wrappedCallback] : [args[0], wrappedCallback];\n return Reflect.apply(original, target, newArgs);\n };\n}\n\n/**\n * Wraps a single query's handle method to create spans.\n */\nfunction _wrapSingleQueryHandle(\n query: { handle: unknown; strings?: string[]; __sentryWrapped?: boolean },\n sqlInstance: unknown,\n options: PostgresJsSqlInstrumentationOptions,\n): void {\n // Prevent double wrapping - check if the handle itself is already wrapped\n if ((query.handle as { __sentryWrapped?: boolean })?.__sentryWrapped) {\n return;\n }\n\n // Mark this query as coming from an instrumented sql instance.\n // This prevents the Node.js Query.prototype fallback patch from double-spanning.\n (query as Record<symbol, unknown>)[QUERY_FROM_INSTRUMENTED_SQL] = true;\n\n const originalHandle = query.handle as (...args: unknown[]) => Promise<unknown>;\n\n // IMPORTANT: We must replace the handle function directly, not use a Proxy,\n // because Query.then() internally calls this.handle(), which would bypass a Proxy wrapper.\n const wrappedHandle = async function (\n this: PostgresQuerySettlement & { executed?: boolean },\n ...args: unknown[]\n ): Promise<unknown> {\n // postgres.js calls handle() from then/catch/finally — only the first call executes SQL,\n // subsequent calls are no-ops (guarded by this.executed). Skip span creation for no-ops.\n if (this.executed || !_shouldCreateSpans(options)) {\n return originalHandle.apply(this, args);\n }\n\n const queryAttributes = getSqlQueryAttributes(_reconstructQuery(query.strings));\n const sanitizedSqlQuery = queryAttributes[DB_QUERY_TEXT] ?? '';\n\n const connectionContext = sqlInstance\n ? ((sqlInstance as Record<symbol, unknown>)[CONNECTION_CONTEXT_SYMBOL] as PostgresConnectionContext | undefined)\n : undefined;\n\n const attributes: SpanAttributes = {\n [SENTRY_OP]: DB,\n [SENTRY_ORIGIN]: 'auto.db.postgresjs',\n [DB_SYSTEM_NAME]: 'postgres',\n ...queryAttributes,\n ...(connectionContext && _getConnectionAttributes(connectionContext)),\n };\n\n return startSpanManual({ name: getSqlSpanName(attributes, 'postgresjs.query'), attributes }, (span: Span) => {\n addNonEnumerableProperty(span, POSTGRESJS_WRAPPER_SPAN, true);\n\n if (options.requestHook) {\n try {\n options.requestHook(span, sanitizedSqlQuery, connectionContext);\n } catch (e) {\n span.setAttribute('sentry.hook.error', 'requestHook failed');\n DEBUG_BUILD && debug.error('Error in requestHook for PostgresJs instrumentation:', e);\n }\n }\n\n _wrapQuerySettlement(this, span, queryAttributes[DB_OPERATION_NAME]);\n\n // Handle synchronous errors that might occur before promise is created\n try {\n return originalHandle.apply(this, args);\n } catch (e) {\n span.setStatus({\n code: SPAN_STATUS_ERROR,\n message: e instanceof Error ? e.message : 'unknown_error',\n });\n span.end();\n throw e;\n }\n });\n };\n\n (wrappedHandle as { __sentryWrapped?: boolean }).__sentryWrapped = true;\n query.handle = wrappedHandle;\n}\n\n/**\n * Whether `span` was started by {@link instrumentPostgresJsSql}.\n *\n * @internal Exported for the diagnostics-channel integration.\n */\nexport function _isPostgresJsWrapperSpan(span: Span | undefined): boolean {\n return !!span && POSTGRESJS_WRAPPER_SPAN in span;\n}\n\n/**\n * Determines whether a span should be created based on the current context.\n * If `requireParentSpan` is set to true in the options, a span will\n * only be created if there is a parent span available.\n */\nfunction _shouldCreateSpans(options: PostgresJsSqlInstrumentationOptions): boolean {\n const hasParentSpan = getActiveSpan() !== undefined;\n return hasParentSpan || !options.requireParentSpan;\n}\n\n/**\n * Reconstructs the full SQL query from template strings with PostgreSQL placeholders.\n *\n * For sql`SELECT * FROM users WHERE id = ${123} AND name = ${'foo'}`:\n * strings = [\"SELECT * FROM users WHERE id = \", \" AND name = \", \"\"]\n * returns: \"SELECT * FROM users WHERE id = $1 AND name = $2\"\n *\n * @internal Exported for testing only\n */\nexport function _reconstructQuery(strings: string[] | undefined): string | undefined {\n if (!strings?.length) {\n return undefined;\n }\n if (strings.length === 1) {\n return strings[0] || undefined;\n }\n // Join template parts with PostgreSQL placeholders ($1, $2, etc.)\n return strings.reduce((acc, str, i) => (i === 0 ? str : `${acc}$${i}${str}`), '');\n}\n\n/**\n * Returns connection context attributes.\n *\n * @internal Exported for the diagnostics-channel integration.\n */\nexport function _getConnectionAttributes(connectionContext: PostgresConnectionContext): SpanAttributes {\n const attributes: SpanAttributes = {};\n\n const portNumber = connectionContext.ATTR_SERVER_PORT ? parseInt(connectionContext.ATTR_SERVER_PORT, 10) : undefined;\n const dbNamespace = connectionContext.ATTR_DB_NAMESPACE;\n const serverAddress = connectionContext.ATTR_SERVER_ADDRESS;\n\n if (dbNamespace) {\n attributes[DB_NAMESPACE] = dbNamespace;\n }\n if (serverAddress) {\n attributes[SERVER_ADDRESS] = serverAddress;\n }\n if (portNumber !== undefined && !isNaN(portNumber)) {\n attributes[SERVER_PORT] = portNumber;\n }\n\n return attributes;\n}\n\n/**\n * Builds a {@link PostgresConnectionContext} from postgres.js' parsed options\n * (which store `host`/`port` as arrays). Defaults to 'localhost'/5432.\n *\n * @internal Exported for the diagnostics-channel integration.\n */\nexport function _buildConnectionContext(options: {\n host?: string[];\n port?: number[];\n database?: string;\n}): PostgresConnectionContext {\n const host = options.host?.[0] || 'localhost';\n const port = options.port?.[0] || 5432;\n return {\n ATTR_DB_NAMESPACE: typeof options.database === 'string' && options.database !== '' ? options.database : undefined,\n ATTR_SERVER_ADDRESS: host,\n ATTR_SERVER_PORT: String(port),\n };\n}\n\n/**\n * Wrap `query.resolve`/`query.reject` so the span ends when the query settles.\n *\n * `Query extends Promise` and `async handle()` only dispatches — its promise\n * resolves immediately, long before the query completes. postgres.js signals\n * completion by calling `this.resolve`/`this.reject`, so we own the span end\n * there. Wrapping happens at handle-start because `reject` can fire\n * synchronously during dispatch and `cursor()` reassigns both before executing.\n */\nexport function _wrapQuerySettlement(\n query: PostgresQuerySettlement,\n span: Span,\n operationName: string | undefined,\n onSettle?: () => void,\n): void {\n const originalResolve = query.resolve;\n if (typeof originalResolve === 'function') {\n query.resolve = function (this: unknown, ...resolveArgs: unknown[]): unknown {\n onSettle?.();\n try {\n const command = (resolveArgs[0] as { command?: string } | undefined)?.command;\n // Re-set the operation name with the server-reported command, which is more reliable than the query text.\n span.setAttribute(DB_OPERATION_NAME, command || operationName);\n span.end();\n } catch (e) {\n DEBUG_BUILD && debug.error('[instrumentation:postgresjs] error ending span in resolve:', e);\n }\n return originalResolve.apply(this, resolveArgs);\n };\n }\n\n const originalReject = query.reject;\n if (typeof originalReject === 'function') {\n query.reject = function (this: unknown, ...rejectArgs: unknown[]): unknown {\n onSettle?.();\n try {\n const err = rejectArgs[0] as { message?: string; code?: string; name?: string } | undefined;\n span.setStatus({ code: SPAN_STATUS_ERROR, message: err?.message || 'unknown_error' });\n span.setAttribute(DB_RESPONSE_STATUS_CODE, err?.code || 'unknown');\n span.setAttribute(ERROR_TYPE, err?.name || 'unknown');\n span.end();\n } catch (e) {\n DEBUG_BUILD && debug.error('[instrumentation:postgresjs] error ending span in reject:', e);\n }\n return originalReject.apply(this, rejectArgs);\n };\n }\n}\n\n/**\n * Extracts and stores connection context from sql.options.\n */\nfunction _attachConnectionContext(sql: unknown, proxiedSql: Record<symbol, unknown>): void {\n const sqlInstance = sql as { options?: { host?: string[]; port?: number[]; database?: string } };\n if (!sqlInstance.options || typeof sqlInstance.options !== 'object') {\n return;\n }\n\n proxiedSql[CONNECTION_CONTEXT_SYMBOL] = _buildConnectionContext(sqlInstance.options);\n}\n","// Origin for the `http.server` child span that traces Hono's internal `app.request(...)` dispatches.\n// Shared by the `app.request` Proxy (`patchAppRequest`) and the orchestrion channel subscriber\n// (`instrumentInternalRequests` in `honoIntegration`), which both open this span.\nexport const INTERNAL_REQUEST_ORIGIN = 'auto.http.hono.internal_request';\n\n// Marks the Sentry request/response middleware so the span-wrapping patches never turn it into a\n// middleware span — most importantly when an auto-instrumented sub-app carrying this middleware is\n// mounted into a parent and `wrapSubAppMiddleware` wraps its handlers. Read by `wrapMiddlewareWithSpan`\n// and `resolveRouteName`.\nexport const SENTRY_HONO_MIDDLEWARE = '__SENTRY_HONO_MIDDLEWARE__';\n","// oxlint-disable-next-line typescript/no-unsafe-function-type\ntype AnyFunction = Function;\n\n/**\n * Proxy traps that expose `original` as `__sentry_original__` on a wrapping Proxy without defining it on the target,\n * which is the original itself. `functionToStringIntegration` only unwraps own properties, so the property has to\n * look like an own one too.\n */\nexport function sentryOriginalTraps<T extends AnyFunction>(\n original: AnyFunction,\n): Pick<ProxyHandler<T>, 'get' | 'getOwnPropertyDescriptor'> {\n return {\n get(target, prop, receiver) {\n if (prop === '__sentry_original__') {\n return original;\n }\n return Reflect.get(target, prop, receiver);\n },\n getOwnPropertyDescriptor(target, prop) {\n if (prop === '__sentry_original__') {\n return { value: original, writable: true, enumerable: false, configurable: true };\n }\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n };\n}\n","import { SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { HTTP_SERVER } from '@sentry/conventions/op';\nimport { debug, getActiveSpan, getOriginalFunction, startSpan, type WrappedFunction } from '@sentry/core';\nimport { INTERNAL_REQUEST_ORIGIN } from './constants';\nimport type { Env, Hono } from './honoTypes';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { sentryOriginalTraps } from './sentryOriginalTraps';\n\nconst INTERNAL_REQUEST_OP = HTTP_SERVER;\n\n// Re-entrancy guard shared with the orchestrion channel subscriber\n// (`instrumentInternalRequests` in `honoIntegration`). Both wrap the same `app.request`: this Proxy\n// calls through to the original, which — when the default integration is active — is orchestrion-\n// instrumented and publishes to the request channel. Without this guard the two stack a second,\n// identical internal-request span inside the first. The Proxy owns the span; the channel subscriber\n// reads this flag and opts out. `Symbol.for` on `globalThis` keeps it shared across copies of\n// `@sentry/server-utils`, matching the request-handling dedup markers.\nconst INTERNAL_REQUEST_SPAN_ACTIVE = Symbol.for('sentry.hono.internalRequestSpanActive');\ntype GuardCarrier = { [INTERNAL_REQUEST_SPAN_ACTIVE]?: boolean };\n\n/** Whether the instance `app.request` Proxy is currently opening an internal-request span. */\nexport function isInternalRequestSpanActive(): boolean {\n return !!(globalThis as GuardCarrier)[INTERNAL_REQUEST_SPAN_ACTIVE];\n}\n\nfunction setInternalRequestSpanActive(active: boolean): void {\n (globalThis as GuardCarrier)[INTERNAL_REQUEST_SPAN_ACTIVE] = active;\n}\n\nfunction stripQueryAndHash(path: string): string {\n const end = path.search(/[?#]/);\n return end === -1 ? path : path.slice(0, end);\n}\n\n/**\n * Derive the span-name path from an `app.request()` argument, mirroring Hono's own handling so the\n * name matches the path actually dispatched, with the query/hash stripped so they can't leak into\n * span names or inflate cardinality.\n *\n * Hono treats an absolute `http(s)://` input as a full URL and everything else as a path under\n * `http://localhost` (see `hono-base`'s `request`). We prepend that same fixed host rather than\n * resolving the string as a URL reference: resolution rewrites protocol-relative inputs\n * (`//example.com/foo` → host `example.com`, dropping the segment Hono keeps in the path) and throws\n * on inputs Hono accepts (`//`, `http:`). This runs before the underlying dispatch, so it must never\n * throw — the `catch` is a final guard against any remaining malformed input.\n */\nexport function extractPathname(input: unknown): string {\n if (typeof input === 'string') {\n try {\n const url = /^https?:\\/\\//.test(input)\n ? new URL(input)\n : new URL(`http://localhost${input.startsWith('/') ? '' : '/'}${input}`);\n return url.pathname;\n } catch {\n return stripQueryAndHash(input);\n }\n }\n\n if (input instanceof Request) {\n return new URL(input.url).pathname;\n }\n\n return input instanceof URL ? input.pathname : '/';\n}\n\n/**\n * Patches `app.request()` on a Hono instance so that each internal dispatch\n * is traced as an `http.server` span — child of whatever span is active at\n * the call site.\n *\n * `.request()` is a class field (arrow function), so this must run per-instance.\n * Idempotent: safe to call multiple times on the same instance.\n */\nexport function patchAppRequest<E extends Env>(app: Hono<E>): void {\n if (getOriginalFunction(app.request as unknown as WrappedFunction)) {\n DEBUG_BUILD && debug.log('[hono] app.request already patched — skipping.');\n return;\n }\n\n const originalRequest = app.request;\n\n app.request = new Proxy(originalRequest, {\n apply(_target, thisArg, args: [string | Request | URL, RequestInit?, ...unknown[]]) {\n const [input, requestInit, ...rest] = args;\n\n if (!getActiveSpan()) {\n return Reflect.apply(_target, thisArg, args);\n }\n\n let method = requestInit?.method ?? (input instanceof Request ? input.method : 'GET');\n method = method.toUpperCase();\n\n const path = extractPathname(input);\n\n return startSpan(\n {\n name: `${method} ${path}`,\n onlyIfParent: true,\n attributes: {\n [SENTRY_OP]: INTERNAL_REQUEST_OP,\n [SENTRY_ORIGIN]: INTERNAL_REQUEST_ORIGIN,\n },\n },\n () => {\n // The flag only needs to cover the synchronous dispatch start, where the orchestrion\n // channel would fire and open its duplicate span. `Reflect.apply` returns the pending\n // promise synchronously, so `finally` clears it before any nested `.request()` runs.\n setInternalRequestSpanActive(true);\n try {\n return Reflect.apply(_target, thisArg, [input, requestInit, ...rest]);\n } finally {\n setInternalRequestSpanActive(false);\n }\n },\n );\n },\n ...sentryOriginalTraps(originalRequest),\n });\n\n DEBUG_BUILD && debug.log('[hono] Patched app.request for internal dispatch tracing.');\n}\n","import { isObjectLike } from '@sentry/core';\n\n/**\n * Default implementation of the `shouldHandleError` callback.\n *\n * Returns `true` (capture) for 5xx errors and any error without a `status` property\n *\n * Returns `false` (skip) for 3xx and 4xx errors (they still generate spans and transactions for tracing)\n *\n * Checks any error-like value that carries a numeric `status` property. This covers\n * Hono's `HTTPException`, third-party middleware errors, and custom error subclasses.\n */\nexport function defaultShouldHandleError(error: unknown): boolean {\n if (!isObjectLike(error)) {\n return true;\n }\n\n const status = error.status;\n\n return !(typeof status === 'number' && status >= 300 && status < 500);\n}\n","import { SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { MIDDLEWARE } from '@sentry/conventions/op';\nimport {\n getActiveSpan,\n getOriginalFunction,\n getRootSpan,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n type WrappedFunction,\n} from '@sentry/core';\nimport { type MiddlewareHandler } from './honoTypes';\nimport { SENTRY_HONO_MIDDLEWARE } from './constants';\nimport { defaultShouldHandleError } from './defaultShouldHandleError';\nimport { sentryOriginalTraps } from './sentryOriginalTraps';\n\nconst MIDDLEWARE_ORIGIN = 'auto.middleware.hono';\n\n/**\n * Wraps a Hono middleware handler so that its execution is traced as a Sentry span.\n * Explicitly parents each span under the root (transaction) span so that all middleware\n * spans are siblings — even when OTel instrumentation introduces nested active contexts\n * (onion order: A → B → handler → B → A would otherwise nest B under A).\n */\nexport function wrapMiddlewareWithSpan(handler: MiddlewareHandler): MiddlewareHandler {\n // Never turn Sentry's own request/response middleware into a middleware span — e.g. when an\n // auto-instrumented sub-app carrying it is mounted into a parent and its handlers get wrapped.\n if ((handler as unknown as Record<PropertyKey, unknown>)[SENTRY_HONO_MIDDLEWARE]) {\n return handler;\n }\n\n if (getOriginalFunction(handler as unknown as WrappedFunction)) {\n return handler;\n }\n\n return new Proxy(handler, {\n async apply(_target, _thisArg, args: Parameters<MiddlewareHandler>) {\n const [context, next] = args;\n const activeSpan = getActiveSpan();\n const rootSpan = activeSpan ? getRootSpan(activeSpan) : undefined;\n const span = startInactiveSpan({\n name: handler.name || '<anonymous>',\n onlyIfParent: true,\n parentSpan: rootSpan,\n attributes: {\n [SENTRY_OP]: MIDDLEWARE,\n [SENTRY_ORIGIN]: MIDDLEWARE_ORIGIN,\n },\n });\n\n try {\n return await handler(context, next);\n } catch (error) {\n // Error capture is handled by `responseHandler` via `context.error`, so this wrapper only sets\n // span status (based on our default \"error\" conditions) and rethrows (no `captureException`).\n if (defaultShouldHandleError(error)) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n throw error;\n } finally {\n span.end();\n }\n },\n ...sentryOriginalTraps(handler),\n });\n}\n","import { debug } from '@sentry/core';\nimport type { Env, Hono, MiddlewareHandler } from './honoTypes';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { wrapMiddlewareWithSpan } from './wrapMiddlewareSpan';\n\n// oxlint-disable-next-line typescript/no-explicit-any\nconst patchedUseInstances = new WeakSet<Hono<any>>();\n// oxlint-disable-next-line typescript/no-explicit-any\nconst patchedMethodInstances = new WeakSet<Hono<any>>();\n\nconst HTTP_METHODS = ['get', 'post', 'put', 'delete', 'options', 'patch', 'all', 'query'] as const;\n\n/**\n * Patches `app.use` (instance own property) on a Hono instance to instrument middleware at registration time.\n *\n * Must be per-instance because `use` is a class field, not a prototype method.\n * Idempotent.\n */\nexport function patchAppUse<E extends Env>(app: Hono<E>): void {\n if (patchedUseInstances.has(app)) {\n DEBUG_BUILD && debug.log('[hono] app.use already patched — skipping.');\n return;\n }\n\n patchedUseInstances.add(app);\n\n app.use = new Proxy(app.use, {\n apply(target: typeof app.use, thisArg: typeof app, args: Parameters<typeof app.use>): ReturnType<typeof app.use> {\n const [first, ...rest] = args as [unknown, ...MiddlewareHandler[]];\n\n if (typeof first === 'string') {\n const wrappedHandlers = rest.map(handler => wrapMiddlewareWithSpan(handler));\n return Reflect.apply(target, thisArg, [first, ...wrappedHandlers]);\n }\n\n const allHandlers = [first as MiddlewareHandler, ...rest].map(handler => wrapMiddlewareWithSpan(handler));\n return Reflect.apply(target, thisArg, allHandlers);\n },\n });\n}\n\n/**\n * Patches HTTP method class fields to instrument inline middleware at registration time.\n *\n * For `app.get('/path', mw1, mw2, handler)`, all handlers except the last are middleware and get wrapped with spans.\n * The final handler (the route handler) is already covered by the root http.server transaction.\n */\nexport function patchHttpMethodHandlers<E extends Env>(app: Hono<E>): void {\n if (patchedMethodInstances.has(app)) {\n DEBUG_BUILD && debug.log('[hono] HTTP method handlers already patched - skipping.');\n return;\n }\n\n patchedMethodInstances.add(app);\n\n for (const method of HTTP_METHODS) {\n patchRegistrationMethod(app, method, wrapInlineMiddleware);\n }\n\n patchRegistrationMethod(app, 'on', args => {\n // .on(method, path, ...handlers) — first two args are method and path\n const [method, path, ...handlers] = args;\n return [method, path, ...wrapInlineMiddleware(handlers)];\n });\n}\n\n/**\n * Given `[path?, ...handlers]` or `[...handlers]`, wraps all handlers except the last one with spans.\n * The last handler is the route handler and is left as-is.\n */\nfunction wrapInlineMiddleware(args: unknown[]): unknown[] {\n const hasPathPrefix = typeof args[0] === 'string';\n const handlersStart = hasPathPrefix ? 1 : 0;\n const handlers = args.slice(handlersStart) as MiddlewareHandler[];\n\n if (handlers.length <= 1) {\n return args;\n }\n\n const wrapped = [...args];\n for (let i = handlersStart; i < wrapped.length - 1; i++) {\n wrapped[i] = wrapMiddlewareWithSpan(wrapped[i] as MiddlewareHandler);\n }\n return wrapped;\n}\n\nfunction patchRegistrationMethod(app: object, method: string, transformArgs: (args: unknown[]) => unknown[]): void {\n const registration: unknown = Reflect.get(app, method);\n if (typeof registration !== 'function') {\n return;\n }\n\n const patchedRegistration = new Proxy(registration, {\n apply(target, thisArg, args: unknown[]) {\n return Reflect.apply(target, thisArg, transformArgs(args));\n },\n });\n Reflect.set(app, method, patchedRegistration);\n}\n","import type { HonoRoute } from './honoTypes';\n\n// Hono 4 stores the original (unwrapped) handler under this key when it wraps a sub-app's handlers\n// for a custom `onError`. Unwrapping it lets us inspect the real handler instead of the wrapper.\n// Hono 5 does not wrap them.\n// See https://github.com/honojs/hono/blob/9f0dadf141a3242a6c3b77462c7d33c6ce0f599d/src/hono-base.ts#L224-L226\nconst COMPOSED_HANDLER = '__COMPOSED_HANDLER';\n\n/**\n * Infers whether a Hono route entry is a middleware (rather than a route handler).\n *\n * Hono has no \"isMiddleware\" flag, so we rely on arity: middleware is `(context, next)` (arity >= 2)\n * while route handlers are `(context)` (arity < 2). `onError`-wrapped sub-app handlers are unwrapped\n * first so we check the original handler's arity, not the wrapper's `(c, next)` signature.\n * https://github.com/honojs/hono/blob/97c6fe1f12298c715eb7b2da65b4b6e0d81682bb/src/utils/handler.ts#L8\n *\n * This is only one signal — callers that must classify inline middleware sharing a method+path with\n * their handler additionally need positional information (`getMiddlewareFlags`).\n */\nexport function isMiddleware(handler: unknown): boolean {\n if (typeof handler !== 'function') {\n return false;\n }\n\n const composed = (handler as unknown as Record<string, unknown>)[COMPOSED_HANDLER];\n const original = typeof composed === 'function' ? composed : handler;\n\n return (original as (...args: unknown[]) => unknown).length >= 2;\n}\n\n/**\n * Tells for each route if it is a middleware. Hono has no flag for this. In a method+path group, the\n * last handler is the route handler (`app.get('/path', mw, handler)`). `.use()` adds middleware with\n * method `ALL` and no route handler, so for `ALL` routes the arity also counts. Arity alone is not\n * enough, because a route handler can declare an unused `next`.\n */\nexport function getMiddlewareFlags(routes: HonoRoute[]): boolean[] {\n // `\\0` cannot appear in an HTTP method or a URL path.\n const groupKey = (route: HonoRoute): string => `${route.method}\\0${route.path}`;\n const lastIndexByKey = new Map(routes.map((route, i) => [groupKey(route), i]));\n\n return routes.map(\n (route, i) => lastIndexByKey.get(groupKey(route)) !== i || (route.method === 'ALL' && isMiddleware(route.handler)),\n );\n}\n","import { debug, getOriginalFunction } from '@sentry/core';\nimport type { WrappedFunction } from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type { Hono, HonoRoute } from './honoTypes';\nimport { getMiddlewareFlags } from './isMiddleware';\nimport { patchAppRequest } from './patchAppRequest';\nimport { wrapMiddlewareWithSpan } from './wrapMiddlewareSpan';\nimport { sentryOriginalTraps } from './sentryOriginalTraps';\n\nexport type { HonoRoute };\n\n// oxlint-disable-next-line typescript/no-explicit-any\ntype HonoAny = Hono<any>;\n\nexport type RouteHookHandle = {\n activate: () => void;\n getPendingSubApps: () => Set<HonoAny>;\n};\n\ntype HonoBaseProto = {\n route?: (path: string, app: HonoAny) => HonoAny;\n __sentryRouteHook__?: RouteHookHandle;\n};\n\n/**\n * Creates the two-phase state machine for the route hook.\n *\n * - Pre-activation: collects sub-app references into a pending set.\n * - Post-activation: instruments sub-apps immediately at mount time.\n */\nfunction createRouteHook(): { handle: RouteHookHandle; onSubAppMounted: (subApp: HonoAny) => void } {\n const pendingSubApps = new Set<HonoAny>();\n let activated = false;\n\n return {\n handle: {\n activate: () => {\n activated = true;\n },\n getPendingSubApps: () => pendingSubApps,\n },\n onSubAppMounted: (subApp: HonoAny) => {\n if (activated) {\n DEBUG_BUILD && debug.log(`[hono] Instrumenting sub-app at mount time (${subApp.routes.length} routes).`);\n wrapSubAppMiddleware(subApp.routes);\n patchAppRequest(subApp);\n } else {\n DEBUG_BUILD &&\n debug.log(`[hono] Collecting sub-app for deferred instrumentation (${subApp.routes.length} routes).`);\n pendingSubApps.add(subApp);\n }\n },\n };\n}\n\n/**\n * Installs a hook on `HonoBase.prototype.route` to intercept sub-app mounting.\n *\n * `honoBaseProto` is `HonoBase.prototype`, where `route` is defined — one level above the concrete\n * subclass. Callers derive it from a live app instance (`Object.getPrototypeOf(Object.getPrototypeOf(app))`)\n * or from the `Hono` class (`Object.getPrototypeOf(Hono.prototype)`), so the instrumentation never\n * imports `hono` itself.\n *\n * Returns a handle with `activate()` and `getPendingSubApps()`.\n * Idempotent: subsequent calls return the same handle\n */\nexport function installRouteHookOnPrototype(honoBaseProto: HonoBaseProto): RouteHookHandle {\n const noopHandle: RouteHookHandle = { activate: () => {}, getPendingSubApps: () => new Set() };\n\n if (!honoBaseProto || typeof honoBaseProto.route !== 'function') {\n DEBUG_BUILD && debug.warn('[hono] Could not find HonoBase.prototype.route — sub-app instrumentation disabled.');\n return noopHandle;\n }\n\n // Already patched\n if (getOriginalFunction(honoBaseProto.route as unknown as WrappedFunction)) {\n return honoBaseProto.__sentryRouteHook__ ?? noopHandle;\n }\n\n const originalRoute = honoBaseProto.route;\n const { handle, onSubAppMounted } = createRouteHook();\n\n honoBaseProto.route = new Proxy(originalRoute, {\n apply(_target, thisArg, args: [string, HonoAny]) {\n const [, subApp] = args;\n if (subApp && Array.isArray(subApp.routes)) {\n onSubAppMounted(subApp);\n }\n\n return Reflect.apply(_target, thisArg, args);\n },\n ...sentryOriginalTraps(originalRoute),\n });\n honoBaseProto.__sentryRouteHook__ = handle;\n\n DEBUG_BUILD && debug.log('[hono] Installed route hook on HonoBase.prototype.');\n\n return handle;\n}\n\n// Hono 5 registers `onError()` and `notFound()` handlers as `(c, next)` middleware routes with these\n// methods. Like on Hono 4, they get no middleware span.\nconst ERROR_AND_NOT_FOUND_METHODS = new Set(['@ERROR', '@NOT_FOUND']);\n\n/**\n * Wraps the middleware handlers of a sub-app's routes in spans.\n */\nexport function wrapSubAppMiddleware(routes: HonoRoute[]): void {\n const middlewareFlags = getMiddlewareFlags(routes);\n for (const [i, route] of routes.entries()) {\n if (middlewareFlags[i] && !ERROR_AND_NOT_FOUND_METHODS.has(route.method) && typeof route.handler === 'function') {\n route.handler = wrapMiddlewareWithSpan(route.handler);\n }\n }\n}\n","import { debug } from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type { Env, Hono } from './honoTypes';\nimport { patchAppRequest } from './patchAppRequest';\nimport { patchAppUse, patchHttpMethodHandlers } from './patchAppUse';\nimport { type RouteHookHandle, installRouteHookOnPrototype, wrapSubAppMiddleware } from './patchRoute';\n\n// Lazily set by the first call to earlyPatchHono or applyPatches.\nlet _routeHook: RouteHookHandle | undefined;\n\n/**\n * Hooks `HonoBase.prototype.route` at import time, before `sentry()` runs.\n *\n * Collecting sub-app references early ensures nothing is missed if sub-apps are mounted synchronously\n * before the `sentry()` middleware is registered. The `Hono` class is passed in by the caller (the\n * `@sentry/hono` SDK, where `hono` is a peer dependency) so this module never imports `hono` itself;\n * `HonoBase.prototype` is one level above the class prototype.\n */\nexport function earlyPatchHono(honoClass: { prototype: object }): void {\n _routeHook ??= installRouteHookOnPrototype(Object.getPrototypeOf(honoClass.prototype));\n}\n\n/**\n * Instruments a Hono app instance for Sentry tracing in middleware and route handlers.\n *\n * - `use` and `request` are per-instance class fields → must be patched on the instance.\n * - `route` is a prototype method → hooked once globally, covers all instances.\n * - Retroactively instruments sub-apps mounted before `sentry()` was called.\n */\nexport function applyPatches<E extends Env>(app: Hono<E>): void {\n // `HonoBase.prototype` (where `route` lives) is two levels up from the app instance:\n // app → Hono.prototype → HonoBase.prototype. Deriving it from the live app avoids importing `hono`.\n // Always call — installRouteHookOnPrototype is idempotent and returns existing handle when prototype already patched\n _routeHook = installRouteHookOnPrototype(Object.getPrototypeOf(Object.getPrototypeOf(app)));\n\n // `app.use` (instance own property) — wraps middleware at registration time on this instance.\n patchAppUse(app);\n\n // `app.get`, `app.post`, … (instance own properties) — wraps inline middleware (all-but-last handler).\n patchHttpMethodHandlers(app);\n\n patchAppRequest(app);\n\n _routeHook.activate();\n\n const pendingSubApps = _routeHook.getPendingSubApps();\n\n if (pendingSubApps.size > 0) {\n DEBUG_BUILD &&\n debug.log(\n `[hono] ${pendingSubApps.size} sub-app(s) were mounted before sentry(). Tracing is applied retroactively. Consider registering sentry() before calling app.route().`,\n );\n }\n\n for (const subApp of pendingSubApps) {\n wrapSubAppMiddleware(subApp.routes);\n patchAppRequest(subApp);\n }\n\n pendingSubApps.clear();\n}\n\n/**\n * Applies Sentry's Hono span patches to an app instance.\n *\n * Typed loosely (`object`) so the real `hono` `Hono<E, S, P>` type used by the `@sentry/hono` SDK is\n * accepted without a cast; internally it is treated as the vendored {@link Hono} shape.\n */\nexport function applyHonoPatches(app: object): void {\n applyPatches(app as Hono);\n}\n","import type { Context } from './honoTypes';\n\nexport type HonoRuntime = 'node' | 'bun' | 'deno' | 'cloudflare';\n\n/** The client side of the request's connection. */\nexport interface ConnInfo {\n address?: string;\n port?: number;\n transport?: string;\n addressType?: string;\n}\n\n// What the runtime adapters pass to `app.fetch` as `c.env`. The readers copy Hono's `getConnInfo` helpers,\n// which Hono 5 moved out of `hono`. The casts are unchecked, and `readConnInfo` catches a read that throws.\ntype NodeBindings = {\n incoming?: { socket?: { remoteAddress?: string; remotePort?: number; remoteFamily?: string } };\n};\ntype BunServer = {\n requestIP?: (request: Request) => { address?: string; port?: number; family?: string } | null;\n};\ntype DenoServeHandlerInfo = { remoteAddr?: { hostname?: string; port?: number; transport?: string } };\n\nconst READERS: Record<HonoRuntime, (context: Context) => ConnInfo | undefined> = {\n // https://github.com/honojs/node-server/blob/v2.1.5/src/conninfo.ts\n node: context => {\n const env = context.env as (NodeBindings & { server?: NodeBindings }) | undefined;\n const socket = (env?.server ?? env)?.incoming?.socket;\n return socket\n ? { address: socket.remoteAddress, port: socket.remotePort, addressType: socket.remoteFamily }\n : undefined;\n },\n // https://github.com/honojs/hono/blob/v4.13.13/src/adapter/bun/conninfo.ts\n bun: context => {\n const env = context.env as (BunServer & { server?: BunServer }) | undefined;\n const info = (env?.server ?? env)?.requestIP?.(context.req.raw);\n return info ? { address: info.address, port: info.port, addressType: info.family } : undefined;\n },\n // https://github.com/honojs/hono/blob/v4.13.13/src/adapter/deno/conninfo.ts\n deno: context => {\n const remoteAddr = (context.env as DenoServeHandlerInfo | undefined)?.remoteAddr;\n return remoteAddr\n ? { address: remoteAddr.hostname, port: remoteAddr.port, transport: remoteAddr.transport }\n : undefined;\n },\n // `c.env` holds the user's bindings here, so only the header is read.\n // https://github.com/honojs/hono/blob/v4.13.13/src/adapter/cloudflare-workers/conninfo.ts\n cloudflare: context => {\n const address = context.req.raw.headers.get('cf-connecting-ip');\n return address ? { address } : undefined;\n },\n};\n\n/** Gives `undefined` when the runtime object is missing or a read throws. */\nexport function readConnInfo(context: Context, runtime: HonoRuntime): ConnInfo | undefined {\n try {\n return READERS[runtime](context);\n } catch {\n return undefined;\n }\n}\n","import type { Context } from './honoTypes';\n\n/**\n * Checks whether the given Hono context has a fetch event.\n */\nexport function hasFetchEvent(c: Context): boolean {\n let hasFetchEvent = true;\n try {\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n c.event;\n } catch {\n hasFetchEvent = false;\n }\n return hasFetchEvent;\n}\n","import { addNonEnumerableProperty, isPlainObject } from '@sentry/core';\nimport type { Context, HonoRoute, MatchedHandler } from './honoTypes';\nimport { sentryOriginalTraps } from './sentryOriginalTraps';\n\n// `routeIndex` of the route handler that started last. `Symbol.for` shares it between SDK copies.\nconst ROUTE_HANDLER_INDEX = Symbol.for('sentry.hono.routeHandlerIndex');\n\n// Marks the index wrapper. The router reuses the match result for each request to a route, so without\n// it the wrappers pile up. A span wrapper does not count: a route handler from `app.use()` has one and\n// still needs this wrapper.\nconst RECORDS_ROUTE_HANDLER_INDEX = Symbol.for('sentry.hono.recordsRouteHandlerIndex');\n\nconst ON_ROUTE_HANDLER_START = Symbol.for('sentry.hono.onRouteHandlerStart');\n\nfunction isMatchedHandler(entry: unknown): entry is MatchedHandler {\n const pair: unknown = Array.isArray(entry) ? entry[0] : undefined;\n if (!Array.isArray(pair)) {\n return false;\n }\n\n const [handler, route]: unknown[] = pair;\n return (\n typeof handler === 'function' &&\n isPlainObject(route) &&\n typeof route.method === 'string' &&\n typeof route.path === 'string' &&\n typeof route.handler === 'function'\n );\n}\n\n/** The match result is internal to Hono. The SDK uses it only in the shape that `compose` reads. */\nexport function isMatchedHandlerList(handlers: unknown): handlers is MatchedHandler[] {\n return Array.isArray(handlers) && handlers.every(isMatchedHandler);\n}\n\n/**\n * Reads the match result like `hono/route` does (Hono 4.8+). Hono does not export the getter's symbol,\n * so this looks for a symbol getter that returns a match result.\n * https://github.com/honojs/hono/blob/v5.0.0-rc.1/src/helper/route/index.ts#L32-L34\n */\nexport function getMatchedHandlers(context: Context): MatchedHandler[] | undefined {\n const requestProto: object | null = Object.getPrototypeOf(context.req);\n if (!requestProto) {\n return undefined;\n }\n\n for (const key of Object.getOwnPropertySymbols(requestProto)) {\n if (typeof Object.getOwnPropertyDescriptor(requestProto, key)?.get !== 'function') {\n continue;\n }\n const matchResult: unknown = Reflect.get(context.req, key);\n if (Array.isArray(matchResult) && isMatchedHandlerList(matchResult[0])) {\n return matchResult[0];\n }\n }\n return undefined;\n}\n\n/** Runs `callback` each time a route handler of this request starts. */\nexport function onRouteHandlerStart(context: Context, callback: () => void): void {\n addNonEnumerableProperty(context, ON_ROUTE_HANDLER_START, callback);\n}\n\n/**\n * Wraps the route handlers so that each stores `c.req.routeIndex` when it starts. Hono 5 resets the\n * index after `next()` (https://github.com/honojs/hono/pull/4424).\n *\n * Wraps only if more than one route handler matched. A single one is the handler that responds. Arity\n * cannot tell if a handler calls `next()`: it does not count rest parameters or a default `next`.\n * Returns `true` if it wrapped.\n *\n * Safe to call during the request: `compose` reads each handler only when it calls it.\n */\nexport function wrapRouteHandlers(handlers: MatchedHandler[], middlewareFlags: boolean[]): boolean {\n const routeHandlerCount = middlewareFlags.filter(flag => !flag).length;\n if (routeHandlerCount < 2) {\n return false;\n }\n\n for (const [i, [pair]] of handlers.entries()) {\n if (!middlewareFlags[i]) {\n pair[0] = recordRouteHandlerIndex(pair[0]);\n }\n }\n return true;\n}\n\nfunction recordRouteHandlerIndex(handler: HonoRoute['handler']): HonoRoute['handler'] {\n if (Reflect.get(handler, RECORDS_ROUTE_HANDLER_INDEX)) {\n return handler;\n }\n\n const originalTraps = sentryOriginalTraps<HonoRoute['handler']>(handler);\n return new Proxy(handler, {\n apply(target, thisArg, args: [Context, ...unknown[]]) {\n const [context] = args;\n addNonEnumerableProperty(context, ROUTE_HANDLER_INDEX, context.req.routeIndex);\n const onStart: unknown = Reflect.get(context, ON_ROUTE_HANDLER_START);\n if (typeof onStart === 'function') {\n onStart();\n }\n return Reflect.apply(target, thisArg, args);\n },\n ...originalTraps,\n get(target, prop, receiver) {\n if (prop === RECORDS_ROUTE_HANDLER_INDEX) {\n return true;\n }\n return originalTraps.get?.(target, prop, receiver);\n },\n });\n}\n\nexport function getRecordedRouteHandlerIndex(context: Context): number | undefined {\n const index: unknown = Reflect.get(context, ROUTE_HANDLER_INDEX);\n return typeof index === 'number' ? index : undefined;\n}\n","import type { Context, HonoRoute } from './honoTypes';\nimport { SENTRY_HONO_MIDDLEWARE } from './constants';\nimport { getRecordedRouteHandlerIndex } from './matchResult';\n\n/**\n * Returns the path of the route that handles the request, or `undefined` if the request has no route.\n * Not the last matched route: a catch-all registered later also matches.\n */\nexport function resolveRouteName(\n context: Context,\n routes: HonoRoute[],\n middlewareFlags: boolean[],\n): string | undefined {\n const recordedIndex = getRecordedRouteHandlerIndex(context);\n const recorded = recordedIndex === undefined ? undefined : routes[recordedIndex];\n if (recorded) {\n return recorded.path;\n }\n\n // Hono runs the first matched route handler first. If a middleware returned early, it is the one that\n // would have run.\n const firstRouteHandler = routes.find((_route, i) => !middlewareFlags[i]);\n if (firstRouteHandler) {\n return firstRouteHandler.path;\n }\n\n // Only middleware matched, for example `app.use('/static/*', serveStatic())`. The Sentry middleware\n // and `/*` middleware say nothing about the route.\n for (let i = routes.length - 1; i >= 0; i--) {\n const route = routes[i];\n if (route && route.path !== '/*' && !isSentryMiddleware(route.handler)) {\n return route.path;\n }\n }\n return undefined;\n}\n\nfunction isSentryMiddleware(handler: unknown): boolean {\n return typeof handler === 'function' && Boolean(Reflect.get(handler, SENTRY_HONO_MIDDLEWARE));\n}\n","import { isError } from '@sentry/core';\n\n/**\n * Returns the value that a handler threw, so that `shouldHandleError` and the event get that value\n * and not Hono's wrapper.\n *\n * Hono 5 wraps a thrown non-Error before its error handlers run:\n * `new Error(typeof err === 'string' ? err : undefined, { cause: err })`.\n * The wrapper has no marker, so it is found by its shape. A user error with the same shape is also unwrapped.\n */\nexport function unwrapThrownValue(error: unknown): unknown {\n if (!isError(error) || error.constructor !== Error || !('cause' in error)) {\n return error;\n }\n\n const { cause } = error;\n if (isError(cause)) {\n return error;\n }\n\n const wrapperMessage = typeof cause === 'string' ? cause : '';\n return error.message === wrapperMessage ? cause : error;\n}\n","import {\n captureException,\n getActiveSpan,\n getClient,\n getDefaultIsolationScope,\n getIsolationScope,\n getRootSpan,\n INTERNAL_setSegmentNameSourceIfSegment,\n updateSpanName,\n type Scope,\n type Span,\n type SpanAttributes,\n spanToJSON,\n winterCGHeadersToDict,\n winterCGRequestToRequestData,\n} from '@sentry/core';\nimport { getClientIPAddress } from '@sentry/core/server';\nimport type { Context } from './honoTypes';\nimport { type HonoRuntime, readConnInfo } from './connInfo';\nimport { hasFetchEvent } from './hono-context';\nimport { defaultShouldHandleError } from './defaultShouldHandleError';\nimport { getMiddlewareFlags } from './isMiddleware';\nimport { getMatchedHandlers, onRouteHandlerStart, wrapRouteHandlers } from './matchResult';\nimport { resolveRouteName } from './resolveRouteName';\nimport { type SentryHonoMiddlewareOptions } from './types';\nimport { unwrapThrownValue } from './unwrapThrownValue';\nimport {\n CLIENT_ADDRESS,\n CLIENT_PORT,\n HTTP_ROUTE,\n NETWORK_PEER_ADDRESS,\n NETWORK_PEER_PORT,\n NETWORK_TRANSPORT,\n NETWORK_TYPE,\n} from '@sentry/conventions/attributes';\n\n/**\n * Request handler for Hono framework\n */\nexport function requestHandler(context: Context, runtime: HonoRuntime): void {\n const isolationScope = getCurrentIsolationScope();\n // Read now: when a route handler starts, a user span can be active.\n const span = getActiveSpan();\n\n // Hono 5 removes `c.req.matchedRoutes`. Before Hono 4.8, it is the only source.\n const matchedHandlers = getMatchedHandlers(context);\n const routes = matchedHandlers?.map(([[, route]]) => route) ?? context.req.matchedRoutes ?? [];\n const middlewareFlags = getMiddlewareFlags(routes);\n const nameSpan = (): void =>\n updateSpanRouteName(isolationScope, span, context, resolveRouteName(context, routes, middlewareFlags));\n\n // Name early, so that events from the handlers carry the route.\n nameSpan();\n\n // A route handler that calls `next()` passes the request on, so rename when each one starts. Without\n // the getter, only the Context hook can wrap the route handlers.\n if (!matchedHandlers || wrapRouteHandlers(matchedHandlers, middlewareFlags)) {\n onRouteHandlerStart(context, nameSpan);\n }\n\n isolationScope.setSDKProcessingMetadata({\n normalizedRequest: winterCGRequestToRequestData(hasFetchEvent(context) ? context.event.request : context.req.raw),\n });\n\n setConnInfoAttributes(context, runtime, isolationScope);\n}\n\nfunction getCurrentIsolationScope(): Scope {\n const defaultScope = getDefaultIsolationScope();\n const currentIsolationScope = getIsolationScope();\n\n return defaultScope === currentIsolationScope ? defaultScope : currentIsolationScope;\n}\n\n/**\n * Adds HTTP connection info (client IP, port, transport, address type) from the runtime to the root\n * (server) span and the isolation scope.\n *\n * Keeps attributes that the runtime SDK already set: it reads forwarding headers, while the runtime\n * objects only know the socket peer, which can be a proxy.\n */\nfunction setConnInfoAttributes(context: Context, runtime: HonoRuntime, isolationScope: Scope): void {\n const activeSpan = getActiveSpan();\n if (!activeSpan) {\n return;\n }\n\n const connInfo = readConnInfo(context, runtime);\n if (!connInfo) {\n return;\n }\n\n const { address, port, transport, addressType } = connInfo;\n\n // Only collect client IP if `userInfo` is enabled (this is primarily for setting data with `.setUser`, but in this case we cannot check for `dataCollection.headers` or similar)\n const ipAddress = address && getClient()?.getDataCollectionOptions().userInfo ? address : undefined;\n\n const rootSpan = getRootSpan(activeSpan);\n const existingAttributes = spanToJSON(rootSpan).attributes ?? {};\n // Pair `client.port` only with the socket address: behind a proxy, the socket port is the proxy's.\n const writesClientAddress = ipAddress !== undefined && existingAttributes[CLIENT_ADDRESS] === undefined;\n rootSpan.setAttributes(\n onlyNewAttributes(\n {\n [CLIENT_PORT]: writesClientAddress ? port : undefined,\n [NETWORK_PEER_PORT]: port,\n [NETWORK_TRANSPORT]: transport,\n [NETWORK_TYPE]: addressType?.toLowerCase(),\n [CLIENT_ADDRESS]: ipAddress,\n [NETWORK_PEER_ADDRESS]: ipAddress,\n },\n existingAttributes,\n ),\n );\n\n if (ipAddress) {\n // Like `RequestData`, prefer the forwarding header: behind a proxy, the socket address is the proxy's.\n const userIpAddress = getClientIPAddress(winterCGHeadersToDict(context.req.raw.headers)) || ipAddress;\n isolationScope.setUser({ ...isolationScope.getUser(), ip_address: userIpAddress });\n }\n}\n\n/** Keeps the defined attributes that are not on the span yet. */\nfunction onlyNewAttributes(attributes: SpanAttributes, existingAttributes: Record<string, unknown>): SpanAttributes {\n return Object.fromEntries(\n Object.entries(attributes).filter(([key, value]) => value !== undefined && existingAttributes[key] === undefined),\n );\n}\n\n/**\n * Response handler for Hono framework\n */\nexport function responseHandler(\n context: Context,\n shouldHandleError?: SentryHonoMiddlewareOptions['shouldHandleError'],\n): void {\n captureContextError(context, shouldHandleError);\n}\n\n/**\n * Captures an unhandled context error, gated by the user's `shouldHandleError` (or the default).\n *\n * A deduplicated middleware calls it directly to report the error of its own context — e.g. the inner\n * context of an internal `.request()` whose route threw but whose failed response the outer handler\n * swallowed.\n */\nexport function captureContextError(\n context: Context,\n shouldHandleError?: SentryHonoMiddlewareOptions['shouldHandleError'],\n): void {\n if (context.error) {\n const error = unwrapThrownValue(context.error);\n if ((shouldHandleError ?? defaultShouldHandleError)(error)) {\n captureException(error, {\n mechanism: { handled: false, type: 'auto.http.hono.context_error' },\n });\n }\n }\n}\n\nfunction updateSpanRouteName(\n isolationScope: Scope,\n activeSpan: Span | undefined,\n context: Context,\n route: string | undefined,\n): void {\n // Without a route, keep the span name from the runtime.\n if (route === undefined) {\n return;\n }\n\n const routeName = `${context.req.method} ${route}`;\n\n if (activeSpan) {\n activeSpan.updateName(routeName);\n\n const rootSpan = getRootSpan(activeSpan);\n updateSpanName(rootSpan, routeName);\n INTERNAL_setSegmentNameSourceIfSegment(rootSpan, 'route');\n rootSpan.setAttribute(HTTP_ROUTE, route);\n }\n\n isolationScope.setTransactionName(routeName);\n}\n","import { addNonEnumerableProperty, getDefaultIsolationScope, getIsolationScope } from '@sentry/core';\nimport type { HonoRuntime } from './connInfo';\nimport { SENTRY_HONO_MIDDLEWARE } from './constants';\nimport type { Context, MiddlewareHandler } from './honoTypes';\nimport { captureContextError, requestHandler, responseHandler } from './middlewareHandlers';\nimport type { SentryHonoMiddlewareOptions } from './types';\n\n// `Symbol.for` (global registry) so the markers are shared even if this module is evaluated from more\n// than one copy of `@sentry/server-utils`.\nconst HONO_REQUEST_HANDLED = Symbol.for('sentry.hono.requestHandled');\n// The effective `shouldHandleError` for the request, recorded even by a deduplicated middleware so a\n// user-provided callback wins over the default (see below).\nconst HONO_SHOULD_HANDLE_ERROR = Symbol.for('sentry.hono.shouldHandleError');\n\nexport interface CreateHonoRequestMiddlewareOptions {\n /** Selects where the connection info is read from. */\n runtime: HonoRuntime;\n\n /** Static `shouldHandleError` callback (Node/Bun/Deno). */\n shouldHandleError?: SentryHonoMiddlewareOptions['shouldHandleError'];\n\n /**\n * Resolves `shouldHandleError` per request from the context. Cloudflare accepts\n * middleware options as a function of `env`, so the callback is only known once a\n * request comes in. When provided, this wins over the static `shouldHandleError`.\n */\n resolveShouldHandleError?: (context: Context) => SentryHonoMiddlewareOptions['shouldHandleError'];\n}\n\n/**\n * The object that carries the per-request dedup/config markers.\n *\n * Prefer the per-request isolation scope over the Hono `Context`, so the request is treated as one\n * even when several Sentry middlewares run for it:\n * - a mounted sub-app that carries its own auto-registered middleware (same context, same scope),\n * - an internal `app.request()` dispatch, which runs in a *new* Hono context but the *same*\n * isolation scope (so it must not re-record the transaction name or overwrite the request data),\n * - a manual `sentry()` middleware registered alongside the auto-instrumentation.\n *\n * When there is no per-request isolation scope (the default scope), fall back to the context so that\n * at least same-context duplicates are still deduplicated.\n */\nfunction getRequestScope(context: Context): Record<PropertyKey, unknown> {\n const isolationScope = getIsolationScope();\n const target: object = isolationScope === getDefaultIsolationScope() ? context : isolationScope;\n return target as Record<PropertyKey, unknown>;\n}\n\n/**\n * Builds the core Sentry request/response Hono middleware: it names the transaction, records the\n * request, and captures unhandled context errors around `next()`.\n *\n * Idempotent per request (see {@link getRequestScope}), so duplicate registrations — a manual\n * `sentry()` alongside the auto-instrumentation, mounted sub-apps, internal `.request()` dispatches —\n * are all safe and run the handling exactly once.\n *\n * A user-provided `shouldHandleError` still takes effect even when the middleware carrying it is\n * deduplicated behind the auto-instrumentation (which is prepended first, per request, from the\n * `Context` constructor hook): the deduplicated middleware records its callback on the request scope, and the\n * middleware that actually runs `responseHandler` uses it in preference to its own default.\n */\nexport function createHonoRequestMiddleware(options: CreateHonoRequestMiddlewareOptions): MiddlewareHandler {\n const middleware: MiddlewareHandler = async (context, next) => {\n const scope = getRequestScope(context);\n\n const shouldHandleError = options.resolveShouldHandleError\n ? options.resolveShouldHandleError(context)\n : options.shouldHandleError;\n // Record a user-provided callback so it wins even if this middleware is deduplicated. Runs before\n // the dedup check so a later manual `sentry({ shouldHandleError })` overrides the auto default.\n if (shouldHandleError) {\n addNonEnumerableProperty(scope, HONO_SHOULD_HANDLE_ERROR, shouldHandleError);\n }\n\n if (scope[HONO_REQUEST_HANDLED]) {\n await next();\n // A deduplicated middleware still reports errors from its own context — e.g. an inner\n // `.request()` whose route threw but whose failed response the outer handler swallowed, so the\n // outer context never sees the error. Route naming and request data stay owned by the request\n // that ran first, so only the error is captured here.\n const dedupShouldHandleError =\n (scope[HONO_SHOULD_HANDLE_ERROR] as SentryHonoMiddlewareOptions['shouldHandleError']) ?? shouldHandleError;\n captureContextError(context, dedupShouldHandleError);\n return;\n }\n addNonEnumerableProperty(scope, HONO_REQUEST_HANDLED, true);\n\n try {\n requestHandler(context, options.runtime);\n\n await next(); // Handler runs in between Request above ⤴ and Response below ⤵\n\n const effectiveShouldHandleError =\n (scope[HONO_SHOULD_HANDLE_ERROR] as SentryHonoMiddlewareOptions['shouldHandleError']) ?? shouldHandleError;\n responseHandler(context, effectiveShouldHandleError);\n } finally {\n // An isolation scope that outlives the request (e.g. forked once around the whole server on a\n // runtime without per-request isolation) must not dedupe the next request against this one.\n addNonEnumerableProperty(scope, HONO_REQUEST_HANDLED, undefined);\n addNonEnumerableProperty(scope, HONO_SHOULD_HANDLE_ERROR, undefined);\n }\n };\n\n addNonEnumerableProperty(middleware, SENTRY_HONO_MIDDLEWARE, true);\n return middleware;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAgBA,SAAgB,gCAAgC,OAAqB;CACnE,MAAM,cAAA,GAAaA,aAAAA,cAAAA,CAAc;CACjC,IAAI,CAAC,YACH;CAEF,MAAM,YAAA,GAAWC,aAAAA,YAAAA,CAAY,UAAU;CACvC,IAAI,CAAC,UACH;CAGF,MAAM,cAAA,GAAaC,aAAAA,WAAAA,CAAW,QAAQ,CAAC,CAAC;CACxC,IAAI,WAAWC,+BAAAA,eAAe,eAC5B;CAIF,MAAM,SAAS,WAAWC,+BAAAA,wBAAwB,WAAWC,+BAAAA,gBAAgB;CAC7E,SAAS,aAAaC,+BAAAA,YAAY,KAAK;CACvC,SAAS,WAAW,GAAG,OAAO,GAAG,OAAO;CACxC,SAAS,aAAaC,+BAAAA,4BAA4B,OAAO;AAC3D;;;;;;;;ACfA,SAAgB,2CAA0E;CAQxF,MAAM,gBAAA,GAHuBC,aAAAA,wBAAAA,EAAAA,GAAwBC,aAAAA,eAAAA,CAAe,CAAC,CAAC,CAAC,2BAA2B,CAAC,EAC/F,qBAEyC,IAAIC,iBAAAA,kBAA8B;CAE/E,SAAS,YAAqD;EAC5D,MAAM,SAAS,aAAa,SAAS;EAErC,IAAI,QACF,OAA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