@sentry/server-utils 11.14.0 → 11.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/cjs/chunks/exports.js +604 -219
- package/build/cjs/chunks/exports.js.map +1 -1
- package/build/cjs/index.js +1028 -120
- package/build/cjs/index.js.map +1 -1
- package/build/cjs/index.request-handler.js +1 -0
- package/build/cjs/index.request-handler.js.map +1 -1
- package/build/esm/ai/anthropic-ai/index.js +32 -56
- package/build/esm/ai/anthropic-ai/index.js.map +1 -1
- package/build/esm/ai/anthropic-ai/streaming.js +10 -6
- package/build/esm/ai/anthropic-ai/streaming.js.map +1 -1
- package/build/esm/ai/anthropic-ai/tool-runner.js +18 -3
- package/build/esm/ai/anthropic-ai/tool-runner.js.map +1 -1
- package/build/esm/ai/anthropic-ai/utils.js +41 -3
- package/build/esm/ai/anthropic-ai/utils.js.map +1 -1
- package/build/esm/ai/core/span-hooks.js +23 -0
- package/build/esm/ai/core/span-hooks.js.map +1 -0
- package/build/esm/ai/core/time-to-first-chunk.js +14 -0
- package/build/esm/ai/core/time-to-first-chunk.js.map +1 -0
- package/build/esm/ai/core/utils.js +29 -3
- package/build/esm/ai/core/utils.js.map +1 -1
- package/build/esm/ai/flue/index.js +15 -12
- package/build/esm/ai/flue/index.js.map +1 -1
- package/build/esm/ai/flue/utils.js +25 -17
- package/build/esm/ai/flue/utils.js.map +1 -1
- package/build/esm/ai/google-genai/decisions.js +29 -1
- package/build/esm/ai/google-genai/decisions.js.map +1 -1
- package/build/esm/ai/google-genai/index.js +21 -8
- package/build/esm/ai/google-genai/index.js.map +1 -1
- package/build/esm/ai/google-genai/streaming.js +6 -2
- package/build/esm/ai/google-genai/streaming.js.map +1 -1
- package/build/esm/ai/langchain/embeddings.js +5 -2
- package/build/esm/ai/langchain/embeddings.js.map +1 -1
- package/build/esm/ai/langchain/index.js +82 -24
- package/build/esm/ai/langchain/index.js.map +1 -1
- package/build/esm/ai/langchain/utils.js +9 -1
- package/build/esm/ai/langchain/utils.js.map +1 -1
- package/build/esm/ai/langgraph/agent-span.js +13 -5
- package/build/esm/ai/langgraph/agent-span.js.map +1 -1
- package/build/esm/ai/langgraph/index.js +13 -15
- package/build/esm/ai/langgraph/index.js.map +1 -1
- package/build/esm/ai/langgraph/stream.js +4 -3
- package/build/esm/ai/langgraph/stream.js.map +1 -1
- package/build/esm/ai/langgraph/utils.js +17 -8
- package/build/esm/ai/langgraph/utils.js.map +1 -1
- package/build/esm/ai/mastra/classifier-evaluation.js.map +1 -1
- package/build/esm/ai/mastra/index.js +33 -16
- package/build/esm/ai/mastra/index.js.map +1 -1
- package/build/esm/ai/mastra/utils.js +3 -5
- package/build/esm/ai/mastra/utils.js.map +1 -1
- package/build/esm/ai/mistral/index.js +21 -7
- package/build/esm/ai/mistral/index.js.map +1 -1
- package/build/esm/ai/mistral/streaming.js +4 -2
- package/build/esm/ai/mistral/streaming.js.map +1 -1
- package/build/esm/ai/openai/index.js +19 -8
- package/build/esm/ai/openai/index.js.map +1 -1
- package/build/esm/ai/openai/mapping.js +48 -1
- package/build/esm/ai/openai/mapping.js.map +1 -1
- package/build/esm/ai/openai/streaming.js +7 -2
- package/build/esm/ai/openai/streaming.js.map +1 -1
- package/build/esm/ai/pi-ai/chat.js +18 -1
- package/build/esm/ai/pi-ai/chat.js.map +1 -1
- package/build/esm/ai/pi-ai/recording.js +34 -15
- package/build/esm/ai/pi-ai/recording.js.map +1 -1
- package/build/esm/ai/pi-durable/index.js +7 -2
- package/build/esm/ai/pi-durable/index.js.map +1 -1
- package/build/esm/ai/pi-durable/runs.js.map +1 -1
- package/build/esm/ai/pi-durable/tools.js +18 -3
- package/build/esm/ai/pi-durable/tools.js.map +1 -1
- package/build/esm/ai/typesafe/index.js +14 -6
- package/build/esm/ai/typesafe/index.js.map +1 -1
- package/build/esm/ai/workers-ai/index.js +26 -9
- package/build/esm/ai/workers-ai/index.js.map +1 -1
- package/build/esm/ai/workers-ai/streaming.js +6 -4
- package/build/esm/ai/workers-ai/streaming.js.map +1 -1
- package/build/esm/cron/common.js +16 -0
- package/build/esm/cron/common.js.map +1 -0
- package/build/esm/cron/cron.js +82 -0
- package/build/esm/cron/cron.js.map +1 -0
- package/build/esm/cron/index.js +13 -0
- package/build/esm/cron/index.js.map +1 -0
- package/build/esm/cron/node-cron.js +66 -0
- package/build/esm/cron/node-cron.js.map +1 -0
- package/build/esm/cron/node-schedule.js +43 -0
- package/build/esm/cron/node-schedule.js.map +1 -0
- package/build/esm/index.js +6 -2
- package/build/esm/index.js.map +1 -1
- package/build/esm/integrations/anthropic.js +25 -16
- package/build/esm/integrations/anthropic.js.map +1 -1
- package/build/esm/integrations/aws-sdk/index.js +1 -0
- package/build/esm/integrations/aws-sdk/index.js.map +1 -1
- package/build/esm/integrations/aws-sdk/services/ServicesExtensions.js +3 -0
- package/build/esm/integrations/aws-sdk/services/ServicesExtensions.js.map +1 -1
- package/build/esm/integrations/aws-sdk/services/bedrock-runtime.js +45 -12
- package/build/esm/integrations/aws-sdk/services/bedrock-runtime.js.map +1 -1
- package/build/esm/integrations/bullmq/contextManager.js +45 -0
- package/build/esm/integrations/bullmq/contextManager.js.map +1 -0
- package/build/esm/integrations/bullmq/index.js +44 -0
- package/build/esm/integrations/bullmq/index.js.map +1 -0
- package/build/esm/integrations/bullmq/meter.js +86 -0
- package/build/esm/integrations/bullmq/meter.js.map +1 -0
- package/build/esm/integrations/bullmq/span.js +114 -0
- package/build/esm/integrations/bullmq/span.js.map +1 -0
- package/build/esm/integrations/bullmq/tracer.js +62 -0
- package/build/esm/integrations/bullmq/tracer.js.map +1 -0
- package/build/esm/integrations/express/instrumentation.js +10 -1
- package/build/esm/integrations/express/instrumentation.js.map +1 -1
- package/build/esm/integrations/google-genai.js +17 -9
- package/build/esm/integrations/google-genai.js.map +1 -1
- package/build/esm/integrations/langgraph.js +5 -7
- package/build/esm/integrations/langgraph.js.map +1 -1
- package/build/esm/integrations/mastra-classifier.js +1 -1
- package/build/esm/integrations/mastra-classifier.js.map +1 -1
- package/build/esm/integrations/mistral.js +13 -4
- package/build/esm/integrations/mistral.js.map +1 -1
- package/build/esm/integrations/openai-compatible.js +16 -8
- package/build/esm/integrations/openai-compatible.js.map +1 -1
- package/build/esm/integrations/openai.js +16 -8
- package/build/esm/integrations/openai.js.map +1 -1
- package/build/esm/integrations/pi-ai.js +39 -18
- package/build/esm/integrations/pi-ai.js.map +1 -1
- package/build/esm/integrations/pino.js +131 -0
- package/build/esm/integrations/pino.js.map +1 -0
- package/build/esm/integrations/typesafe.js +17 -3
- package/build/esm/integrations/typesafe.js.map +1 -1
- package/build/esm/integrations/vercel-ai/index.js.map +1 -1
- package/build/esm/integrations/vercel-ai/util.js +3 -2
- package/build/esm/integrations/vercel-ai/util.js.map +1 -1
- package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js +44 -17
- package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -1
- package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js +22 -16
- package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js.map +1 -1
- package/build/esm/integrations/winston.js +90 -0
- package/build/esm/integrations/winston.js.map +1 -0
- package/build/esm/orchestrion/detect.js +1 -1
- package/build/esm/orchestrion/detect.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/esm/utils/wrapServerRequestHandler.js +2 -1
- package/build/esm/utils/wrapServerRequestHandler.js.map +1 -1
- package/build/types/ai/anthropic-ai/index.d.ts +1 -5
- package/build/types/ai/anthropic-ai/index.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/streaming.d.ts +3 -2
- package/build/types/ai/anthropic-ai/streaming.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/tool-runner.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/types.d.ts +24 -3
- package/build/types/ai/anthropic-ai/types.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/utils.d.ts +2 -3
- package/build/types/ai/anthropic-ai/utils.d.ts.map +1 -1
- package/build/types/ai/core/span-hooks.d.ts +31 -0
- package/build/types/ai/core/span-hooks.d.ts.map +1 -0
- package/build/types/ai/core/time-to-first-chunk.d.ts +7 -0
- package/build/types/ai/core/time-to-first-chunk.d.ts.map +1 -0
- package/build/types/ai/core/utils.d.ts +30 -1
- package/build/types/ai/core/utils.d.ts.map +1 -1
- package/build/types/ai/flue/index.d.ts +13 -5
- package/build/types/ai/flue/index.d.ts.map +1 -1
- package/build/types/ai/flue/types.d.ts +20 -2
- package/build/types/ai/flue/types.d.ts.map +1 -1
- package/build/types/ai/flue/utils.d.ts +5 -9
- package/build/types/ai/flue/utils.d.ts.map +1 -1
- package/build/types/ai/google-genai/decisions.d.ts.map +1 -1
- package/build/types/ai/google-genai/index.d.ts.map +1 -1
- package/build/types/ai/google-genai/streaming.d.ts +2 -1
- package/build/types/ai/google-genai/streaming.d.ts.map +1 -1
- package/build/types/ai/google-genai/types.d.ts +17 -3
- package/build/types/ai/google-genai/types.d.ts.map +1 -1
- package/build/types/ai/langchain/index.d.ts.map +1 -1
- package/build/types/ai/langchain/types.d.ts +49 -3
- package/build/types/ai/langchain/types.d.ts.map +1 -1
- package/build/types/ai/langchain/utils.d.ts +6 -0
- package/build/types/ai/langchain/utils.d.ts.map +1 -1
- package/build/types/ai/langgraph/agent-span.d.ts +4 -1
- package/build/types/ai/langgraph/agent-span.d.ts.map +1 -1
- package/build/types/ai/langgraph/index.d.ts +1 -1
- package/build/types/ai/langgraph/index.d.ts.map +1 -1
- package/build/types/ai/langgraph/stream.d.ts.map +1 -1
- package/build/types/ai/langgraph/types.d.ts +14 -3
- package/build/types/ai/langgraph/types.d.ts.map +1 -1
- package/build/types/ai/langgraph/utils.d.ts +3 -0
- package/build/types/ai/langgraph/utils.d.ts.map +1 -1
- package/build/types/ai/mastra/classifier-evaluation.d.ts +3 -3
- package/build/types/ai/mastra/classifier-evaluation.d.ts.map +1 -1
- package/build/types/ai/mastra/index.d.ts +17 -3
- package/build/types/ai/mastra/index.d.ts.map +1 -1
- package/build/types/ai/mastra/types.d.ts +2 -0
- package/build/types/ai/mastra/types.d.ts.map +1 -1
- package/build/types/ai/mastra/utils.d.ts.map +1 -1
- package/build/types/ai/mistral/index.d.ts.map +1 -1
- package/build/types/ai/mistral/streaming.d.ts +2 -1
- package/build/types/ai/mistral/streaming.d.ts.map +1 -1
- package/build/types/ai/mistral/types.d.ts +14 -3
- package/build/types/ai/mistral/types.d.ts.map +1 -1
- package/build/types/ai/openai/index.d.ts.map +1 -1
- package/build/types/ai/openai/mapping.d.ts.map +1 -1
- package/build/types/ai/openai/streaming.d.ts +3 -1
- package/build/types/ai/openai/streaming.d.ts.map +1 -1
- package/build/types/ai/openai/types.d.ts +14 -3
- package/build/types/ai/openai/types.d.ts.map +1 -1
- package/build/types/ai/pi-ai/chat.d.ts +7 -1
- package/build/types/ai/pi-ai/chat.d.ts.map +1 -1
- package/build/types/ai/pi-ai/recording.d.ts +21 -9
- package/build/types/ai/pi-ai/recording.d.ts.map +1 -1
- package/build/types/ai/pi-ai/types.d.ts +16 -0
- package/build/types/ai/pi-ai/types.d.ts.map +1 -1
- package/build/types/ai/pi-durable/index.d.ts +12 -3
- package/build/types/ai/pi-durable/index.d.ts.map +1 -1
- package/build/types/ai/pi-durable/runs.d.ts +2 -0
- package/build/types/ai/pi-durable/runs.d.ts.map +1 -1
- package/build/types/ai/pi-durable/tools.d.ts +4 -3
- package/build/types/ai/pi-durable/tools.d.ts.map +1 -1
- package/build/types/ai/pi-durable/types.d.ts +15 -0
- package/build/types/ai/pi-durable/types.d.ts.map +1 -1
- package/build/types/ai/types.d.ts +1 -1
- package/build/types/ai/types.d.ts.map +1 -1
- package/build/types/ai/typesafe/index.d.ts +10 -2
- package/build/types/ai/typesafe/index.d.ts.map +1 -1
- package/build/types/ai/workers-ai/index.d.ts.map +1 -1
- package/build/types/ai/workers-ai/streaming.d.ts +2 -1
- package/build/types/ai/workers-ai/streaming.d.ts.map +1 -1
- package/build/types/ai/workers-ai/types.d.ts +18 -3
- package/build/types/ai/workers-ai/types.d.ts.map +1 -1
- package/build/types/cron/common.d.ts +8 -0
- package/build/types/cron/common.d.ts.map +1 -0
- package/build/types/cron/cron.d.ts +45 -0
- package/build/types/cron/cron.d.ts.map +1 -0
- package/build/types/cron/index.d.ts +10 -0
- package/build/types/cron/index.d.ts.map +1 -0
- package/build/types/cron/node-cron.d.ts +33 -0
- package/build/types/cron/node-cron.d.ts.map +1 -0
- package/build/types/cron/node-schedule.d.ts +19 -0
- package/build/types/cron/node-schedule.d.ts.map +1 -0
- package/build/types/index.d.ts +5 -2
- package/build/types/index.d.ts.map +1 -1
- package/build/types/integrations/anthropic.d.ts +2 -1
- package/build/types/integrations/anthropic.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/index.d.ts +3 -3
- package/build/types/integrations/aws-sdk/index.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/services/ServiceExtension.d.ts +1 -0
- package/build/types/integrations/aws-sdk/services/ServiceExtension.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/services/ServicesExtensions.d.ts +3 -2
- package/build/types/integrations/aws-sdk/services/ServicesExtensions.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/services/bedrock-runtime.d.ts +25 -4
- package/build/types/integrations/aws-sdk/services/bedrock-runtime.d.ts.map +1 -1
- package/build/types/integrations/bullmq/contextManager.d.ts +13 -0
- package/build/types/integrations/bullmq/contextManager.d.ts.map +1 -0
- package/build/types/integrations/bullmq/index.d.ts +43 -0
- package/build/types/integrations/bullmq/index.d.ts.map +1 -0
- package/build/types/integrations/bullmq/meter.d.ts +7 -0
- package/build/types/integrations/bullmq/meter.d.ts.map +1 -0
- package/build/types/integrations/bullmq/span.d.ts +35 -0
- package/build/types/integrations/bullmq/span.d.ts.map +1 -0
- package/build/types/integrations/bullmq/tracer.d.ts +5 -0
- package/build/types/integrations/bullmq/tracer.d.ts.map +1 -0
- package/build/types/integrations/bullmq/types.d.ts +72 -0
- package/build/types/integrations/bullmq/types.d.ts.map +1 -0
- package/build/types/integrations/express/types.d.ts +1 -0
- package/build/types/integrations/express/types.d.ts.map +1 -1
- package/build/types/integrations/flue.d.ts +2 -1
- package/build/types/integrations/flue.d.ts.map +1 -1
- package/build/types/integrations/google-genai.d.ts +2 -1
- package/build/types/integrations/google-genai.d.ts.map +1 -1
- package/build/types/integrations/groq.d.ts +1 -1
- package/build/types/integrations/langchain.d.ts +2 -1
- package/build/types/integrations/langchain.d.ts.map +1 -1
- package/build/types/integrations/langgraph.d.ts +2 -1
- package/build/types/integrations/langgraph.d.ts.map +1 -1
- package/build/types/integrations/mistral.d.ts +2 -1
- package/build/types/integrations/mistral.d.ts.map +1 -1
- package/build/types/integrations/openai-compatible.d.ts.map +1 -1
- package/build/types/integrations/openai.d.ts +2 -1
- package/build/types/integrations/openai.d.ts.map +1 -1
- package/build/types/integrations/pi-ai.d.ts +6 -3
- package/build/types/integrations/pi-ai.d.ts.map +1 -1
- package/build/types/integrations/pi-durable.d.ts +2 -1
- package/build/types/integrations/pi-durable.d.ts.map +1 -1
- package/build/types/integrations/pino.d.ts +61 -0
- package/build/types/integrations/pino.d.ts.map +1 -0
- package/build/types/integrations/together-ai.d.ts +1 -1
- package/build/types/integrations/typesafe.d.ts +2 -2
- package/build/types/integrations/typesafe.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/index.d.ts +3 -3
- package/build/types/integrations/vercel-ai/index.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/util.d.ts +2 -1
- package/build/types/integrations/vercel-ai/util.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts +20 -4
- package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.d.ts.map +1 -1
- package/build/types/integrations/winston.d.ts +55 -0
- package/build/types/integrations/winston.d.ts.map +1 -0
- package/build/types/utils/wrapServerRequestHandler.d.ts.map +1 -1
- package/package.json +4 -4
package/build/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["_attachHapiErrorHandler"],"sources":["../../src/index.ts"],"sourcesContent":["export * from './exports';\n\n// Exports using diagnostics channels\nexport { detectOrchestrionSetup } from './orchestrion/detect';\n// oxlint-disable-next-line typescript/no-deprecated -- re-exported so the deprecated `setupKoaErrorHandler` can delegate\nexport { attachKoaErrorHandler } from './integrations/koa/koa-error-handler';\nimport { attachHapiErrorHandler as _attachHapiErrorHandler } from './integrations/hapi/hapi-error-handler';\nexport { bindTracingChannelToSpan } from './tracing-channel';\nexport type { TracingChannelPayloadWithSpan } from './tracing-channel';\nexport type { InstrumentationConfig } from './orchestrion/apmTypes';\nexport type { OrchestrionChannelContext } from './orchestrion/types';\n// Runtime target of the bundler-injected module snippet. The snippet imports it\n// from this entry alongside the module's subscriber factory (see\n// `orchestrion/bundler/moduleInjectedTransform.ts`); it is a plain runtime\n// helper with no orchestrion build-time dependency.\nexport { orchestrionModuleInjected } from './utils/moduleInjected';\nexport {\n subscribe as subscribeDiagnosticsChannel,\n tracingChannel as diagnosticsTracingChannel,\n} from './utils/diagnosticsChannel';\nexport { eveConversationHook, eveIntegration, eveTracePolicy } from './eve';\nexport { getInstrumentedModuleNames } from './orchestrion/config';\nexport {\n fastifyIntegration,\n // oxlint-disable-next-line typescript/no-deprecated\n setupFastifyErrorHandler,\n} from './integrations/fastify';\n\n/**\n * @deprecated This is a temporary export to avoid breaking changes. It will be removed in the next major version.\n */\nexport const attachHapiErrorHandler = _attachHapiErrorHandler;\n\n// Integrations\nexport { prismaIntegration } from './integrations/prisma';\nexport { amqplibIntegration } from './integrations/amqplib';\nexport { anthropicAIIntegration } from './integrations/anthropic';\nexport { awsIntegration } from './integrations/aws-sdk';\nexport { dataloaderIntegration } from './integrations/dataloader';\nexport { genericPoolIntegration } from './integrations/generic-pool';\nexport { cronJobIntegration } from './integrations/cron';\nexport type { CronJobIntegrationOptions } from './integrations/cron';\nexport {
|
|
1
|
+
{"version":3,"file":"index.js","names":["_attachHapiErrorHandler"],"sources":["../../src/index.ts"],"sourcesContent":["export * from './exports';\n\n// Exports using diagnostics channels\nexport { detectOrchestrionSetup } from './orchestrion/detect';\n// oxlint-disable-next-line typescript/no-deprecated -- re-exported so the deprecated `setupKoaErrorHandler` can delegate\nexport { attachKoaErrorHandler } from './integrations/koa/koa-error-handler';\nimport { attachHapiErrorHandler as _attachHapiErrorHandler } from './integrations/hapi/hapi-error-handler';\nexport { bindTracingChannelToSpan } from './tracing-channel';\nexport type { TracingChannelPayloadWithSpan } from './tracing-channel';\nexport type { InstrumentationConfig } from './orchestrion/apmTypes';\nexport type { OrchestrionChannelContext } from './orchestrion/types';\n// Runtime target of the bundler-injected module snippet. The snippet imports it\n// from this entry alongside the module's subscriber factory (see\n// `orchestrion/bundler/moduleInjectedTransform.ts`); it is a plain runtime\n// helper with no orchestrion build-time dependency.\nexport { orchestrionModuleInjected } from './utils/moduleInjected';\nexport {\n subscribe as subscribeDiagnosticsChannel,\n tracingChannel as diagnosticsTracingChannel,\n} from './utils/diagnosticsChannel';\nexport { eveConversationHook, eveIntegration, eveTracePolicy } from './eve';\nexport { getInstrumentedModuleNames } from './orchestrion/config';\nexport {\n fastifyIntegration,\n // oxlint-disable-next-line typescript/no-deprecated\n setupFastifyErrorHandler,\n} from './integrations/fastify';\n\n/**\n * @deprecated This is a temporary export to avoid breaking changes. It will be removed in the next major version.\n */\nexport const attachHapiErrorHandler = _attachHapiErrorHandler;\n\n// Integrations\nexport { prismaIntegration } from './integrations/prisma';\nexport { amqplibIntegration } from './integrations/amqplib';\nexport { anthropicAIIntegration } from './integrations/anthropic';\nexport { awsIntegration } from './integrations/aws-sdk';\nexport { dataloaderIntegration } from './integrations/dataloader';\nexport { genericPoolIntegration } from './integrations/generic-pool';\nexport { cronJobIntegration } from './integrations/cron';\nexport type { CronJobIntegrationOptions } from './integrations/cron';\nexport { nodeCronIntegration } from './integrations/node-cron';\nexport type { NodeCronIntegrationOptions } from './integrations/node-cron';\nexport { nodeScheduleIntegration } from './integrations/node-schedule';\nexport type { NodeScheduleIntegrationOptions } from './integrations/node-schedule';\nexport { cronExpressionToMonitorConfig as _INTERNAL_cronExpressionToMonitorConfig } from './utils/cronMonitoring';\nexport { cron } from './cron';\nexport { BullMQTelemetry } from './integrations/bullmq';\nexport { googleGenAIIntegration } from './integrations/google-genai';\nexport { graphqlIntegration } from './integrations/graphql';\nexport { hapiIntegration } from './integrations/hapi';\nexport { honoIntegration, honoMiddleware } from './integrations/hono';\nexport type { HonoIntegrationOptions } from './integrations/hono';\nexport { koaIntegration } from './integrations/koa';\nexport { redisIntegration } from './integrations/redis';\nexport { kafkaIntegration } from './integrations/kafkajs';\nexport { knexIntegration } from './integrations/knex';\nexport { langChainIntegration } from './integrations/langchain';\nexport { langGraphIntegration } from './integrations/langgraph';\nexport { createFlueInstrumentation } from './ai/flue';\nexport { flueIntegration } from './integrations/flue';\nexport { piAiIntegration } from './integrations/pi-ai';\nexport { piDurableIntegration } from './integrations/pi-durable';\nexport type { FlueOptions } from './ai/flue';\nexport { mastraIntegration } from './integrations/mastra';\nexport { mcpServerIntegration } from './integrations/mcp-server';\nexport {\n instrumentTunnelServers as _INTERNAL_instrumentTunnelServers,\n makeServeTunnelIntegration,\n} from './integrations/serveTunnel';\nexport { instrumentTunnelServer as _INTERNAL_instrumentTunnelServer } from './utils/tunnelServer';\nexport { SentryMastraExporter } from './ai/mastra';\nexport { lruMemoizerIntegration } from './integrations/lru-memoizer';\nexport { mongoIntegration } from './integrations/mongodb';\nexport { mongooseIntegration } from './integrations/mongoose';\nexport { mistralAIIntegration } from './integrations/mistral';\nexport { groqIntegration } from './integrations/groq';\nexport { togetherAIIntegration } from './integrations/together-ai';\nexport { typesafeIntegration } from './integrations/typesafe';\nexport { mysqlIntegration } from './integrations/mysql';\nexport { mysql2Integration } from './integrations/mysql2';\nexport { pinoIntegration } from './integrations/pino';\nexport { createSentryWinstonTransport } from './integrations/winston';\nexport { openAIIntegration } from './integrations/openai';\nexport { postgresIntegration } from './integrations/pg';\nexport { postgresJsIntegration } from './integrations/postgresjs';\nexport { neonIntegration } from './integrations/neon';\nexport { tediousIntegration } from './integrations/tedious';\nexport { vercelAIIntegration } from './integrations/vercel-ai';\nexport { expressIntegration } from './integrations/express';\nexport type { ExpressIntegrationOptions } from './integrations/express/types';\n/* oxlint-disable typescript/no-deprecated -- deprecated Express error-handler exports, kept until the next major */\nexport { expressErrorHandler, setupExpressErrorHandler } from './integrations/express/error-handler';\n/* oxlint-enable typescript/no-deprecated */\nexport { firebaseIntegration } from './integrations/firebase';\nexport { nitroIntegration } from './integrations/nitro';\nexport type { NitroIntegrationOptions } from './integrations/nitro';\n\nexport { getTracingIntegrations, getErrorIntegrations } from './integrations';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,yBAAyBA"}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { tracingChannel } from "../utils/diagnosticsChannel.js";
|
|
2
|
-
import { getGenAiSpanOp, getRequestSignal, markCancelledIfAborted,
|
|
2
|
+
import { getGenAiSpanOp, getRequestSignal, markCancelledIfAborted, resolveGenAiCallRecording } from "../ai/core/utils.js";
|
|
3
3
|
import { wrapApiPromiseResponse } from "../ai/core/apiPromise.js";
|
|
4
|
-
import {
|
|
4
|
+
import { runGenAiSpanEnd, runGenAiSpanStart } from "../ai/core/span-hooks.js";
|
|
5
|
+
import { addPrivateRequestAttributes, extractRequestAttributes } from "../ai/anthropic-ai/index.js";
|
|
5
6
|
import { ANTHROPIC_AI_ORIGIN } from "../ai/anthropic-ai/constants.js";
|
|
6
|
-
import { getProviderName } from "../ai/anthropic-ai/utils.js";
|
|
7
|
+
import { addResponseAttributes, getProviderName } from "../ai/anthropic-ai/utils.js";
|
|
7
8
|
import { instrumentAsyncIterableStream, instrumentMessageStream } from "../ai/anthropic-ai/streaming.js";
|
|
8
9
|
import { instrumentSessionToolRunner, instrumentToolRunner } from "../ai/anthropic-ai/tool-runner.js";
|
|
9
10
|
import { shouldSkipAiProviderSpan } from "../ai/pi-ai/providers.js";
|
|
@@ -43,12 +44,13 @@ function instrumentAnthropic(options) {
|
|
|
43
44
|
for (const { channel, operation, stream } of INSTRUMENTED_CHANNELS) bindTracingChannelToSpan(tracingChannel(channel), (data) => createGenAiSpan(data, operation, options, stream), {
|
|
44
45
|
beforeSpanEnd: (span, data) => {
|
|
45
46
|
if ("error" in data) markCancelledIfAborted(span, getRequestSignal(data.arguments?.[1]));
|
|
46
|
-
addResponseAttributes(span, data.result,
|
|
47
|
+
addResponseAttributes(span, data.result, !!data._sentryRecordOutputs);
|
|
48
|
+
data._sentryOnSpanEnd?.("error" in data ? { error: data.error } : { response: data.result });
|
|
47
49
|
},
|
|
48
|
-
deferSpanEnd: ({ span, data, end }) => wrapThreadStreamRequest(span, data, end
|
|
50
|
+
deferSpanEnd: ({ span, data, end }) => wrapThreadStreamRequest(span, data, end) || wrapApiPromiseResponse(data.result, (response) => {
|
|
49
51
|
data.result = response;
|
|
50
|
-
if (!wrapStreamResult(span, data, stream
|
|
51
|
-
}, end) || wrapStreamResult(span, data, stream
|
|
52
|
+
if (!wrapStreamResult(span, data, stream)) end();
|
|
53
|
+
}, end) || wrapStreamResult(span, data, stream)
|
|
52
54
|
});
|
|
53
55
|
tracingChannel(CHANNELS.ANTHROPIC_TOOL_RUNNER).end.subscribe((message) => {
|
|
54
56
|
instrumentToolRunner(message.result, options);
|
|
@@ -75,7 +77,12 @@ function createGenAiSpan(data, operation, options, stream) {
|
|
|
75
77
|
const requestOptions = args[1];
|
|
76
78
|
if (isStreamHelperRequest(requestOptions?.headers) && isInsideStreamHelperSpan()) return;
|
|
77
79
|
const params = typeof args[0] === "object" && args[0] !== null ? args[0] : void 0;
|
|
78
|
-
const
|
|
80
|
+
const call = {
|
|
81
|
+
operation,
|
|
82
|
+
request: params
|
|
83
|
+
};
|
|
84
|
+
const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);
|
|
85
|
+
data._sentryRecordOutputs = recordOutputs;
|
|
79
86
|
const attributes = extractRequestAttributes(args, operation, recordInputs, getProviderName(data.self));
|
|
80
87
|
const model = attributes[GEN_AI_REQUEST_MODEL] || "unknown";
|
|
81
88
|
attributes[SENTRY_ORIGIN] = ANTHROPIC_AI_ORIGIN;
|
|
@@ -86,6 +93,8 @@ function createGenAiSpan(data, operation, options, stream) {
|
|
|
86
93
|
attributes
|
|
87
94
|
});
|
|
88
95
|
if (recordInputs && params) addPrivateRequestAttributes(span, params);
|
|
96
|
+
runGenAiSpanStart(options, span, call);
|
|
97
|
+
data._sentryOnSpanEnd = (result) => runGenAiSpanEnd(options, span, call, result);
|
|
89
98
|
if (stream === "message-stream") streamHelperSpans.add(span);
|
|
90
99
|
return span;
|
|
91
100
|
}
|
|
@@ -127,18 +136,18 @@ const threadStreams = /* @__PURE__ */ new WeakMap();
|
|
|
127
136
|
* End the span of a thread stream's `create()` call from the stream once the response arrives. A thread may
|
|
128
137
|
* retry a rejected call, so a failed call ends its own span and only the one that succeeds reads the stream.
|
|
129
138
|
*/
|
|
130
|
-
function wrapThreadStreamRequest(span, data, end
|
|
139
|
+
function wrapThreadStreamRequest(span, data, end) {
|
|
131
140
|
const signal = (data.arguments?.[1])?.signal;
|
|
132
141
|
const threadStream = signal && threadStreams.get(signal);
|
|
133
142
|
const request = data.result;
|
|
134
143
|
if (!threadStream || threadStream.stream.ended || typeof request?._responseProps !== "function") return false;
|
|
135
144
|
const { stream, callerSignal } = threadStream;
|
|
136
|
-
const
|
|
145
|
+
const recordOutputs = !!data._sentryRecordOutputs;
|
|
137
146
|
request._responseProps().then(() => {
|
|
138
147
|
threadStreams.delete(signal);
|
|
139
|
-
instrumentMessageStream(stream, span, recordOutputs, callerSignal);
|
|
148
|
+
instrumentMessageStream(stream, span, recordOutputs, callerSignal, data._sentryOnSpanEnd);
|
|
140
149
|
}, (error) => {
|
|
141
|
-
if (signal.aborted) instrumentMessageStream(stream, span, recordOutputs, callerSignal);
|
|
150
|
+
if (signal.aborted) instrumentMessageStream(stream, span, recordOutputs, callerSignal, data._sentryOnSpanEnd);
|
|
142
151
|
else end(error);
|
|
143
152
|
});
|
|
144
153
|
return true;
|
|
@@ -151,17 +160,17 @@ function wrapThreadStreamRequest(span, data, end, options) {
|
|
|
151
160
|
* the span when iteration finishes.
|
|
152
161
|
* - `message-stream`: `instrumentMessageStream` attaches `'message'`/`'error'`/`'end'` listeners that end the span.
|
|
153
162
|
*/
|
|
154
|
-
function wrapStreamResult(span, data, stream
|
|
155
|
-
const
|
|
163
|
+
function wrapStreamResult(span, data, stream) {
|
|
164
|
+
const recordOutputs = !!data._sentryRecordOutputs;
|
|
156
165
|
const result = data.result;
|
|
157
166
|
if (stream === "async-iterable" && isAsyncIterable(result)) {
|
|
158
167
|
const iterate = result[Symbol.asyncIterator].bind(result);
|
|
159
|
-
const instrumented = instrumentAsyncIterableStream({ [Symbol.asyncIterator]: iterate }, span, recordOutputs);
|
|
168
|
+
const instrumented = instrumentAsyncIterableStream({ [Symbol.asyncIterator]: iterate }, span, recordOutputs, data._sentryOnSpanEnd);
|
|
160
169
|
result[Symbol.asyncIterator] = () => instrumented;
|
|
161
170
|
return true;
|
|
162
171
|
}
|
|
163
172
|
if (stream === "message-stream" && isMessageStream(result)) {
|
|
164
|
-
instrumentMessageStream(result, span, recordOutputs, getRequestSignal(data.arguments?.[1]));
|
|
173
|
+
instrumentMessageStream(result, span, recordOutputs, getRequestSignal(data.arguments?.[1]), data._sentryOnSpanEnd);
|
|
165
174
|
return true;
|
|
166
175
|
}
|
|
167
176
|
return false;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"anthropic.js","names":["diagnosticsChannel.tracingChannel","diagnosticsChannel\n .tracingChannel"],"sources":["../../../src/integrations/anthropic.ts"],"sourcesContent":["import { GEN_AI_REQUEST_MODEL, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn, Span, SpanAttributeValue } from '@sentry/core';\nimport { defineIntegration, getActiveSpan, getClient, hasSpanStreamingEnabled, startInactiveSpan } from '@sentry/core';\nimport { getGenAiSpanOp, getRequestSignal, markCancelledIfAborted, resolveAIRecordingOptions } from '../ai/core/utils';\nimport { wrapApiPromiseResponse } from '../ai/core/apiPromise';\nimport { addPrivateRequestAttributes, addResponseAttributes, extractRequestAttributes } from '../ai/anthropic-ai';\nimport { ANTHROPIC_AI_ORIGIN } from '../ai/anthropic-ai/constants';\nimport { getProviderName } from '../ai/anthropic-ai/utils';\nimport { instrumentAsyncIterableStream, instrumentMessageStream } from '../ai/anthropic-ai/streaming';\nimport { instrumentSessionToolRunner, instrumentToolRunner } from '../ai/anthropic-ai/tool-runner';\nimport type { AnthropicAiOptions, AnthropicAiResponse } from '../ai/anthropic-ai/types';\nimport { shouldSkipAiProviderSpan } from '../ai/pi-ai/providers';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\nimport { anthropicAiModuleNames } from '../orchestrion/config/anthropic-ai';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\n\n// Same name as the OTel integration by design, so the OTel 'Anthropic_AI'\n// integration is deduplicated out of the default set.\nconst INTEGRATION_NAME = 'Anthropic_AI' as const;\n\n// `stream` determines how the span is ended\nconst INSTRUMENTED_CHANNELS = [\n { channel: CHANNELS.ANTHROPIC_CHAT, operation: 'chat', stream: 'async-iterable' },\n {\n channel: CHANNELS.ANTHROPIC_MESSAGES_STREAM,\n operation: 'chat',\n stream: 'message-stream',\n },\n] as const;\n\ntype StreamMode = (typeof INSTRUMENTED_CHANNELS)[number]['stream'];\n\nconst _anthropicAIIntegration = ((options: AnthropicAiOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, anthropicAiModuleNames, instrumentAnthropic, [options]);\n },\n };\n}) satisfies IntegrationFn;\n\n// Since 0.134 `@anthropic-ai/sdk` traces itself through the global OTel tracer provider, which duplicates our\n// spans. Only turned off once our channels subscribe, so an app we do not instrument keeps the SDK's spans.\n// A value the user set wins.\nfunction disableNativeTracing(): void {\n try {\n process.env.ANTHROPIC_OPEN_TELEMETRY ??= 'false';\n } catch {\n // `process` is absent (edge runtimes) or env access is gated (Deno without `--allow-env`).\n }\n}\n\nfunction instrumentAnthropic(options: AnthropicAiOptions): void {\n disableNativeTracing();\n for (const { channel, operation, stream } of INSTRUMENTED_CHANNELS) {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(channel),\n data => createGenAiSpan(data, operation, options, stream),\n {\n beforeSpanEnd: (span, data) => {\n if ('error' in data) {\n markCancelledIfAborted(span, getRequestSignal(data.arguments?.[1]));\n }\n addResponseAttributes(\n span,\n data.result as AnthropicAiResponse,\n resolveAIRecordingOptions(options).recordOutputs,\n );\n },\n deferSpanEnd: ({ span, data, end }) =>\n wrapThreadStreamRequest(span, data, end, options) ||\n wrapApiPromiseResponse(\n data.result,\n response => {\n data.result = response;\n if (!wrapStreamResult(span, data, stream, options)) {\n end();\n }\n },\n end,\n ) ||\n wrapStreamResult(span, data, stream, options),\n },\n );\n }\n\n diagnosticsChannel\n .tracingChannel<OrchestrionChannelContext>(CHANNELS.ANTHROPIC_TOOL_RUNNER)\n .end.subscribe(message => {\n instrumentToolRunner((message as OrchestrionChannelContext).result, options);\n });\n diagnosticsChannel\n .tracingChannel<OrchestrionChannelContext>(CHANNELS.ANTHROPIC_SESSION_TOOL_RUNNER)\n .end.subscribe(message => {\n instrumentSessionToolRunner((message as OrchestrionChannelContext).self, options);\n });\n // On `start`, because `_start()` sends the first request before it returns.\n diagnosticsChannel\n .tracingChannel<OrchestrionChannelContext>(CHANNELS.ANTHROPIC_THREAD_STREAM)\n .start.subscribe(message => {\n const data = message as OrchestrionChannelContext;\n const stream = data.self as ThreadStream | undefined;\n if (isMessageStream(stream) && stream.controller?.signal) {\n // `_start(create, params, options)`: each `create()` gets only the stream's own signal, which doesn't carry\n // the reason a caller's signal fired with.\n threadStreams.set(stream.controller.signal, { stream, callerSignal: getRequestSignal(data.arguments?.[2]) });\n }\n });\n}\n\n/**\n * Build the span for an instrumented call.\n * Returning `undefined` opts the payload out so no span is opened.\n */\nfunction createGenAiSpan(\n data: OrchestrionChannelContext,\n operation: string,\n options: AnthropicAiOptions,\n stream: StreamMode,\n): Span | undefined {\n const args = data.arguments ?? [];\n\n if (shouldSkipAiProviderSpan(INTEGRATION_NAME)) {\n return undefined;\n }\n\n // `messages.stream()` internally calls the instrumented `messages.create({ stream: true })` tagged with\n // a `stream` helper-method header. The messages-stream channel already covers it, so skip the nested\n // create to avoid a duplicate span. Only the non-beta helper is on that channel, though:\n // `beta.messages.stream()` and the streaming tool runner send the same header with no span covering\n // them, so the header alone is not enough. Skip only while a stream-helper span of ours is active.\n const requestOptions = args[1] as { headers?: unknown } | undefined;\n if (isStreamHelperRequest(requestOptions?.headers) && isInsideStreamHelperSpan()) {\n return undefined;\n }\n\n const params = typeof args[0] === 'object' && args[0] !== null ? (args[0] as Record<string, unknown>) : undefined;\n\n const { recordInputs } = resolveAIRecordingOptions(options);\n\n const attributes = extractRequestAttributes(args, operation, recordInputs, getProviderName(data.self));\n const model = (attributes[GEN_AI_REQUEST_MODEL] as string) || 'unknown';\n attributes[SENTRY_ORIGIN] = ANTHROPIC_AI_ORIGIN;\n const client = getClient();\n\n const span = startInactiveSpan({\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name: model !== 'unknown' || !(client && hasSpanStreamingEnabled(client)) ? `${operation} ${model}` : operation,\n op: getGenAiSpanOp(operation),\n attributes: attributes as Record<string, SpanAttributeValue>,\n });\n\n if (recordInputs && params) {\n addPrivateRequestAttributes(span, params);\n }\n\n if (stream === 'message-stream') {\n streamHelperSpans.add(span);\n }\n\n return span;\n}\n\nconst STREAM_HELPER_METHOD_HEADER = 'x-stainless-helper-method';\n\n/** The spans opened for the messages-stream channel, i.e. for `messages.stream()` calls. */\nconst streamHelperSpans = new WeakSet<Span>();\n\n/**\n * Whether the active span is one this integration opened for `messages.stream()`. The helper's\n * internal `create` runs inside that span, so this is what tells it apart from the beta helper and\n * the tool runner, which send the same header but are not on the messages-stream channel.\n */\nfunction isInsideStreamHelperSpan(): boolean {\n const activeSpan = getActiveSpan();\n return !!activeSpan && streamHelperSpans.has(activeSpan);\n}\n\n/**\n * Whether request options carry the header the SDK's `messages.stream()` helper puts on its internal\n * `create` call. The SDK sent it as `X-Stainless-Helper-Method` up to 0.105 and lowercase since 0.106, and\n * HTTP header names are case-insensitive either way, so match without regard to case. The headers\n * arrive as a plain object; a `Headers` instance is handled for completeness.\n */\nfunction isStreamHelperRequest(headers: unknown): boolean {\n if (!headers || typeof headers !== 'object') {\n return false;\n }\n\n if (typeof (headers as Headers).get === 'function') {\n return (headers as Headers).get(STREAM_HELPER_METHOD_HEADER) === 'stream';\n }\n\n return Object.entries(headers as Record<string, unknown>).some(\n ([name, value]) => name.toLowerCase() === STREAM_HELPER_METHOD_HEADER && value === 'stream',\n );\n}\n\ntype AsyncIterableStream = { [Symbol.asyncIterator]: () => AsyncIterator<unknown> };\ntype MessageStreamEmitter = { on: (...args: unknown[]) => void };\n\nfunction isAsyncIterable(value: unknown): value is AsyncIterableStream {\n return !!value && typeof (value as AsyncIterableStream)[Symbol.asyncIterator] === 'function';\n}\n\nfunction isMessageStream(value: unknown): value is MessageStreamEmitter {\n return !!value && typeof (value as MessageStreamEmitter).on === 'function';\n}\n\ntype ThreadStream = MessageStreamEmitter & { ended?: boolean; controller?: { signal?: AbortSignal } };\n\n/**\n * The streams of threads and tool runners on 1.2+, by the signal they send each `create()` call with. Such a\n * stream parses the response itself, so the `create()` result is never parsed and never ends its span.\n */\nconst threadStreams = new WeakMap<AbortSignal, { stream: ThreadStream; callerSignal: AbortSignal | undefined }>();\n\n/**\n * End the span of a thread stream's `create()` call from the stream once the response arrives. A thread may\n * retry a rejected call, so a failed call ends its own span and only the one that succeeds reads the stream.\n */\nfunction wrapThreadStreamRequest(\n span: Span,\n data: OrchestrionChannelContext,\n end: (error?: unknown) => void,\n options: AnthropicAiOptions,\n): boolean {\n const signal = (data.arguments?.[1] as { signal?: AbortSignal } | undefined)?.signal;\n const threadStream = signal && threadStreams.get(signal);\n const request = data.result as { _responseProps?: () => Promise<unknown> } | undefined;\n // A finished stream sends no more requests, so a later call with its signal is the caller's own.\n if (!threadStream || threadStream.stream.ended || typeof request?._responseProps !== 'function') {\n return false;\n }\n const { stream, callerSignal } = threadStream;\n\n const { recordOutputs } = resolveAIRecordingOptions(options);\n // Not `asResponse()`, which on 1.x also ends the SDK's own span when the user turned its tracing on.\n void request._responseProps().then(\n () => {\n // Only a rejected attempt is retried, so nothing else may claim this stream.\n threadStreams.delete(signal);\n instrumentMessageStream(stream, span, recordOutputs, callerSignal);\n },\n error => {\n // An abort is not a failed request. The stream still emits 'end', which sets the status from the caller's signal.\n if (signal.aborted) {\n instrumentMessageStream(stream, span, recordOutputs, callerSignal);\n } else {\n end(error);\n }\n },\n );\n return true;\n}\n\n/**\n * Hand span-ending ownership to a streamed result: returns `true` to skip the normal `beforeSpanEnd`,\n * `false` for non-streaming results (which end via `beforeSpanEnd`).\n *\n * - `async-iterable`: patch the `Stream`'s async iterator in place so `instrumentAsyncIterableStream` ends\n * the span when iteration finishes.\n * - `message-stream`: `instrumentMessageStream` attaches `'message'`/`'error'`/`'end'` listeners that end the span.\n */\nfunction wrapStreamResult(\n span: Span,\n data: OrchestrionChannelContext,\n stream: StreamMode,\n options: AnthropicAiOptions,\n): boolean {\n const { recordOutputs } = resolveAIRecordingOptions(options);\n const result = data.result;\n\n if (stream === 'async-iterable' && isAsyncIterable(result)) {\n const iterate = result[Symbol.asyncIterator].bind(result);\n const instrumented = instrumentAsyncIterableStream({ [Symbol.asyncIterator]: iterate }, span, recordOutputs);\n result[Symbol.asyncIterator] = () => instrumented;\n return true;\n }\n\n if (stream === 'message-stream' && isMessageStream(result)) {\n instrumentMessageStream(result, span, recordOutputs, getRequestSignal(data.arguments?.[1]));\n return true;\n }\n\n return false;\n}\n\n/**\n * Diagnostics-channel-based Anthropic integration. Subscribes to the `orchestrion:@anthropic-ai/sdk:*`\n * diagnostics_channels injected into the SDK's chat (`messages`/`completions`/beta `messages`) and\n * `messages.stream()` methods, so it requires the Sentry runtime hook or bundler plugin.\n */\nexport const anthropicAIIntegration = defineIntegration(_anthropicAIIntegration);\n"],"mappings":";;;;;;;;;;;;;;;;AAqBA,MAAM,mBAAmB;AAGzB,MAAM,wBAAwB,CAC5B;CAAE,SAAS,SAAS;CAAgB,WAAW;CAAQ,QAAQ;AAAiB,GAChF;CACE,SAAS,SAAS;CAClB,WAAW;CACX,QAAQ;AACV,CACF;AAIA,MAAM,4BAA4B,UAA8B,CAAC,MAAM;CACrE,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GACZ,iCAAiC,QAAQ,wBAAwB,qBAAqB,CAAC,OAAO,CAAC;EACjG;CACF;AACF;AAKA,SAAS,uBAA6B;CACpC,IAAI;;EACF,CAAA,eAAA,QAAQ,IAAA,CAAI,6BAAA,aAAA,2BAA6B;CAC3C,QAAQ,CAER;AACF;AAEA,SAAS,oBAAoB,SAAmC;CAC9D,qBAAqB;CACrB,KAAK,MAAM,EAAE,SAAS,WAAW,YAAY,uBAC3C,yBACEA,eAA6D,OAAO,IACpE,SAAQ,gBAAgB,MAAM,WAAW,SAAS,MAAM,GACxD;EACE,gBAAgB,MAAM,SAAS;GAC7B,IAAI,WAAW,MACb,uBAAuB,MAAM,iBAAiB,KAAK,YAAY,EAAE,CAAC;GAEpE,sBACE,MACA,KAAK,QACL,0BAA0B,OAAO,CAAC,CAAC,aACrC;EACF;EACA,eAAe,EAA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wB,QAAQ,MAAM,eAAe,YAAY;CACnE,IACA,UAAS;EAEP,IAAI,OAAO,SACT,wBAAwB,QAAQ,MAAM,eAAe,YAAY;OAEjE,IAAI,KAAK;CAEb,CACF;CACA,OAAO;AACT;;;;;;;;;AAUA,SAAS,iBACP,MACA,MACA,QACA,SACS;CACT,MAAM,EAAE,kBAAkB,0BAA0B,OAAO;CAC3D,MAAM,SAAS,KAAK;CAEpB,IAAI,WAAW,oBAAoB,gBAAgB,MAAM,GAAG;EAC1D,MAAM,UAAU,OAAO,OAAO,cAAc,CAAC,KAAK,MAAM;EACxD,MAAM,eAAe,8BAA8B,GAAG,OAAO,gBAAgB,QAAQ,GAAG,MAAM,aAAa;EAC3G,OAAO,OAAO,uBAAuB;EACrC,OAAO;CACT;CAEA,IAAI,WAAW,oBAAoB,gBAAgB,MAAM,GAAG;EAC1D,wBAAwB,QAAQ,MAAM,eAAe,iBAAiB,KAAK,YAAY,EAAE,CAAC;EAC1F,OAAO;CACT;CAEA,OAAO;AACT;;;;;;AAOA,MAAa,yBAAyB,kBAAkB,uBAAuB"}
|
|
1
|
+
{"version":3,"file":"anthropic.js","names":["diagnosticsChannel.tracingChannel","diagnosticsChannel\n .tracingChannel"],"sources":["../../../src/integrations/anthropic.ts"],"sourcesContent":["import { GEN_AI_REQUEST_MODEL, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn, Span, SpanAttributeValue } from '@sentry/core';\nimport { defineIntegration, getActiveSpan, getClient, hasSpanStreamingEnabled, startInactiveSpan } from '@sentry/core';\nimport { getGenAiSpanOp, getRequestSignal, markCancelledIfAborted, resolveGenAiCallRecording } from '../ai/core/utils';\nimport { wrapApiPromiseResponse } from '../ai/core/apiPromise';\nimport { type GenAiSpanResult, runGenAiSpanEnd, runGenAiSpanStart } from '../ai/core/span-hooks';\nimport { addPrivateRequestAttributes, extractRequestAttributes } from '../ai/anthropic-ai';\nimport { ANTHROPIC_AI_ORIGIN } from '../ai/anthropic-ai/constants';\nimport { addResponseAttributes, getProviderName } from '../ai/anthropic-ai/utils';\nimport { instrumentAsyncIterableStream, instrumentMessageStream } from '../ai/anthropic-ai/streaming';\nimport { instrumentSessionToolRunner, instrumentToolRunner } from '../ai/anthropic-ai/tool-runner';\nimport type { AnthropicAiCallInfo, AnthropicAiOptions, AnthropicAiResponse } from '../ai/anthropic-ai/types';\nimport { shouldSkipAiProviderSpan } from '../ai/pi-ai/providers';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\nimport { anthropicAiModuleNames } from '../orchestrion/config/anthropic-ai';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\n\n// Same name as the OTel integration by design, so the OTel 'Anthropic_AI'\n// integration is deduplicated out of the default set.\nconst INTEGRATION_NAME = 'Anthropic_AI' as const;\n\n// The recording decision is made once, when the span starts, in the caller's async context.\ntype AnthropicChannelContext = OrchestrionChannelContext & {\n _sentryRecordOutputs?: boolean;\n _sentryOnSpanEnd?: (result: GenAiSpanResult<unknown>) => void;\n};\n\n// `stream` determines how the span is ended\nconst INSTRUMENTED_CHANNELS = [\n { channel: CHANNELS.ANTHROPIC_CHAT, operation: 'chat', stream: 'async-iterable' },\n {\n channel: CHANNELS.ANTHROPIC_MESSAGES_STREAM,\n operation: 'chat',\n stream: 'message-stream',\n },\n] as const;\n\ntype StreamMode = (typeof INSTRUMENTED_CHANNELS)[number]['stream'];\n\nconst _anthropicAIIntegration = ((options: AnthropicAiOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, anthropicAiModuleNames, instrumentAnthropic, [options]);\n },\n };\n}) satisfies IntegrationFn;\n\n// Since 0.134 `@anthropic-ai/sdk` traces itself through the global OTel tracer provider, which duplicates our\n// spans. Only turned off once our channels subscribe, so an app we do not instrument keeps the SDK's spans.\n// A value the user set wins.\nfunction disableNativeTracing(): void {\n try {\n process.env.ANTHROPIC_OPEN_TELEMETRY ??= 'false';\n } catch {\n // `process` is absent (edge runtimes) or env access is gated (Deno without `--allow-env`).\n }\n}\n\nfunction instrumentAnthropic(options: AnthropicAiOptions): void {\n disableNativeTracing();\n for (const { channel, operation, stream } of INSTRUMENTED_CHANNELS) {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<AnthropicChannelContext>(channel),\n data => createGenAiSpan(data, operation, options, stream),\n {\n beforeSpanEnd: (span, data) => {\n if ('error' in data) {\n markCancelledIfAborted(span, getRequestSignal(data.arguments?.[1]));\n }\n addResponseAttributes(span, data.result as AnthropicAiResponse, !!data._sentryRecordOutputs);\n data._sentryOnSpanEnd?.('error' in data ? { error: data.error } : { response: data.result });\n },\n deferSpanEnd: ({ span, data, end }) =>\n wrapThreadStreamRequest(span, data, end) ||\n wrapApiPromiseResponse(\n data.result,\n response => {\n data.result = response;\n if (!wrapStreamResult(span, data, stream)) {\n end();\n }\n },\n end,\n ) ||\n wrapStreamResult(span, data, stream),\n },\n );\n }\n\n diagnosticsChannel\n .tracingChannel<OrchestrionChannelContext>(CHANNELS.ANTHROPIC_TOOL_RUNNER)\n .end.subscribe(message => {\n instrumentToolRunner((message as OrchestrionChannelContext).result, options);\n });\n diagnosticsChannel\n .tracingChannel<OrchestrionChannelContext>(CHANNELS.ANTHROPIC_SESSION_TOOL_RUNNER)\n .end.subscribe(message => {\n instrumentSessionToolRunner((message as OrchestrionChannelContext).self, options);\n });\n // On `start`, because `_start()` sends the first request before it returns.\n diagnosticsChannel\n .tracingChannel<OrchestrionChannelContext>(CHANNELS.ANTHROPIC_THREAD_STREAM)\n .start.subscribe(message => {\n const data = message as OrchestrionChannelContext;\n const stream = data.self as ThreadStream | undefined;\n if (isMessageStream(stream) && stream.controller?.signal) {\n // `_start(create, params, options)`: each `create()` gets only the stream's own signal, which doesn't carry\n // the reason a caller's signal fired with.\n threadStreams.set(stream.controller.signal, { stream, callerSignal: getRequestSignal(data.arguments?.[2]) });\n }\n });\n}\n\n/**\n * Build the span for an instrumented call.\n * Returning `undefined` opts the payload out so no span is opened.\n */\nfunction createGenAiSpan(\n data: AnthropicChannelContext,\n operation: 'chat',\n options: AnthropicAiOptions,\n stream: StreamMode,\n): Span | undefined {\n const args = data.arguments ?? [];\n\n if (shouldSkipAiProviderSpan(INTEGRATION_NAME)) {\n return undefined;\n }\n\n // `messages.stream()` internally calls the instrumented `messages.create({ stream: true })` tagged with\n // a `stream` helper-method header. The messages-stream channel already covers it, so skip the nested\n // create to avoid a duplicate span. Only the non-beta helper is on that channel, though:\n // `beta.messages.stream()` and the streaming tool runner send the same header with no span covering\n // them, so the header alone is not enough. Skip only while a stream-helper span of ours is active.\n const requestOptions = args[1] as { headers?: unknown } | undefined;\n if (isStreamHelperRequest(requestOptions?.headers) && isInsideStreamHelperSpan()) {\n return undefined;\n }\n\n const params = typeof args[0] === 'object' && args[0] !== null ? (args[0] as Record<string, unknown>) : undefined;\n\n const call: AnthropicAiCallInfo = { operation, request: params };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n data._sentryRecordOutputs = recordOutputs;\n\n const attributes = extractRequestAttributes(args, operation, recordInputs, getProviderName(data.self));\n const model = (attributes[GEN_AI_REQUEST_MODEL] as string) || 'unknown';\n attributes[SENTRY_ORIGIN] = ANTHROPIC_AI_ORIGIN;\n const client = getClient();\n\n const span = startInactiveSpan({\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name: model !== 'unknown' || !(client && hasSpanStreamingEnabled(client)) ? `${operation} ${model}` : operation,\n op: getGenAiSpanOp(operation),\n attributes: attributes as Record<string, SpanAttributeValue>,\n });\n\n if (recordInputs && params) {\n addPrivateRequestAttributes(span, params);\n }\n\n runGenAiSpanStart(options, span, call);\n data._sentryOnSpanEnd = result => runGenAiSpanEnd(options, span, call, result);\n\n if (stream === 'message-stream') {\n streamHelperSpans.add(span);\n }\n\n return span;\n}\n\nconst STREAM_HELPER_METHOD_HEADER = 'x-stainless-helper-method';\n\n/** The spans opened for the messages-stream channel, i.e. for `messages.stream()` calls. */\nconst streamHelperSpans = new WeakSet<Span>();\n\n/**\n * Whether the active span is one this integration opened for `messages.stream()`. The helper's\n * internal `create` runs inside that span, so this is what tells it apart from the beta helper and\n * the tool runner, which send the same header but are not on the messages-stream channel.\n */\nfunction isInsideStreamHelperSpan(): boolean {\n const activeSpan = getActiveSpan();\n return !!activeSpan && streamHelperSpans.has(activeSpan);\n}\n\n/**\n * Whether request options carry the header the SDK's `messages.stream()` helper puts on its internal\n * `create` call. The SDK sent it as `X-Stainless-Helper-Method` up to 0.105 and lowercase since 0.106, and\n * HTTP header names are case-insensitive either way, so match without regard to case. The headers\n * arrive as a plain object; a `Headers` instance is handled for completeness.\n */\nfunction isStreamHelperRequest(headers: unknown): boolean {\n if (!headers || typeof headers !== 'object') {\n return false;\n }\n\n if (typeof (headers as Headers).get === 'function') {\n return (headers as Headers).get(STREAM_HELPER_METHOD_HEADER) === 'stream';\n }\n\n return Object.entries(headers as Record<string, unknown>).some(\n ([name, value]) => name.toLowerCase() === STREAM_HELPER_METHOD_HEADER && value === 'stream',\n );\n}\n\ntype AsyncIterableStream = { [Symbol.asyncIterator]: () => AsyncIterator<unknown> };\ntype MessageStreamEmitter = { on: (...args: unknown[]) => void };\n\nfunction isAsyncIterable(value: unknown): value is AsyncIterableStream {\n return !!value && typeof (value as AsyncIterableStream)[Symbol.asyncIterator] === 'function';\n}\n\nfunction isMessageStream(value: unknown): value is MessageStreamEmitter {\n return !!value && typeof (value as MessageStreamEmitter).on === 'function';\n}\n\ntype ThreadStream = MessageStreamEmitter & { ended?: boolean; controller?: { signal?: AbortSignal } };\n\n/**\n * The streams of threads and tool runners on 1.2+, by the signal they send each `create()` call with. Such a\n * stream parses the response itself, so the `create()` result is never parsed and never ends its span.\n */\nconst threadStreams = new WeakMap<AbortSignal, { stream: ThreadStream; callerSignal: AbortSignal | undefined }>();\n\n/**\n * End the span of a thread stream's `create()` call from the stream once the response arrives. A thread may\n * retry a rejected call, so a failed call ends its own span and only the one that succeeds reads the stream.\n */\nfunction wrapThreadStreamRequest(span: Span, data: AnthropicChannelContext, end: (error?: unknown) => void): boolean {\n const signal = (data.arguments?.[1] as { signal?: AbortSignal } | undefined)?.signal;\n const threadStream = signal && threadStreams.get(signal);\n const request = data.result as { _responseProps?: () => Promise<unknown> } | undefined;\n // A finished stream sends no more requests, so a later call with its signal is the caller's own.\n if (!threadStream || threadStream.stream.ended || typeof request?._responseProps !== 'function') {\n return false;\n }\n const { stream, callerSignal } = threadStream;\n\n const recordOutputs = !!data._sentryRecordOutputs;\n // Not `asResponse()`, which on 1.x also ends the SDK's own span when the user turned its tracing on.\n void request._responseProps().then(\n () => {\n // Only a rejected attempt is retried, so nothing else may claim this stream.\n threadStreams.delete(signal);\n instrumentMessageStream(stream, span, recordOutputs, callerSignal, data._sentryOnSpanEnd);\n },\n error => {\n // An abort is not a failed request. The stream still emits 'end', which sets the status from the caller's signal.\n if (signal.aborted) {\n instrumentMessageStream(stream, span, recordOutputs, callerSignal, data._sentryOnSpanEnd);\n } else {\n end(error);\n }\n },\n );\n return true;\n}\n\n/**\n * Hand span-ending ownership to a streamed result: returns `true` to skip the normal `beforeSpanEnd`,\n * `false` for non-streaming results (which end via `beforeSpanEnd`).\n *\n * - `async-iterable`: patch the `Stream`'s async iterator in place so `instrumentAsyncIterableStream` ends\n * the span when iteration finishes.\n * - `message-stream`: `instrumentMessageStream` attaches `'message'`/`'error'`/`'end'` listeners that end the span.\n */\nfunction wrapStreamResult(span: Span, data: AnthropicChannelContext, stream: StreamMode): boolean {\n const recordOutputs = !!data._sentryRecordOutputs;\n const result = data.result;\n\n if (stream === 'async-iterable' && isAsyncIterable(result)) {\n const iterate = result[Symbol.asyncIterator].bind(result);\n const instrumented = instrumentAsyncIterableStream(\n { [Symbol.asyncIterator]: iterate },\n span,\n recordOutputs,\n data._sentryOnSpanEnd,\n );\n result[Symbol.asyncIterator] = () => instrumented;\n return true;\n }\n\n if (stream === 'message-stream' && isMessageStream(result)) {\n instrumentMessageStream(result, span, recordOutputs, getRequestSignal(data.arguments?.[1]), data._sentryOnSpanEnd);\n return true;\n }\n\n return false;\n}\n\n/**\n * Diagnostics-channel-based Anthropic integration. Subscribes to the `orchestrion:@anthropic-ai/sdk:*`\n * diagnostics_channels injected into the SDK's chat (`messages`/`completions`/beta `messages`) and\n * `messages.stream()` methods, so it requires the Sentry runtime hook or bundler plugin.\n */\nexport const anthropicAIIntegration = defineIntegration(_anthropicAIIntegration);\n"],"mappings":";;;;;;;;;;;;;;;;;AAsBA,MAAM,mBAAmB;AASzB,MAAM,wBAAwB,CAC5B;CAAE,SAAS,SAAS;CAAgB,WAAW;CAAQ,QAAQ;AAAiB,GAChF;CACE,SAAS,SAAS;CAClB,WAAW;CACX,QAAQ;AACV,CACF;AAIA,MAAM,4BAA4B,UAA8B,CAAC,MAAM;CACrE,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GACZ,iCAAiC,QAAQ,wBAAwB,qBAAqB,CAAC,OAAO,CAAC;EACjG;CACF;AACF;AAKA,SAAS,uBAA6B;CACpC,IAAI;;EACF,CAAA,eAAA,QAAQ,IAAA,CAAI,6BAAA,aAAA,2BAA6B;CAC3C,QAAQ,CAER;AACF;AAEA,SAAS,oBAAoB,SAAmC;CAC9D,qBAAqB;CACrB,KAAK,MAAM,EAAE,SAAS,WAAW,YAAY,uBAC3C,yBACEA,eAA2D,OAAO,IAClE,SAAQ,gBAAgB,MAAM,WAAW,SAAS,MAAM,GACxD;EACE,gBAAgB,MAAM,SAAS;GAC7B,IAAI,WAAW,MACb,uBAAuB,MAAM,iBAAiB,KAAK,YAAY,EAAE,CAAC;GAEpE,sBAAsB,MAAM,KAAK,QAA+B,CAAC,CAAC,KAAK,oBAAoB;GAC3F,KAAK,mBAAmB,WAAW,OAAO,EAAE,OAAO,KAAK,MAAM,IAAI,EAAE,UAAU,KAAK,O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AS,OAAO,SAAS,mBAAmB,YACnF,OAAO;CAET,MAAM,EAAE,QAAQ,iBAAiB;CAEjC,MAAM,gBAAgB,CAAC,CAAC,KAAK;CAExB,QAAQ,eAAe,CAAC,CAAC,WACtB;EAEJ,cAAc,OAAO,MAAM;EAC3B,wBAAwB,QAAQ,MAAM,eAAe,cAAc,KAAK,gBAAgB;CAC1F,IACA,UAAS;EAEP,IAAI,OAAO,SACT,wBAAwB,QAAQ,MAAM,eAAe,cAAc,KAAK,gBAAgB;OAExF,IAAI,KAAK;CAEb,CACF;CACA,OAAO;AACT;;;;;;;;;AAUA,SAAS,iBAAiB,MAAY,MAA+B,QAA6B;CAChG,MAAM,gBAAgB,CAAC,CAAC,KAAK;CAC7B,MAAM,SAAS,KAAK;CAEpB,IAAI,WAAW,oBAAoB,gBAAgB,MAAM,GAAG;EAC1D,MAAM,UAAU,OAAO,OAAO,cAAc,CAAC,KAAK,MAAM;EACxD,MAAM,eAAe,8BACnB,GAAG,OAAO,gBAAgB,QAAQ,GAClC,MACA,eACA,KAAK,gBACP;EACA,OAAO,OAAO,uBAAuB;EACrC,OAAO;CACT;CAEA,IAAI,WAAW,oBAAoB,gBAAgB,MAAM,GAAG;EAC1D,wBAAwB,QAAQ,MAAM,eAAe,iBAAiB,KAAK,YAAY,EAAE,GAAG,KAAK,gBAAgB;EACjH,OAAO;CACT;CAEA,OAAO;AACT;;;;;;AAOA,MAAa,yBAAyB,kBAAkB,uBAAuB"}
|
|
@@ -88,6 +88,7 @@ function instrumentAwsSdk(servicesExtensions) {
|
|
|
88
88
|
httpStatusCode: errMetadata?.httpStatusCode,
|
|
89
89
|
extendedRequestId: err?.extendedRequestId ?? errMetadata?.extendedRequestId
|
|
90
90
|
});
|
|
91
|
+
servicesExtensions.errorHook(normalizedRequest, data.error, span);
|
|
91
92
|
return;
|
|
92
93
|
}
|
|
93
94
|
const output = data.result;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["AWS_REQUEST_ID","diagnosticsChannel.tracingChannel"],"sources":["../../../../src/integrations/aws-sdk/index.ts"],"sourcesContent":["import * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport type { IntegrationFn, Span } from '@sentry/core';\nimport { defineIntegration, startInactiveSpan } from '@sentry/core';\nimport {\n _AWS_REQUEST_ID as AWS_REQUEST_ID,\n AWS_REQUEST_EXTENDED_ID,\n CLOUD_REGION,\n SENTRY_KIND,\n HTTP_RESPONSE_STATUS_CODE,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { RPC } from '@sentry/conventions/op';\nimport type { GenAiOptions } from '../../ai/core/utils';\nimport type { OrchestrionChannelContext } from '../../orchestrion/types';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { awsSdkModuleNames } from '../../orchestrion/config/aws-sdk';\nimport { invokeOrchestrionInstrumentation } from '../../orchestrion/instrumentation';\nimport type { TracingChannelLifeCycleOptions } from '../../tracing-channel';\nimport { bindTracingChannelToSpan, safeChannelCallback } from '../../tracing-channel';\nimport { AWS_SDK_ORIGIN_INTEGRATION_NAME } from './constants';\nimport { ServicesExtensions } from './services';\nimport type { NormalizedRequest, NormalizedResponse, RequestMetadata } from './types';\nimport { extractAttributesFromNormalizedRequest, normalizeV3Request, removeSuffixFromStringIfExists } from './utils';\n\n// Same name as the OTel `Aws` integration by design, so enabling injection swaps this in for it.\nconst INTEGRATION_NAME = 'Aws' as const;\n\n// The context orchestrion's transform attaches to the channel: `arguments` is the live args of the\n// wrapped `Client.prototype.send` call (`[command, ...]`), `self` the client, `result`/`error` the\n// settled value. The `_sentry*` fields are stashed by us across the call's lifecycle.\ninterface AwsSendChannelContext extends OrchestrionChannelContext {\n self?: { config?: AwsClientConfig; constructor?: { name?: string } };\n _sentryNormalizedRequest?: NormalizedRequest;\n _sentryRequestMetadata?: RequestMetadata;\n _sentryRegion?: { settled: boolean; promise: Promise<void> };\n}\n\ninterface AwsClientConfig {\n serviceId?: string;\n region?: () => string | Promise<string> | undefined;\n}\n\ninterface AwsV3Command {\n input?: Record<string, unknown>;\n constructor?: { name?: string };\n}\n\n// `metadata` is smithy's `ResponseMetadata`, read off the untyped channel result/error (`any` for the\n// same reason as `CommandInput`, see types.ts).\nfunction setMetadataAttributes(span: Span, metadata: Record<string, any> | undefined): void {\n if (!metadata) {\n return;\n }\n if (metadata.requestId) {\n // oxlint-disable-next-line typescript/no-deprecated\n span.setAttribute(AWS_REQUEST_ID, metadata.requestId);\n }\n if (metadata.httpStatusCode) {\n span.setAttribute(HTTP_RESPONSE_STATUS_CODE, metadata.httpStatusCode);\n }\n if (metadata.extendedRequestId) {\n // oxlint-disable-next-line typescript/no-deprecated\n span.setAttribute(AWS_REQUEST_EXTENDED_ID, metadata.extendedRequestId);\n }\n}\n\n// `recordInputs` and `recordOutputs` apply to Bedrock Runtime calls, the only AWS calls that carry prompts and responses.\nexport type AwsIntegrationOptions = GenAiOptions;\n\nconst _awsIntegration = ((options?: AwsIntegrationOptions) => {\n const servicesExtensions = new ServicesExtensions(options);\n\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, awsSdkModuleNames, instrumentAwsSdk, [servicesExtensions]);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction getSpanOrigin(op: string): string {\n const opCategory = op.split('.')[0];\n // AI integrations use `ai` as their origin category, although their ops are `gen_ai.*`.\n const category = opCategory === 'gen_ai' ? 'ai' : opCategory;\n return `auto.${category}.${AWS_SDK_ORIGIN_INTEGRATION_NAME}`;\n}\n\nfunction instrumentAwsSdk(servicesExtensions: ServicesExtensions): void {\n const getSpan = (data: AwsSendChannelContext): Span | undefined =>\n safeChannelCallback(() => {\n const command = data.arguments[0] as AwsV3Command | undefined;\n const commandName = command?.constructor?.name;\n if (!command || !commandName) {\n // Not a recognizable v3 command call; leave the active context untouched.\n return undefined;\n }\n\n const clientConfig = data.self?.config;\n const serviceName =\n clientConfig?.serviceId ??\n // `clientName` isn't available at the `send` boundary; fall back to the client's\n // constructor name (e.g. `S3Client` -> `S3`). `serviceId` is set for all AWS clients.\n removeSuffixFromStringIfExists(data.self?.constructor?.name || 'AWS', 'Client');\n\n // Commands with all-optional members can be constructed without an input (`new\n // ListBucketsCommand()`); the OTel path traces those too, so default rather than bail.\n // The default is assigned back onto the command (not kept detached) because service hooks\n // mutate `commandInput` (trace-propagation headers, `MessageAttributeNames`) and those\n // writes must reach the serialized request. Current smithy clients already default `input`\n // to `{}` in the command constructor; this only affects older clients in our range.\n if (!command.input) {\n command.input = {};\n }\n const normalizedRequest = normalizeV3Request(serviceName, commandName, command.input, undefined);\n normalizedRequest.abortSignal = (data.arguments[1] as { abortSignal?: AbortSignal } | undefined)?.abortSignal;\n const requestMetadata = servicesExtensions.requestPreSpanHook(normalizedRequest);\n\n // `rpc` matches what the exporter infers from `rpc.service` for the OTel aws-sdk spans;\n // service extensions override it where inference yields a different op (DynamoDB: `db`).\n const op = requestMetadata.spanOp || RPC;\n const span = startInactiveSpan({\n name: requestMetadata.spanName ?? `${normalizedRequest.serviceName}.${normalizedRequest.commandName}`,\n op,\n attributes: {\n [SENTRY_KIND]: 'client',\n [SENTRY_ORIGIN]: getSpanOrigin(op),\n ...extractAttributesFromNormalizedRequest(normalizedRequest),\n ...requestMetadata.spanAttributes,\n },\n });\n\n data._sentryNormalizedRequest = normalizedRequest;\n data._sentryRequestMetadata = requestMetadata;\n\n // `region` resolves asynchronously while `send` proceeds (a channel subscriber cannot delay\n // the traced call the way the OTel middleware does). Backfill it onto the span and the\n // normalized request once available; `deferSpanEnd` holds the span open until this settles\n // so `cloud.region` cannot be lost when `send` settles first (e.g. an early failure).\n //\n // The provider call is guarded separately: the span is already started, so a synchronous\n // throw bubbling into the enclosing `safeChannelCallback` would discard it without ending it (a leaked\n // open span).\n let regionResult: string | Promise<string> | undefined;\n try {\n regionResult = clientConfig?.region?.();\n } catch {\n // Nothing to do; continue without a region.\n }\n // The `.finally` self-reference is safe: the callback only runs after initialization.\n const regionHolder: { settled: boolean; promise: Promise<void> } = {\n settled: false,\n promise: Promise.resolve(regionResult)\n .then(region => {\n if (region) {\n normalizedRequest.region = region;\n span.setAttribute(CLOUD_REGION, region);\n }\n })\n .catch(() => {\n // Nothing to do; continue without a region.\n })\n .finally(() => {\n regionHolder.settled = true;\n }),\n };\n data._sentryRegion = regionHolder;\n\n // Inject trace-propagation headers into outgoing messages (SQS/SNS/Lambda). Runs before\n // `send` proceeds, so the mutated `commandInput` is used to build the request.\n safeChannelCallback(() => servicesExtensions.requestPostSpanHook(normalizedRequest, span));\n\n return span;\n });\n\n const opts: TracingChannelLifeCycleOptions<AwsSendChannelContext> = {\n deferSpanEnd({ span, data, end }) {\n const normalizedRequest = data._sentryNormalizedRequest;\n const requestMetadata = data._sentryRequestMetadata;\n if (!normalizedRequest) {\n return false;\n }\n\n const failed = 'error' in data;\n\n // The channel `result`/`error` are untyped; the `$metadata` casts below name smithy's\n // `ResponseMetadata` shape (`any`-valued, see `setMetadataAttributes`).\n safeChannelCallback(() => {\n if (failed) {\n const err = data.error as\n | { $metadata?: Record<string, any>; RequestId?: string; extendedRequestId?: string }\n | undefined;\n const errMetadata = err?.$metadata;\n // Like the OTel path, read RequestId/extendedRequestId off the error itself, with\n // `$metadata` (which smithy service errors also carry) as the fallback. A spread won't\n // do: `$metadata` includes these keys with `undefined` values, clobbering the fallback.\n setMetadataAttributes(span, {\n requestId: err?.RequestId ?? errMetadata?.requestId,\n httpStatusCode: errMetadata?.httpStatusCode,\n extendedRequestId: err?.extendedRequestId ?? errMetadata?.extendedRequestId,\n });\n return;\n }\n\n const output = data.result as { $metadata?: Record<string, any> } | undefined;\n setMetadataAttributes(span, output?.$metadata);\n\n const normalizedResponse: NormalizedResponse = {\n data: output,\n request: normalizedRequest,\n requestId: output?.$metadata?.requestId,\n };\n servicesExtensions.responseHook(normalizedResponse, span);\n });\n\n // Streaming responses end the span when their wrapped stream is consumed (see\n // bedrock-runtime); the helper must not end it on `send` settling. Errors always end here.\n if (requestMetadata?.isStream && !failed) {\n return true;\n }\n\n // Normally the region settles long before `send` does (the SDK awaits it internally to\n // build the endpoint), but when `send` settles first (e.g. an early failure) hold the span\n // open until the region backfill lands. The error status was already applied by the\n // helper's `error` subscriber, so a plain `end()` suffices.\n const region = data._sentryRegion;\n if (region && !region.settled) {\n void region.promise.then(() => end());\n return true;\n }\n\n return false;\n },\n };\n\n // The AWS SDK's `Client.prototype.send` lives in different smithy packages across versions; the\n // transform injects one channel per package. Only the package hosting the app's client fires, so\n // subscribing to all of them is safe and never double-instruments a single call.\n const awsSendChannels = [\n CHANNELS.AWS_SMITHY_CORE_SEND,\n CHANNELS.AWS_SMITHY_CLIENT_SEND,\n CHANNELS.AWS_SDK_SMITHY_CLIENT_SEND,\n ] as const;\n\n for (const channelName of awsSendChannels) {\n bindTracingChannelToSpan(diagnosticsChannel.tracingChannel<AwsSendChannelContext>(channelName), getSpan, opts);\n }\n}\n\n/**\n * Diagnostics-channel-based aws-sdk (v3) integration.\n *\n * Subscribes to the `orchestrion:@smithy/smithy-client:send` (and equivalent) diagnostics_channel\n * Sentry's code transform injects into the AWS SDK's smithy `Client.prototype.send`, emitting\n * spans identical to the OTel `@opentelemetry/instrumentation-aws-sdk` integration. Requires the\n * Sentry runtime hook or bundler plugin.\n */\nexport const awsIntegration = defineIntegration(_awsIntegration);\n"],"mappings":";;;;;;;;;;;;;AAyBA,MAAM,mBAAmB;AAwBzB,SAAS,sBAAsB,MAAY,UAAiD;CAC1F,IAAI,CAAC,UACH;CAEF,IAAI,SAAS,WAEX,KAAK,aAAaA,iBAAgB,SAAS,SAAS;CAEtD,IAAI,SAAS,gBACX,KAAK,aAAa,2BAA2B,SAAS,cAAc;CAEtE,IAAI,SAAS,mBAEX,KAAK,aAAa,yBAAyB,SAAS,iBAAiB;AAEzE;AAKA,MAAM,oBAAoB,YAAoC;CAC5D,MAAM,qBAAqB,IAAI,mBAAmB,OAAO;CAEzD,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GACZ,iCAAiC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Ac;IACb,aAAa,UAAU;GACzB,CAAC;EACL;EACA,KAAK,gBAAgB;EAIrB,0BAA0B,mBAAmB,oBAAoB,mBAAmB,IAAI,CAAC;EAEzF,OAAO;CACT,CAAC;CAEH,MAAM,OAA8D,EAClE,aAAa,EAAE,MAAM,MAAM,OAAO;EAChC,MAAM,oBAAoB,KAAK;EAC/B,MAAM,kBAAkB,KAAK;EAC7B,IAAI,CAAC,mBACH,OAAO;EAGT,MAAM,SAAS,WAAW;EAI1B,0BAA0B;GACxB,IAAI,QAAQ;IACV,MAAM,MAAM,KAAK;IAGjB,MAAM,cAAc,KAAK;IAIzB,sBAAsB,MAAM;KAC1B,WAAW,KAAK,aAAa,aAAa;KAC1C,gBAAgB,aAAa;KAC7B,mBAAmB,KAAK,qBAAqB,aAAa;IAC5D,CAAC;IACD;GACF;GAEA,MAAM,SAAS,KAAK;GACpB,sBAAsB,MAAM,QAAQ,SAAS;GAE7C,MAAM,qBAAyC;IAC7C,MAAM;IACN,SAAS;IACT,WAAW,QAAQ,WAAW;GAChC;GACA,mBAAmB,aAAa,oBAAoB,IAAI;EAC1D,CAAC;EAID,IAAI,iBAAiB,YAAY,CAAC,QAChC,OAAO;EAOT,MAAM,SAAS,KAAK;EACpB,IAAI,UAAU,CAAC,OAAO,SAAS;GACxB,OAAO,QAAQ,WAAW,IAAI,CAAC;GACpC,OAAO;EACT;EAEA,OAAO;CACT,EACF;CAKA,MAAM,kBAAkB;EACtB,SAAS;EACT,SAAS;EACT,SAAS;CACX;CAEA,KAAK,MAAM,eAAe,iBACxB,yBAAyBC,eAAyD,WAAW,GAAG,SAAS,IAAI;AAEjH;;;;;;;;;AAUA,MAAa,iBAAiB,kBAAkB,eAAe"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["AWS_REQUEST_ID","diagnosticsChannel.tracingChannel"],"sources":["../../../../src/integrations/aws-sdk/index.ts"],"sourcesContent":["import * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport type { IntegrationFn, Span } from '@sentry/core';\nimport { defineIntegration, startInactiveSpan } from '@sentry/core';\nimport {\n _AWS_REQUEST_ID as AWS_REQUEST_ID,\n AWS_REQUEST_EXTENDED_ID,\n CLOUD_REGION,\n SENTRY_KIND,\n HTTP_RESPONSE_STATUS_CODE,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { RPC } from '@sentry/conventions/op';\nimport type { OrchestrionChannelContext } from '../../orchestrion/types';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { awsSdkModuleNames } from '../../orchestrion/config/aws-sdk';\nimport { invokeOrchestrionInstrumentation } from '../../orchestrion/instrumentation';\nimport type { TracingChannelLifeCycleOptions } from '../../tracing-channel';\nimport { bindTracingChannelToSpan, safeChannelCallback } from '../../tracing-channel';\nimport { AWS_SDK_ORIGIN_INTEGRATION_NAME } from './constants';\nimport { ServicesExtensions } from './services';\nimport type { BedrockRuntimeOptions } from './services/bedrock-runtime';\nimport type { NormalizedRequest, NormalizedResponse, RequestMetadata } from './types';\nimport { extractAttributesFromNormalizedRequest, normalizeV3Request, removeSuffixFromStringIfExists } from './utils';\n\n// Same name as the OTel `Aws` integration by design, so enabling injection swaps this in for it.\nconst INTEGRATION_NAME = 'Aws' as const;\n\n// The context orchestrion's transform attaches to the channel: `arguments` is the live args of the\n// wrapped `Client.prototype.send` call (`[command, ...]`), `self` the client, `result`/`error` the\n// settled value. The `_sentry*` fields are stashed by us across the call's lifecycle.\ninterface AwsSendChannelContext extends OrchestrionChannelContext {\n self?: { config?: AwsClientConfig; constructor?: { name?: string } };\n _sentryNormalizedRequest?: NormalizedRequest;\n _sentryRequestMetadata?: RequestMetadata;\n _sentryRegion?: { settled: boolean; promise: Promise<void> };\n}\n\ninterface AwsClientConfig {\n serviceId?: string;\n region?: () => string | Promise<string> | undefined;\n}\n\ninterface AwsV3Command {\n input?: Record<string, unknown>;\n constructor?: { name?: string };\n}\n\n// `metadata` is smithy's `ResponseMetadata`, read off the untyped channel result/error (`any` for the\n// same reason as `CommandInput`, see types.ts).\nfunction setMetadataAttributes(span: Span, metadata: Record<string, any> | undefined): void {\n if (!metadata) {\n return;\n }\n if (metadata.requestId) {\n // oxlint-disable-next-line typescript/no-deprecated\n span.setAttribute(AWS_REQUEST_ID, metadata.requestId);\n }\n if (metadata.httpStatusCode) {\n span.setAttribute(HTTP_RESPONSE_STATUS_CODE, metadata.httpStatusCode);\n }\n if (metadata.extendedRequestId) {\n // oxlint-disable-next-line typescript/no-deprecated\n span.setAttribute(AWS_REQUEST_EXTENDED_ID, metadata.extendedRequestId);\n }\n}\n\n// `recordInputs` and `recordOutputs` apply to Bedrock Runtime calls, the only AWS calls that carry prompts and responses.\nexport type AwsIntegrationOptions = BedrockRuntimeOptions;\n\nconst _awsIntegration = ((options?: AwsIntegrationOptions) => {\n const servicesExtensions = new ServicesExtensions(options);\n\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, awsSdkModuleNames, instrumentAwsSdk, [servicesExtensions]);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction getSpanOrigin(op: string): string {\n const opCategory = op.split('.')[0];\n // AI integrations use `ai` as their origin category, although their ops are `gen_ai.*`.\n const category = opCategory === 'gen_ai' ? 'ai' : opCategory;\n return `auto.${category}.${AWS_SDK_ORIGIN_INTEGRATION_NAME}`;\n}\n\nfunction instrumentAwsSdk(servicesExtensions: ServicesExtensions): void {\n const getSpan = (data: AwsSendChannelContext): Span | undefined =>\n safeChannelCallback(() => {\n const command = data.arguments[0] as AwsV3Command | undefined;\n const commandName = command?.constructor?.name;\n if (!command || !commandName) {\n // Not a recognizable v3 command call; leave the active context untouched.\n return undefined;\n }\n\n const clientConfig = data.self?.config;\n const serviceName =\n clientConfig?.serviceId ??\n // `clientName` isn't available at the `send` boundary; fall back to the client's\n // constructor name (e.g. `S3Client` -> `S3`). `serviceId` is set for all AWS clients.\n removeSuffixFromStringIfExists(data.self?.constructor?.name || 'AWS', 'Client');\n\n // Commands with all-optional members can be constructed without an input (`new\n // ListBucketsCommand()`); the OTel path traces those too, so default rather than bail.\n // The default is assigned back onto the command (not kept detached) because service hooks\n // mutate `commandInput` (trace-propagation headers, `MessageAttributeNames`) and those\n // writes must reach the serialized request. Current smithy clients already default `input`\n // to `{}` in the command constructor; this only affects older clients in our range.\n if (!command.input) {\n command.input = {};\n }\n const normalizedRequest = normalizeV3Request(serviceName, commandName, command.input, undefined);\n normalizedRequest.abortSignal = (data.arguments[1] as { abortSignal?: AbortSignal } | undefined)?.abortSignal;\n const requestMetadata = servicesExtensions.requestPreSpanHook(normalizedRequest);\n\n // `rpc` matches what the exporter infers from `rpc.service` for the OTel aws-sdk spans;\n // service extensions override it where inference yields a different op (DynamoDB: `db`).\n const op = requestMetadata.spanOp || RPC;\n const span = startInactiveSpan({\n name: requestMetadata.spanName ?? `${normalizedRequest.serviceName}.${normalizedRequest.commandName}`,\n op,\n attributes: {\n [SENTRY_KIND]: 'client',\n [SENTRY_ORIGIN]: getSpanOrigin(op),\n ...extractAttributesFromNormalizedRequest(normalizedRequest),\n ...requestMetadata.spanAttributes,\n },\n });\n\n data._sentryNormalizedRequest = normalizedRequest;\n data._sentryRequestMetadata = requestMetadata;\n\n // `region` resolves asynchronously while `send` proceeds (a channel subscriber cannot delay\n // the traced call the way the OTel middleware does). Backfill it onto the span and the\n // normalized request once available; `deferSpanEnd` holds the span open until this settles\n // so `cloud.region` cannot be lost when `send` settles first (e.g. an early failure).\n //\n // The provider call is guarded separately: the span is already started, so a synchronous\n // throw bubbling into the enclosing `safeChannelCallback` would discard it without ending it (a leaked\n // open span).\n let regionResult: string | Promise<string> | undefined;\n try {\n regionResult = clientConfig?.region?.();\n } catch {\n // Nothing to do; continue without a region.\n }\n // The `.finally` self-reference is safe: the callback only runs after initialization.\n const regionHolder: { settled: boolean; promise: Promise<void> } = {\n settled: false,\n promise: Promise.resolve(regionResult)\n .then(region => {\n if (region) {\n normalizedRequest.region = region;\n span.setAttribute(CLOUD_REGION, region);\n }\n })\n .catch(() => {\n // Nothing to do; continue without a region.\n })\n .finally(() => {\n regionHolder.settled = true;\n }),\n };\n data._sentryRegion = regionHolder;\n\n // Inject trace-propagation headers into outgoing messages (SQS/SNS/Lambda). Runs before\n // `send` proceeds, so the mutated `commandInput` is used to build the request.\n safeChannelCallback(() => servicesExtensions.requestPostSpanHook(normalizedRequest, span));\n\n return span;\n });\n\n const opts: TracingChannelLifeCycleOptions<AwsSendChannelContext> = {\n deferSpanEnd({ span, data, end }) {\n const normalizedRequest = data._sentryNormalizedRequest;\n const requestMetadata = data._sentryRequestMetadata;\n if (!normalizedRequest) {\n return false;\n }\n\n const failed = 'error' in data;\n\n // The channel `result`/`error` are untyped; the `$metadata` casts below name smithy's\n // `ResponseMetadata` shape (`any`-valued, see `setMetadataAttributes`).\n safeChannelCallback(() => {\n if (failed) {\n const err = data.error as\n | { $metadata?: Record<string, any>; RequestId?: string; extendedRequestId?: string }\n | undefined;\n const errMetadata = err?.$metadata;\n // Like the OTel path, read RequestId/extendedRequestId off the error itself, with\n // `$metadata` (which smithy service errors also carry) as the fallback. A spread won't\n // do: `$metadata` includes these keys with `undefined` values, clobbering the fallback.\n setMetadataAttributes(span, {\n requestId: err?.RequestId ?? errMetadata?.requestId,\n httpStatusCode: errMetadata?.httpStatusCode,\n extendedRequestId: err?.extendedRequestId ?? errMetadata?.extendedRequestId,\n });\n servicesExtensions.errorHook(normalizedRequest, data.error, span);\n return;\n }\n\n const output = data.result as { $metadata?: Record<string, any> } | undefined;\n setMetadataAttributes(span, output?.$metadata);\n\n const normalizedResponse: NormalizedResponse = {\n data: output,\n request: normalizedRequest,\n requestId: output?.$metadata?.requestId,\n };\n servicesExtensions.responseHook(normalizedResponse, span);\n });\n\n // Streaming responses end the span when their wrapped stream is consumed (see\n // bedrock-runtime); the helper must not end it on `send` settling. Errors always end here.\n if (requestMetadata?.isStream && !failed) {\n return true;\n }\n\n // Normally the region settles long before `send` does (the SDK awaits it internally to\n // build the endpoint), but when `send` settles first (e.g. an early failure) hold the span\n // open until the region backfill lands. The error status was already applied by the\n // helper's `error` subscriber, so a plain `end()` suffices.\n const region = data._sentryRegion;\n if (region && !region.settled) {\n void region.promise.then(() => end());\n return true;\n }\n\n return false;\n },\n };\n\n // The AWS SDK's `Client.prototype.send` lives in different smithy packages across versions; the\n // transform injects one channel per package. Only the package hosting the app's client fires, so\n // subscribing to all of them is safe and never double-instruments a single call.\n const awsSendChannels = [\n CHANNELS.AWS_SMITHY_CORE_SEND,\n CHANNELS.AWS_SMITHY_CLIENT_SEND,\n CHANNELS.AWS_SDK_SMITHY_CLIENT_SEND,\n ] as const;\n\n for (const channelName of awsSendChannels) {\n bindTracingChannelToSpan(diagnosticsChannel.tracingChannel<AwsSendChannelContext>(channelName), getSpan, opts);\n }\n}\n\n/**\n * Diagnostics-channel-based aws-sdk (v3) integration.\n *\n * Subscribes to the `orchestrion:@smithy/smithy-client:send` (and equivalent) diagnostics_channel\n * Sentry's code transform injects into the AWS SDK's smithy `Client.prototype.send`, emitting\n * spans identical to the OTel `@opentelemetry/instrumentation-aws-sdk` integration. Requires the\n * Sentry runtime hook or bundler plugin.\n */\nexport const awsIntegration = defineIntegration(_awsIntegration);\n"],"mappings":";;;;;;;;;;;;;AAyBA,MAAM,mBAAmB;AAwBzB,SAAS,sBAAsB,MAAY,UAAiD;CAC1F,IAAI,CAAC,UACH;CAEF,IAAI,SAAS,WAEX,KAAK,aAAaA,iBAAgB,SAAS,SAAS;CAEtD,IAAI,SAAS,gBACX,KAAK,aAAa,2BAA2B,SAAS,cAAc;CAEtE,IAAI,SAAS,mBAEX,KAAK,aAAa,yBAAyB,SAAS,iBAAiB;AAEzE;AAKA,MAAM,oBAAoB,YAAoC;CAC5D,MAAM,qBAAqB,IAAI,mBAAmB,OAAO;CAEzD,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GACZ,iCAAiC,QAAQ,mBAAmB,kBAAkB,CAAC,kBAAkB,CAAC;EACpG;CACF;AACF;AAEA,SAAS,cAAc,IAA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AAoB,mBAAmB,IAAI,CAAC;EAEzF,OAAO;CACT,CAAC;CAEH,MAAM,OAA8D,EAClE,aAAa,EAAE,MAAM,MAAM,OAAO;EAChC,MAAM,oBAAoB,KAAK;EAC/B,MAAM,kBAAkB,KAAK;EAC7B,IAAI,CAAC,mBACH,OAAO;EAGT,MAAM,SAAS,WAAW;EAI1B,0BAA0B;GACxB,IAAI,QAAQ;IACV,MAAM,MAAM,KAAK;IAGjB,MAAM,cAAc,KAAK;IAIzB,sBAAsB,MAAM;KAC1B,WAAW,KAAK,aAAa,aAAa;KAC1C,gBAAgB,aAAa;KAC7B,mBAAmB,KAAK,qBAAqB,aAAa;IAC5D,CAAC;IACD,mBAAmB,UAAU,mBAAmB,KAAK,OAAO,IAAI;IAChE;GACF;GAEA,MAAM,SAAS,KAAK;GACpB,sBAAsB,MAAM,QAAQ,SAAS;GAE7C,MAAM,qBAAyC;IAC7C,MAAM;IACN,SAAS;IACT,WAAW,QAAQ,WAAW;GAChC;GACA,mBAAmB,aAAa,oBAAoB,IAAI;EAC1D,CAAC;EAID,IAAI,iBAAiB,YAAY,CAAC,QAChC,OAAO;EAOT,MAAM,SAAS,KAAK;EACpB,IAAI,UAAU,CAAC,OAAO,SAAS;GACxB,OAAO,QAAQ,WAAW,IAAI,CAAC;GACpC,OAAO;EACT;EAEA,OAAO;CACT,EACF;CAKA,MAAM,kBAAkB;EACtB,SAAS;EACT,SAAS;EACT,SAAS;CACX;CAEA,KAAK,MAAM,eAAe,iBACxB,yBAAyBC,eAAyD,WAAW,GAAG,SAAS,IAAI;AAEjH;;;;;;;;;AAUA,MAAa,iBAAiB,kBAAkB,eAAe"}
|
|
@@ -33,6 +33,9 @@ var ServicesExtensions = class {
|
|
|
33
33
|
responseHook(response, span) {
|
|
34
34
|
this._services.get(response.request.serviceName)?.responseHook?.(response, span);
|
|
35
35
|
}
|
|
36
|
+
errorHook(request, error, span) {
|
|
37
|
+
this._services.get(request.serviceName)?.errorHook?.(request, error, span);
|
|
38
|
+
}
|
|
36
39
|
};
|
|
37
40
|
export { ServicesExtensions };
|
|
38
41
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ServicesExtensions.js","names":[],"sources":["../../../../../src/integrations/aws-sdk/services/ServicesExtensions.ts"],"sourcesContent":["import type { Span } from '@sentry/core';\nimport type {
|
|
1
|
+
{"version":3,"file":"ServicesExtensions.js","names":[],"sources":["../../../../../src/integrations/aws-sdk/services/ServicesExtensions.ts"],"sourcesContent":["import type { Span } from '@sentry/core';\nimport type { NormalizedRequest, NormalizedResponse, RequestMetadata } from '../types';\nimport type { BedrockRuntimeOptions } from './bedrock-runtime';\nimport { BedrockRuntimeServiceExtension } from './bedrock-runtime';\nimport { DynamodbServiceExtension } from './dynamodb';\nimport { KinesisServiceExtension } from './kinesis';\nimport { LambdaServiceExtension } from './lambda';\nimport { S3ServiceExtension } from './s3';\nimport { SecretsManagerServiceExtension } from './secretsmanager';\nimport type { ServiceExtension } from './ServiceExtension';\nimport { SnsServiceExtension } from './sns';\nimport { SqsServiceExtension } from './sqs';\nimport { StepFunctionsServiceExtension } from './stepfunctions';\n\nexport class ServicesExtensions implements ServiceExtension {\n // Per-service extensions, keyed by the client's `serviceId` (e.g. `'S3'`). Services without a\n // registered extension still get the base rpc span from the subscriber.\n private _services: Map<string, ServiceExtension>;\n\n public constructor(genAiOptions?: BedrockRuntimeOptions) {\n this._services = new Map<string, ServiceExtension>([\n ['SecretsManager', new SecretsManagerServiceExtension()],\n ['SFN', new StepFunctionsServiceExtension()],\n ['SQS', new SqsServiceExtension()],\n ['SNS', new SnsServiceExtension()],\n ['DynamoDB', new DynamodbServiceExtension()],\n ['Lambda', new LambdaServiceExtension()],\n ['S3', new S3ServiceExtension()],\n ['Kinesis', new KinesisServiceExtension()],\n ['BedrockRuntime', new BedrockRuntimeServiceExtension(genAiOptions)],\n ]);\n }\n\n public requestPreSpanHook(request: NormalizedRequest): RequestMetadata {\n const serviceExtension = this._services.get(request.serviceName);\n if (!serviceExtension) {\n return {};\n }\n return serviceExtension.requestPreSpanHook(request);\n }\n\n public requestPostSpanHook(request: NormalizedRequest, span: Span): void {\n const serviceExtension = this._services.get(request.serviceName);\n serviceExtension?.requestPostSpanHook?.(request, span);\n }\n\n public responseHook(response: NormalizedResponse, span: Span): void {\n const serviceExtension = this._services.get(response.request.serviceName);\n serviceExtension?.responseHook?.(response, span);\n }\n\n public errorHook(request: NormalizedRequest, error: unknown, span: Span): void {\n const serviceExtension = this._services.get(request.serviceName);\n serviceExtension?.errorHook?.(request, error, span);\n }\n}\n"],"mappings":";;;;;;;;;;AAcA,IAAa,qBAAb,MAA4D;CAKnD,YAAY,cAAsC;EACvD,KAAK,4BAAY,IAAI,IAA8B;GACjD,CAAC,kBAAkB,IAAI,+BAA+B,CAAC;GACvD,CAAC,OAAO,IAAI,8BAA8B,CAAC;GAC3C,CAAC,OAAO,IAAI,oBAAoB,CAAC;GACjC,CAAC,OAAO,IAAI,oBAAoB,CAAC;GACjC,CAAC,YAAY,IAAI,yBAAyB,CAAC;GAC3C,CAAC,UAAU,IAAI,uBAAuB,CAAC;GACvC,CAAC,MAAM,IAAI,mBAAmB,CAAC;GAC/B,CAAC,WAAW,IAAI,wBAAwB,CAAC;GACzC,CAAC,kBAAkB,IAAI,+BAA+B,YAAY,CAAC;EACrE,CAAC;CACH;CAEO,mBAAmB,SAA6C;EACrE,MAAM,mBAAmB,KAAK,UAAU,IAAI,QAAQ,WAAW;EAC/D,IAAI,CAAC,kBACH,OAAO,CAAC;EAEV,OAAO,iBAAiB,mBAAmB,OAAO;CACpD;CAEO,oBAAoB,SAA4B,MAAkB;EAC9C,KAAK,UAAU,IAAI,QAAQ,WACrC,CAAC,EAAE,sBAAsB,SAAS,IAAI;CACvD;CAEO,aAAa,UAA8B,MAAkB;EACzC,KAAK,UAAU,IAAI,SAAS,QAAQ,WAC9C,CAAC,EAAE,eAAe,UAAU,IAAI;CACjD;CAEO,UAAU,SAA4B,OAAgB,MAAkB;EACpD,KAAK,UAAU,IAAI,QAAQ,WACrC,CAAC,EAAE,YAAY,SAAS,OAAO,IAAI;CACpD;AACF"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { runGenAiSpanEnd, runGenAiSpanStart } from "../../../ai/core/span-hooks.js";
|
|
2
|
+
import { endStreamSpan, getErrorStatus, getTokenUsageAttributes, resolveGenAiCallRecording } from "../../../ai/core/utils.js";
|
|
2
3
|
import { isInsidePiAiSpan } from "../../../ai/pi-ai/providers.js";
|
|
3
4
|
import { DEBUG_BUILD } from "../../../debug-build.js";
|
|
4
5
|
import { GEN_AI_OPERATION_NAME_VALUE_CHAT, GEN_AI_OPERATION_NAME_VALUE_GENERATE_CONTENT, GEN_AI_SYSTEM_VALUE_AWS_BEDROCK } from "../constants.js";
|
|
@@ -12,9 +13,33 @@ var BedrockRuntimeServiceExtension = class {
|
|
|
12
13
|
constructor(_options = {}) {
|
|
13
14
|
this._options = _options;
|
|
14
15
|
this._piAiRequests = /* @__PURE__ */ new WeakSet();
|
|
16
|
+
this._calls = /* @__PURE__ */ new WeakMap();
|
|
15
17
|
}
|
|
16
|
-
|
|
17
|
-
|
|
18
|
+
_resolveRecording(request) {
|
|
19
|
+
const info = {
|
|
20
|
+
commandName: request.commandName,
|
|
21
|
+
input: request.commandInput
|
|
22
|
+
};
|
|
23
|
+
const { recordInputs, recordOutputs } = resolveGenAiCallRecording(this._options, info);
|
|
24
|
+
this._calls.set(request, {
|
|
25
|
+
info,
|
|
26
|
+
recordOutputs
|
|
27
|
+
});
|
|
28
|
+
return recordInputs;
|
|
29
|
+
}
|
|
30
|
+
_shouldRecordOutputs(response) {
|
|
31
|
+
return this._calls.get(response.request)?.recordOutputs ?? false;
|
|
32
|
+
}
|
|
33
|
+
_runSpanEnd(request, span, result) {
|
|
34
|
+
const call = this._calls.get(request);
|
|
35
|
+
if (call) runGenAiSpanEnd(this._options, span, call.info, result);
|
|
36
|
+
}
|
|
37
|
+
requestPostSpanHook(request, span) {
|
|
38
|
+
const call = this._calls.get(request);
|
|
39
|
+
if (call) runGenAiSpanStart(this._options, span, call.info);
|
|
40
|
+
}
|
|
41
|
+
errorHook(request, error, span) {
|
|
42
|
+
this._runSpanEnd(request, span, { error });
|
|
18
43
|
}
|
|
19
44
|
requestPreSpanHook(request) {
|
|
20
45
|
if (isInsidePiAiSpan()) {
|
|
@@ -49,6 +74,7 @@ var BedrockRuntimeServiceExtension = class {
|
|
|
49
74
|
[GEN_AI_PROVIDER_NAME]: GEN_AI_SYSTEM_VALUE_AWS_BEDROCK,
|
|
50
75
|
[GEN_AI_OPERATION_NAME]: GEN_AI_OPERATION_NAME_VALUE_CHAT
|
|
51
76
|
};
|
|
77
|
+
const recordInputs = this._resolveRecording(request);
|
|
52
78
|
const modelId = request.commandInput.modelId;
|
|
53
79
|
if (modelId) {
|
|
54
80
|
spanAttributes[GEN_AI_REQUEST_MODEL] = modelId;
|
|
@@ -62,7 +88,7 @@ var BedrockRuntimeServiceExtension = class {
|
|
|
62
88
|
if (topP !== void 0) spanAttributes[GEN_AI_REQUEST_TOP_P] = topP;
|
|
63
89
|
if (stopSequences !== void 0) spanAttributes[GEN_AI_REQUEST_STOP_SEQUENCES] = stopSequences;
|
|
64
90
|
}
|
|
65
|
-
if (
|
|
91
|
+
if (recordInputs) Object.assign(spanAttributes, getConverseInputAttributes(request.commandInput));
|
|
66
92
|
return {
|
|
67
93
|
spanName,
|
|
68
94
|
spanOp: GEN_AI_CHAT,
|
|
@@ -76,6 +102,7 @@ var BedrockRuntimeServiceExtension = class {
|
|
|
76
102
|
[GEN_AI_PROVIDER_NAME]: GEN_AI_SYSTEM_VALUE_AWS_BEDROCK,
|
|
77
103
|
[GEN_AI_OPERATION_NAME]: GEN_AI_OPERATION_NAME_VALUE_GENERATE_CONTENT
|
|
78
104
|
};
|
|
105
|
+
const recordInputs = this._resolveRecording(request);
|
|
79
106
|
const modelId = request.commandInput?.modelId;
|
|
80
107
|
if (modelId) {
|
|
81
108
|
spanAttributes[GEN_AI_REQUEST_MODEL] = modelId;
|
|
@@ -121,7 +148,7 @@ var BedrockRuntimeServiceExtension = class {
|
|
|
121
148
|
if (requestBody.top_p !== void 0) spanAttributes[GEN_AI_REQUEST_TOP_P] = requestBody.top_p;
|
|
122
149
|
if (requestBody.stop !== void 0) spanAttributes[GEN_AI_REQUEST_STOP_SEQUENCES] = requestBody.stop;
|
|
123
150
|
}
|
|
124
|
-
if (
|
|
151
|
+
if (recordInputs) Object.assign(spanAttributes, getInvokeModelInputAttributes(modelId, requestBody));
|
|
125
152
|
}
|
|
126
153
|
return {
|
|
127
154
|
spanName,
|
|
@@ -133,15 +160,17 @@ var BedrockRuntimeServiceExtension = class {
|
|
|
133
160
|
_responseHookConverse(response, span) {
|
|
134
161
|
const { stopReason, usage, output } = response.data;
|
|
135
162
|
setStopReason(span, stopReason);
|
|
136
|
-
if (this.
|
|
163
|
+
if (this._shouldRecordOutputs(response)) setOutputMessages(span, contentBlocksToParts(output?.message?.content));
|
|
137
164
|
span.setAttributes(getTokenUsageAttributes(typeof usage?.inputTokens === "number" ? usage.inputTokens + (usage.cacheReadInputTokens ?? 0) + (usage.cacheWriteInputTokens ?? 0) : void 0, usage?.outputTokens, usage?.cacheWriteInputTokens, usage?.cacheReadInputTokens));
|
|
165
|
+
this._runSpanEnd(response.request, span, { response: response.data });
|
|
138
166
|
}
|
|
139
167
|
_responseHookConverseStream(response, span) {
|
|
140
168
|
if (!response.data?.stream) {
|
|
169
|
+
this._runSpanEnd(response.request, span, { response: response.data });
|
|
141
170
|
span.end();
|
|
142
171
|
return;
|
|
143
172
|
}
|
|
144
|
-
response.data.stream = instrumentStream(response.data.stream, span, response.request.abortSignal, this.
|
|
173
|
+
response.data.stream = instrumentStream(response.data.stream, span, response.request.abortSignal, this._shouldRecordOutputs(response), processConverseStreamEvent, (result) => this._runSpanEnd(response.request, span, result));
|
|
145
174
|
}
|
|
146
175
|
_responseHookInvokeModel(response, span) {
|
|
147
176
|
const currentModelId = response.request.commandInput?.modelId;
|
|
@@ -170,18 +199,20 @@ var BedrockRuntimeServiceExtension = class {
|
|
|
170
199
|
} else if (currentModelId.includes("mistral")) {
|
|
171
200
|
if (responseBody.outputs?.[0]?.text !== void 0) span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, Math.ceil(responseBody.outputs[0].text.length / 6));
|
|
172
201
|
}
|
|
173
|
-
if (this.
|
|
202
|
+
if (this._shouldRecordOutputs(response)) setOutputMessages(span, getInvokeModelOutputParts(responseBody));
|
|
174
203
|
}
|
|
204
|
+
this._runSpanEnd(response.request, span, { response: response.data });
|
|
175
205
|
}
|
|
176
206
|
_responseHookInvokeModelWithResponseStream(response, span) {
|
|
177
207
|
const stream = response.data?.body;
|
|
178
208
|
const modelId = response.request.commandInput?.modelId;
|
|
179
209
|
if (!stream) {
|
|
210
|
+
this._runSpanEnd(response.request, span, { response: response.data });
|
|
180
211
|
span.end();
|
|
181
212
|
return;
|
|
182
213
|
}
|
|
183
214
|
const processChunk = typeof modelId === "string" ? resolveStreamProcessor(modelId) : void 0;
|
|
184
|
-
response.data.body = instrumentStream(stream, span, response.request.abortSignal, this.
|
|
215
|
+
response.data.body = instrumentStream(stream, span, response.request.abortSignal, this._shouldRecordOutputs(response), (item, state) => {
|
|
185
216
|
if (processChunk) {
|
|
186
217
|
const parsedChunk = parseChunk(item?.chunk?.bytes);
|
|
187
218
|
if (parsedChunk) {
|
|
@@ -189,7 +220,7 @@ var BedrockRuntimeServiceExtension = class {
|
|
|
189
220
|
processChunk(parsedChunk, state);
|
|
190
221
|
}
|
|
191
222
|
}
|
|
192
|
-
});
|
|
223
|
+
}, (result) => this._runSpanEnd(response.request, span, result));
|
|
193
224
|
}
|
|
194
225
|
};
|
|
195
226
|
function getInvokeModelOutputParts(responseBody) {
|
|
@@ -214,13 +245,14 @@ function resolveStreamProcessor(modelId) {
|
|
|
214
245
|
if (modelId.includes("mistral")) return processMistralChunk;
|
|
215
246
|
}
|
|
216
247
|
/** Collects the stream items into a state and sets the span attributes from it when the stream ends. */
|
|
217
|
-
async function* instrumentStream(stream, span, abortSignal, recordOutputs, processItem) {
|
|
248
|
+
async function* instrumentStream(stream, span, abortSignal, recordOutputs, processItem, beforeSpanEnd) {
|
|
218
249
|
const state = {
|
|
219
250
|
finishReasons: [],
|
|
220
251
|
responseTexts: [],
|
|
221
252
|
toolCalls: [],
|
|
222
253
|
parts: recordOutputs ? [] : void 0
|
|
223
254
|
};
|
|
255
|
+
const result = {};
|
|
224
256
|
try {
|
|
225
257
|
for await (const item of stream) {
|
|
226
258
|
processItem(item, state);
|
|
@@ -228,10 +260,11 @@ async function* instrumentStream(stream, span, abortSignal, recordOutputs, proce
|
|
|
228
260
|
}
|
|
229
261
|
} catch (error) {
|
|
230
262
|
span.setStatus(getErrorStatus(abortSignal));
|
|
263
|
+
result.error = error;
|
|
231
264
|
throw error;
|
|
232
265
|
} finally {
|
|
233
266
|
if (state.parts) setOutputMessages(span, state.parts);
|
|
234
|
-
endStreamSpan(span, state, false);
|
|
267
|
+
endStreamSpan(span, state, false, () => beforeSpanEnd(result));
|
|
235
268
|
}
|
|
236
269
|
}
|
|
237
270
|
function processConverseStreamEvent(event, state) {
|