@sentry/server-utils 11.14.0 → 11.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/cjs/chunks/exports.js +526 -217
- package/build/cjs/chunks/exports.js.map +1 -1
- package/build/cjs/index.js +1028 -120
- package/build/cjs/index.js.map +1 -1
- package/build/esm/ai/anthropic-ai/index.js +32 -56
- package/build/esm/ai/anthropic-ai/index.js.map +1 -1
- package/build/esm/ai/anthropic-ai/streaming.js +10 -6
- package/build/esm/ai/anthropic-ai/streaming.js.map +1 -1
- package/build/esm/ai/anthropic-ai/tool-runner.js +18 -3
- package/build/esm/ai/anthropic-ai/tool-runner.js.map +1 -1
- package/build/esm/ai/anthropic-ai/utils.js +41 -3
- package/build/esm/ai/anthropic-ai/utils.js.map +1 -1
- package/build/esm/ai/core/span-hooks.js +23 -0
- package/build/esm/ai/core/span-hooks.js.map +1 -0
- package/build/esm/ai/core/time-to-first-chunk.js +14 -0
- package/build/esm/ai/core/time-to-first-chunk.js.map +1 -0
- package/build/esm/ai/core/utils.js +29 -3
- package/build/esm/ai/core/utils.js.map +1 -1
- package/build/esm/ai/flue/index.js +15 -12
- package/build/esm/ai/flue/index.js.map +1 -1
- package/build/esm/ai/flue/utils.js +24 -17
- package/build/esm/ai/flue/utils.js.map +1 -1
- package/build/esm/ai/google-genai/index.js +21 -8
- package/build/esm/ai/google-genai/index.js.map +1 -1
- package/build/esm/ai/google-genai/streaming.js +6 -2
- package/build/esm/ai/google-genai/streaming.js.map +1 -1
- package/build/esm/ai/langchain/embeddings.js +5 -2
- package/build/esm/ai/langchain/embeddings.js.map +1 -1
- package/build/esm/ai/langchain/index.js +82 -24
- package/build/esm/ai/langchain/index.js.map +1 -1
- package/build/esm/ai/langchain/utils.js +9 -1
- package/build/esm/ai/langchain/utils.js.map +1 -1
- package/build/esm/ai/langgraph/agent-span.js +13 -5
- package/build/esm/ai/langgraph/agent-span.js.map +1 -1
- package/build/esm/ai/langgraph/index.js +13 -15
- package/build/esm/ai/langgraph/index.js.map +1 -1
- package/build/esm/ai/langgraph/stream.js +4 -3
- package/build/esm/ai/langgraph/stream.js.map +1 -1
- package/build/esm/ai/langgraph/utils.js +17 -8
- package/build/esm/ai/langgraph/utils.js.map +1 -1
- package/build/esm/ai/mastra/classifier-evaluation.js.map +1 -1
- package/build/esm/ai/mastra/index.js +33 -16
- package/build/esm/ai/mastra/index.js.map +1 -1
- package/build/esm/ai/mastra/utils.js +3 -5
- package/build/esm/ai/mastra/utils.js.map +1 -1
- package/build/esm/ai/mistral/index.js +21 -7
- package/build/esm/ai/mistral/index.js.map +1 -1
- package/build/esm/ai/mistral/streaming.js +4 -2
- package/build/esm/ai/mistral/streaming.js.map +1 -1
- package/build/esm/ai/openai/index.js +19 -8
- package/build/esm/ai/openai/index.js.map +1 -1
- package/build/esm/ai/openai/streaming.js +7 -2
- package/build/esm/ai/openai/streaming.js.map +1 -1
- package/build/esm/ai/pi-ai/chat.js +18 -1
- package/build/esm/ai/pi-ai/chat.js.map +1 -1
- package/build/esm/ai/pi-ai/recording.js +34 -15
- package/build/esm/ai/pi-ai/recording.js.map +1 -1
- package/build/esm/ai/pi-durable/index.js +7 -2
- package/build/esm/ai/pi-durable/index.js.map +1 -1
- package/build/esm/ai/pi-durable/runs.js.map +1 -1
- package/build/esm/ai/pi-durable/tools.js +18 -3
- package/build/esm/ai/pi-durable/tools.js.map +1 -1
- package/build/esm/ai/typesafe/index.js +14 -6
- package/build/esm/ai/typesafe/index.js.map +1 -1
- package/build/esm/ai/workers-ai/index.js +26 -9
- package/build/esm/ai/workers-ai/index.js.map +1 -1
- package/build/esm/ai/workers-ai/streaming.js +6 -4
- package/build/esm/ai/workers-ai/streaming.js.map +1 -1
- package/build/esm/cron/common.js +16 -0
- package/build/esm/cron/common.js.map +1 -0
- package/build/esm/cron/cron.js +82 -0
- package/build/esm/cron/cron.js.map +1 -0
- package/build/esm/cron/index.js +13 -0
- package/build/esm/cron/index.js.map +1 -0
- package/build/esm/cron/node-cron.js +66 -0
- package/build/esm/cron/node-cron.js.map +1 -0
- package/build/esm/cron/node-schedule.js +43 -0
- package/build/esm/cron/node-schedule.js.map +1 -0
- package/build/esm/index.js +6 -2
- package/build/esm/index.js.map +1 -1
- package/build/esm/integrations/anthropic.js +25 -16
- package/build/esm/integrations/anthropic.js.map +1 -1
- package/build/esm/integrations/aws-sdk/index.js +1 -0
- package/build/esm/integrations/aws-sdk/index.js.map +1 -1
- package/build/esm/integrations/aws-sdk/services/ServicesExtensions.js +3 -0
- package/build/esm/integrations/aws-sdk/services/ServicesExtensions.js.map +1 -1
- package/build/esm/integrations/aws-sdk/services/bedrock-runtime.js +45 -12
- package/build/esm/integrations/aws-sdk/services/bedrock-runtime.js.map +1 -1
- package/build/esm/integrations/bullmq/contextManager.js +45 -0
- package/build/esm/integrations/bullmq/contextManager.js.map +1 -0
- package/build/esm/integrations/bullmq/index.js +44 -0
- package/build/esm/integrations/bullmq/index.js.map +1 -0
- package/build/esm/integrations/bullmq/meter.js +86 -0
- package/build/esm/integrations/bullmq/meter.js.map +1 -0
- package/build/esm/integrations/bullmq/span.js +114 -0
- package/build/esm/integrations/bullmq/span.js.map +1 -0
- package/build/esm/integrations/bullmq/tracer.js +62 -0
- package/build/esm/integrations/bullmq/tracer.js.map +1 -0
- package/build/esm/integrations/express/instrumentation.js +10 -1
- package/build/esm/integrations/express/instrumentation.js.map +1 -1
- package/build/esm/integrations/google-genai.js +17 -9
- package/build/esm/integrations/google-genai.js.map +1 -1
- package/build/esm/integrations/langgraph.js +5 -7
- package/build/esm/integrations/langgraph.js.map +1 -1
- package/build/esm/integrations/mastra-classifier.js +1 -1
- package/build/esm/integrations/mastra-classifier.js.map +1 -1
- package/build/esm/integrations/mistral.js +13 -4
- package/build/esm/integrations/mistral.js.map +1 -1
- package/build/esm/integrations/openai-compatible.js +16 -8
- package/build/esm/integrations/openai-compatible.js.map +1 -1
- package/build/esm/integrations/openai.js +16 -8
- package/build/esm/integrations/openai.js.map +1 -1
- package/build/esm/integrations/pi-ai.js +39 -18
- package/build/esm/integrations/pi-ai.js.map +1 -1
- package/build/esm/integrations/pino.js +131 -0
- package/build/esm/integrations/pino.js.map +1 -0
- package/build/esm/integrations/typesafe.js +17 -3
- package/build/esm/integrations/typesafe.js.map +1 -1
- package/build/esm/integrations/vercel-ai/index.js.map +1 -1
- package/build/esm/integrations/vercel-ai/util.js +3 -2
- package/build/esm/integrations/vercel-ai/util.js.map +1 -1
- package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js +44 -17
- package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -1
- package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js +22 -16
- package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js.map +1 -1
- package/build/esm/integrations/winston.js +90 -0
- package/build/esm/integrations/winston.js.map +1 -0
- package/build/esm/orchestrion/detect.js +1 -1
- package/build/esm/orchestrion/detect.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/types/ai/anthropic-ai/index.d.ts +1 -5
- package/build/types/ai/anthropic-ai/index.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/streaming.d.ts +3 -2
- package/build/types/ai/anthropic-ai/streaming.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/tool-runner.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/types.d.ts +24 -3
- package/build/types/ai/anthropic-ai/types.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/utils.d.ts +2 -3
- package/build/types/ai/anthropic-ai/utils.d.ts.map +1 -1
- package/build/types/ai/core/span-hooks.d.ts +31 -0
- package/build/types/ai/core/span-hooks.d.ts.map +1 -0
- package/build/types/ai/core/time-to-first-chunk.d.ts +7 -0
- package/build/types/ai/core/time-to-first-chunk.d.ts.map +1 -0
- package/build/types/ai/core/utils.d.ts +30 -1
- package/build/types/ai/core/utils.d.ts.map +1 -1
- package/build/types/ai/flue/index.d.ts +13 -5
- package/build/types/ai/flue/index.d.ts.map +1 -1
- package/build/types/ai/flue/types.d.ts +20 -2
- package/build/types/ai/flue/types.d.ts.map +1 -1
- package/build/types/ai/flue/utils.d.ts +5 -9
- package/build/types/ai/flue/utils.d.ts.map +1 -1
- package/build/types/ai/google-genai/index.d.ts.map +1 -1
- package/build/types/ai/google-genai/streaming.d.ts +2 -1
- package/build/types/ai/google-genai/streaming.d.ts.map +1 -1
- package/build/types/ai/google-genai/types.d.ts +17 -3
- package/build/types/ai/google-genai/types.d.ts.map +1 -1
- package/build/types/ai/langchain/index.d.ts.map +1 -1
- package/build/types/ai/langchain/types.d.ts +49 -3
- package/build/types/ai/langchain/types.d.ts.map +1 -1
- package/build/types/ai/langchain/utils.d.ts +6 -0
- package/build/types/ai/langchain/utils.d.ts.map +1 -1
- package/build/types/ai/langgraph/agent-span.d.ts +4 -1
- package/build/types/ai/langgraph/agent-span.d.ts.map +1 -1
- package/build/types/ai/langgraph/index.d.ts +1 -1
- package/build/types/ai/langgraph/index.d.ts.map +1 -1
- package/build/types/ai/langgraph/stream.d.ts.map +1 -1
- package/build/types/ai/langgraph/types.d.ts +14 -3
- package/build/types/ai/langgraph/types.d.ts.map +1 -1
- package/build/types/ai/langgraph/utils.d.ts +3 -0
- package/build/types/ai/langgraph/utils.d.ts.map +1 -1
- package/build/types/ai/mastra/classifier-evaluation.d.ts +3 -3
- package/build/types/ai/mastra/classifier-evaluation.d.ts.map +1 -1
- package/build/types/ai/mastra/index.d.ts +17 -3
- package/build/types/ai/mastra/index.d.ts.map +1 -1
- package/build/types/ai/mastra/types.d.ts +2 -0
- package/build/types/ai/mastra/types.d.ts.map +1 -1
- package/build/types/ai/mastra/utils.d.ts.map +1 -1
- package/build/types/ai/mistral/index.d.ts.map +1 -1
- package/build/types/ai/mistral/streaming.d.ts +2 -1
- package/build/types/ai/mistral/streaming.d.ts.map +1 -1
- package/build/types/ai/mistral/types.d.ts +14 -3
- package/build/types/ai/mistral/types.d.ts.map +1 -1
- package/build/types/ai/openai/index.d.ts.map +1 -1
- package/build/types/ai/openai/streaming.d.ts +3 -1
- package/build/types/ai/openai/streaming.d.ts.map +1 -1
- package/build/types/ai/openai/types.d.ts +14 -3
- package/build/types/ai/openai/types.d.ts.map +1 -1
- package/build/types/ai/pi-ai/chat.d.ts +7 -1
- package/build/types/ai/pi-ai/chat.d.ts.map +1 -1
- package/build/types/ai/pi-ai/recording.d.ts +21 -9
- package/build/types/ai/pi-ai/recording.d.ts.map +1 -1
- package/build/types/ai/pi-ai/types.d.ts +16 -0
- package/build/types/ai/pi-ai/types.d.ts.map +1 -1
- package/build/types/ai/pi-durable/index.d.ts +12 -3
- package/build/types/ai/pi-durable/index.d.ts.map +1 -1
- package/build/types/ai/pi-durable/runs.d.ts +2 -0
- package/build/types/ai/pi-durable/runs.d.ts.map +1 -1
- package/build/types/ai/pi-durable/tools.d.ts +4 -3
- package/build/types/ai/pi-durable/tools.d.ts.map +1 -1
- package/build/types/ai/pi-durable/types.d.ts +15 -0
- package/build/types/ai/pi-durable/types.d.ts.map +1 -1
- package/build/types/ai/typesafe/index.d.ts +10 -2
- package/build/types/ai/typesafe/index.d.ts.map +1 -1
- package/build/types/ai/workers-ai/index.d.ts.map +1 -1
- package/build/types/ai/workers-ai/streaming.d.ts +2 -1
- package/build/types/ai/workers-ai/streaming.d.ts.map +1 -1
- package/build/types/ai/workers-ai/types.d.ts +18 -3
- package/build/types/ai/workers-ai/types.d.ts.map +1 -1
- package/build/types/cron/common.d.ts +8 -0
- package/build/types/cron/common.d.ts.map +1 -0
- package/build/types/cron/cron.d.ts +45 -0
- package/build/types/cron/cron.d.ts.map +1 -0
- package/build/types/cron/index.d.ts +10 -0
- package/build/types/cron/index.d.ts.map +1 -0
- package/build/types/cron/node-cron.d.ts +33 -0
- package/build/types/cron/node-cron.d.ts.map +1 -0
- package/build/types/cron/node-schedule.d.ts +19 -0
- package/build/types/cron/node-schedule.d.ts.map +1 -0
- package/build/types/index.d.ts +5 -2
- package/build/types/index.d.ts.map +1 -1
- package/build/types/integrations/anthropic.d.ts +2 -1
- package/build/types/integrations/anthropic.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/index.d.ts +3 -3
- package/build/types/integrations/aws-sdk/index.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/services/ServiceExtension.d.ts +1 -0
- package/build/types/integrations/aws-sdk/services/ServiceExtension.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/services/ServicesExtensions.d.ts +3 -2
- package/build/types/integrations/aws-sdk/services/ServicesExtensions.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/services/bedrock-runtime.d.ts +25 -4
- package/build/types/integrations/aws-sdk/services/bedrock-runtime.d.ts.map +1 -1
- package/build/types/integrations/bullmq/contextManager.d.ts +13 -0
- package/build/types/integrations/bullmq/contextManager.d.ts.map +1 -0
- package/build/types/integrations/bullmq/index.d.ts +43 -0
- package/build/types/integrations/bullmq/index.d.ts.map +1 -0
- package/build/types/integrations/bullmq/meter.d.ts +7 -0
- package/build/types/integrations/bullmq/meter.d.ts.map +1 -0
- package/build/types/integrations/bullmq/span.d.ts +35 -0
- package/build/types/integrations/bullmq/span.d.ts.map +1 -0
- package/build/types/integrations/bullmq/tracer.d.ts +5 -0
- package/build/types/integrations/bullmq/tracer.d.ts.map +1 -0
- package/build/types/integrations/bullmq/types.d.ts +72 -0
- package/build/types/integrations/bullmq/types.d.ts.map +1 -0
- package/build/types/integrations/express/types.d.ts +1 -0
- package/build/types/integrations/express/types.d.ts.map +1 -1
- package/build/types/integrations/flue.d.ts +2 -1
- package/build/types/integrations/flue.d.ts.map +1 -1
- package/build/types/integrations/google-genai.d.ts +2 -1
- package/build/types/integrations/google-genai.d.ts.map +1 -1
- package/build/types/integrations/groq.d.ts +1 -1
- package/build/types/integrations/langchain.d.ts +2 -1
- package/build/types/integrations/langchain.d.ts.map +1 -1
- package/build/types/integrations/langgraph.d.ts +2 -1
- package/build/types/integrations/langgraph.d.ts.map +1 -1
- package/build/types/integrations/mistral.d.ts +2 -1
- package/build/types/integrations/mistral.d.ts.map +1 -1
- package/build/types/integrations/openai-compatible.d.ts.map +1 -1
- package/build/types/integrations/openai.d.ts +2 -1
- package/build/types/integrations/openai.d.ts.map +1 -1
- package/build/types/integrations/pi-ai.d.ts +6 -3
- package/build/types/integrations/pi-ai.d.ts.map +1 -1
- package/build/types/integrations/pi-durable.d.ts +2 -1
- package/build/types/integrations/pi-durable.d.ts.map +1 -1
- package/build/types/integrations/pino.d.ts +61 -0
- package/build/types/integrations/pino.d.ts.map +1 -0
- package/build/types/integrations/together-ai.d.ts +1 -1
- package/build/types/integrations/typesafe.d.ts +2 -2
- package/build/types/integrations/typesafe.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/index.d.ts +3 -3
- package/build/types/integrations/vercel-ai/index.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/util.d.ts +2 -1
- package/build/types/integrations/vercel-ai/util.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts +20 -4
- package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.d.ts.map +1 -1
- package/build/types/integrations/winston.d.ts +55 -0
- package/build/types/integrations/winston.d.ts.map +1 -0
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"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) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bedrock-runtime.js","names":["ATTR_GEN_AI_REQUEST_STOP_SEQUENCES"],"sources":["../../../../../src/integrations/aws-sdk/services/bedrock-runtime.ts"],"sourcesContent":["import type { Span } from '@sentry/core';\nimport { debug } from '@sentry/core';\nimport {\n GEN_AI_OPERATION_NAME,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_MAX_TOKENS,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_REQUEST_STOP_SEQUENCES as ATTR_GEN_AI_REQUEST_STOP_SEQUENCES,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_REQUEST_TOP_P,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_CHAT, GEN_AI_GENERATE_CONTENT } from '@sentry/conventions/op';\nimport type { GenAiOptions, StreamResponseState } from '../../../ai/core/utils';\nimport type { GenAiMessagePart } from '../../../ai/types';\nimport {\n endStreamSpan,\n getErrorStatus,\n getTokenUsageAttributes,\n resolveAIRecordingOptions,\n} from '../../../ai/core/utils';\nimport { isInsidePiAiSpan } from '../../../ai/pi-ai/providers';\nimport { DEBUG_BUILD } from '../../../debug-build';\nimport {\n GEN_AI_OPERATION_NAME_VALUE_CHAT,\n GEN_AI_OPERATION_NAME_VALUE_GENERATE_CONTENT,\n GEN_AI_SYSTEM_VALUE_AWS_BEDROCK,\n} from '../constants';\nimport type { NormalizedRequest, NormalizedResponse } from '../types';\nimport {\n appendStreamPart,\n contentBlocksToParts,\n getClaudeInputAttributes,\n getConverseInputAttributes,\n getPromptInputAttributes,\n setOutputMessages,\n startStreamToolCall,\n} from './bedrock-runtime-content';\nimport type { RequestMetadata, ServiceExtension } from './ServiceExtension';\n\n// Simplified types inlined from @aws-sdk/client-bedrock-runtime\n// Only the fields accessed by this instrumentation are included\ninterface TokenUsage {\n inputTokens: number | undefined;\n outputTokens: number | undefined;\n totalTokens: number | undefined;\n cacheReadInputTokens?: number;\n cacheWriteInputTokens?: number;\n}\n\ninterface ConverseStreamOutput {\n messageStop?: { stopReason?: string };\n metadata?: { usage?: TokenUsage };\n [key: string]: unknown;\n}\n\n// Streamed `InvokeModel` chunks and response bodies are model-family-specific JSON (titan, nova,\n// claude, llama, cohere, mistral); the record helpers probe the shapes defensively, so `any` instead\n// of one structural type per family.\ntype ParsedChunk = any;\n\n/** The output parts are only collected when outputs are recorded. */\ntype BedrockStreamState = StreamResponseState & { parts?: GenAiMessagePart[] };\n\nconst textDecoder = new TextDecoder();\n\nexport class BedrockRuntimeServiceExtension implements ServiceExtension {\n // Requests pi-ai sends, which its own `gen_ai.chat` span already reports. They keep the plain AWS\n // client span, without the model call on it.\n private _piAiRequests: WeakSet<NormalizedRequest> = new WeakSet();\n\n public constructor(private readonly _options: GenAiOptions = {}) {}\n\n private _recordingOptions(): Required<GenAiOptions> {\n return resolveAIRecordingOptions(this._options);\n }\n\n public requestPreSpanHook(request: NormalizedRequest): RequestMetadata {\n if (isInsidePiAiSpan()) {\n this._piAiRequests.add(request);\n return {};\n }\n\n switch (request.commandName) {\n case 'Converse':\n return this._requestPreSpanHookConverse(request, false);\n case 'ConverseStream':\n return this._requestPreSpanHookConverse(request, true);\n case 'InvokeModel':\n return this._requestPreSpanHookInvokeModel(request, false);\n case 'InvokeModelWithResponseStream':\n return this._requestPreSpanHookInvokeModel(request, true);\n }\n\n return {};\n }\n\n public responseHook(response: NormalizedResponse, span: Span): void {\n if (this._piAiRequests.has(response.request)) {\n return;\n }\n\n const commandName = response.request.commandName;\n\n if (!span.isRecording()) {\n // Streaming spans are ended by the wrapped stream (the subscriber's `deferSpanEnd` suppresses\n // the helper's own `end()`). When the span isn't recording we skip wrapping, so end it here to\n // avoid leaking an open span. Non-streaming commands are ended by the helper, so leave them.\n if (commandName === 'ConverseStream' || commandName === 'InvokeModelWithResponseStream') {\n span.end();\n }\n return;\n }\n\n switch (commandName) {\n case 'Converse':\n return this._responseHookConverse(response, span);\n case 'ConverseStream':\n return this._responseHookConverseStream(response, span);\n case 'InvokeModel':\n return this._responseHookInvokeModel(response, span);\n case 'InvokeModelWithResponseStream':\n return this._responseHookInvokeModelWithResponseStream(response, span);\n }\n }\n\n private _requestPreSpanHookConverse(request: NormalizedRequest, isStream: boolean): RequestMetadata {\n let spanName = GEN_AI_OPERATION_NAME_VALUE_CHAT;\n const spanAttributes: Record<string, unknown> = {\n [GEN_AI_PROVIDER_NAME]: GEN_AI_SYSTEM_VALUE_AWS_BEDROCK,\n [GEN_AI_OPERATION_NAME]: GEN_AI_OPERATION_NAME_VALUE_CHAT,\n };\n\n const modelId = request.commandInput.modelId;\n if (modelId) {\n spanAttributes[GEN_AI_REQUEST_MODEL] = modelId;\n if (spanName) {\n spanName += ` ${modelId}`;\n }\n }\n\n const inferenceConfig = request.commandInput.inferenceConfig;\n if (inferenceConfig) {\n const { maxTokens, temperature, topP, stopSequences } = inferenceConfig;\n if (maxTokens !== undefined) {\n spanAttributes[GEN_AI_REQUEST_MAX_TOKENS] = maxTokens;\n }\n if (temperature !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TEMPERATURE] = temperature;\n }\n if (topP !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TOP_P] = topP;\n }\n if (stopSequences !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] = stopSequences;\n }\n }\n\n if (this._recordingOptions().recordInputs) {\n Object.assign(spanAttributes, getConverseInputAttributes(request.commandInput));\n }\n\n return {\n spanName,\n spanOp: GEN_AI_CHAT,\n isStream,\n spanAttributes,\n };\n }\n\n private _requestPreSpanHookInvokeModel(request: NormalizedRequest, isStream: boolean): RequestMetadata {\n let spanName = GEN_AI_OPERATION_NAME_VALUE_GENERATE_CONTENT;\n const spanAttributes: Record<string, unknown> = {\n [GEN_AI_PROVIDER_NAME]: GEN_AI_SYSTEM_VALUE_AWS_BEDROCK,\n [GEN_AI_OPERATION_NAME]: GEN_AI_OPERATION_NAME_VALUE_GENERATE_CONTENT,\n };\n\n const modelId = request.commandInput?.modelId;\n if (modelId) {\n spanAttributes[GEN_AI_REQUEST_MODEL] = modelId;\n spanName += ` ${modelId}`;\n }\n\n const requestBody = parseRequestBody(request.commandInput?.body);\n if (requestBody && typeof modelId === 'string') {\n if (modelId.includes('amazon.titan')) {\n if (requestBody.textGenerationConfig?.temperature !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TEMPERATURE] = requestBody.textGenerationConfig.temperature;\n }\n if (requestBody.textGenerationConfig?.topP !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TOP_P] = requestBody.textGenerationConfig.topP;\n }\n if (requestBody.textGenerationConfig?.maxTokenCount !== undefined) {\n spanAttributes[GEN_AI_REQUEST_MAX_TOKENS] = requestBody.textGenerationConfig.maxTokenCount;\n }\n if (requestBody.textGenerationConfig?.stopSequences !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] = requestBody.textGenerationConfig.stopSequences;\n }\n } else if (modelId.includes('amazon.nova')) {\n if (requestBody.inferenceConfig?.temperature !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TEMPERATURE] = requestBody.inferenceConfig.temperature;\n }\n if (requestBody.inferenceConfig?.top_p !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TOP_P] = requestBody.inferenceConfig.top_p;\n }\n if (requestBody.inferenceConfig?.max_new_tokens !== undefined) {\n spanAttributes[GEN_AI_REQUEST_MAX_TOKENS] = requestBody.inferenceConfig.max_new_tokens;\n }\n if (requestBody.inferenceConfig?.stopSequences !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] = requestBody.inferenceConfig.stopSequences;\n }\n } else if (modelId.includes('anthropic.claude')) {\n if (requestBody.max_tokens !== undefined) {\n spanAttributes[GEN_AI_REQUEST_MAX_TOKENS] = requestBody.max_tokens;\n }\n if (requestBody.temperature !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TEMPERATURE] = requestBody.temperature;\n }\n if (requestBody.top_p !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TOP_P] = requestBody.top_p;\n }\n if (requestBody.stop_sequences !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] = requestBody.stop_sequences;\n }\n } else if (modelId.includes('meta.llama')) {\n if (requestBody.max_gen_len !== undefined) {\n spanAttributes[GEN_AI_REQUEST_MAX_TOKENS] = requestBody.max_gen_len;\n }\n if (requestBody.temperature !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TEMPERATURE] = requestBody.temperature;\n }\n if (requestBody.top_p !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TOP_P] = requestBody.top_p;\n }\n // request for meta llama models does not contain stop_sequences field\n } else if (modelId.includes('cohere.command-r')) {\n if (requestBody.max_tokens !== undefined) {\n spanAttributes[GEN_AI_REQUEST_MAX_TOKENS] = requestBody.max_tokens;\n }\n if (requestBody.temperature !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TEMPERATURE] = requestBody.temperature;\n }\n if (requestBody.p !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TOP_P] = requestBody.p;\n }\n if (requestBody.message !== undefined) {\n // NOTE: We approximate the token count since this value is not directly available in the body.\n // According to Bedrock docs they use (total_chars / 6) to approximate token count for pricing.\n spanAttributes[GEN_AI_USAGE_INPUT_TOKENS] = Math.ceil(requestBody.message.length / 6);\n }\n if (requestBody.stop_sequences !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] = requestBody.stop_sequences;\n }\n } else if (modelId.includes('cohere.command')) {\n if (requestBody.max_tokens !== undefined) {\n spanAttributes[GEN_AI_REQUEST_MAX_TOKENS] = requestBody.max_tokens;\n }\n if (requestBody.temperature !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TEMPERATURE] = requestBody.temperature;\n }\n if (requestBody.p !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TOP_P] = requestBody.p;\n }\n if (requestBody.prompt !== undefined) {\n spanAttributes[GEN_AI_USAGE_INPUT_TOKENS] = Math.ceil(requestBody.prompt.length / 6);\n }\n if (requestBody.stop_sequences !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] = requestBody.stop_sequences;\n }\n } else if (modelId.includes('mistral')) {\n if (requestBody.prompt !== undefined) {\n spanAttributes[GEN_AI_USAGE_INPUT_TOKENS] = Math.ceil(requestBody.prompt.length / 6);\n }\n if (requestBody.max_tokens !== undefined) {\n spanAttributes[GEN_AI_REQUEST_MAX_TOKENS] = requestBody.max_tokens;\n }\n if (requestBody.temperature !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TEMPERATURE] = requestBody.temperature;\n }\n if (requestBody.top_p !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TOP_P] = requestBody.top_p;\n }\n if (requestBody.stop !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] = requestBody.stop;\n }\n }\n\n if (this._recordingOptions().recordInputs) {\n Object.assign(spanAttributes, getInvokeModelInputAttributes(modelId, requestBody));\n }\n }\n\n return {\n spanName,\n spanOp: GEN_AI_GENERATE_CONTENT,\n isStream,\n spanAttributes,\n };\n }\n\n private _responseHookConverse(response: NormalizedResponse, span: Span): void {\n const { stopReason, usage, output } = response.data;\n\n setStopReason(span, stopReason);\n if (this._recordingOptions().recordOutputs) {\n setOutputMessages(span, contentBlocksToParts(output?.message?.content));\n }\n span.setAttributes(\n getTokenUsageAttributes(\n // With prompt caching, `inputTokens` leaves out cache reads and writes, which the conventions count as input.\n typeof usage?.inputTokens === 'number'\n ? usage.inputTokens + (usage.cacheReadInputTokens ?? 0) + (usage.cacheWriteInputTokens ?? 0)\n : undefined,\n usage?.outputTokens,\n usage?.cacheWriteInputTokens,\n usage?.cacheReadInputTokens,\n ),\n );\n }\n\n private _responseHookConverseStream(response: NormalizedResponse, span: Span): void {\n if (!response.data?.stream) {\n span.end();\n return;\n }\n\n // Wrap and replace the response stream in place to process events into telemetry\n // before yielding to the user.\n response.data.stream = instrumentStream(\n response.data.stream as AsyncIterable<ConverseStreamOutput>,\n span,\n response.request.abortSignal,\n this._recordingOptions().recordOutputs,\n processConverseStreamEvent,\n );\n }\n\n private _responseHookInvokeModel(response: NormalizedResponse, span: Span): void {\n const currentModelId = response.request.commandInput?.modelId;\n if (response.data?.body) {\n const decodedResponseBody = textDecoder.decode(response.data.body);\n const responseBody = JSON.parse(decodedResponseBody);\n // Nova; Claude and Llama; Cohere Command R; Titan; Cohere Command; Mistral.\n const finishReason =\n responseBody.stopReason ??\n responseBody.stop_reason ??\n responseBody.finish_reason ??\n responseBody.results?.[0]?.completionReason ??\n responseBody.generations?.[0]?.finish_reason ??\n responseBody.outputs?.[0]?.stop_reason;\n setStopReason(span, finishReason);\n if (currentModelId.includes('amazon.titan')) {\n if (responseBody.inputTextTokenCount !== undefined) {\n span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, responseBody.inputTextTokenCount);\n }\n if (responseBody.results?.[0]?.tokenCount !== undefined) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, responseBody.results[0].tokenCount);\n }\n } else if (currentModelId.includes('amazon.nova')) {\n if (responseBody.usage !== undefined) {\n if (responseBody.usage.inputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, responseBody.usage.inputTokens);\n }\n if (responseBody.usage.outputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, responseBody.usage.outputTokens);\n }\n }\n } else if (currentModelId.includes('anthropic.claude')) {\n const usage = responseBody.usage;\n span.setAttributes(\n getTokenUsageAttributes(\n // Anthropic's `input_tokens` leaves out cache reads and writes, which the conventions count as input.\n typeof usage?.input_tokens === 'number'\n ? usage.input_tokens + (usage.cache_read_input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0)\n : undefined,\n usage?.output_tokens,\n usage?.cache_creation_input_tokens,\n usage?.cache_read_input_tokens,\n ),\n );\n } else if (currentModelId.includes('meta.llama')) {\n if (responseBody.prompt_token_count !== undefined) {\n span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, responseBody.prompt_token_count);\n }\n if (responseBody.generation_token_count !== undefined) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, responseBody.generation_token_count);\n }\n } else if (currentModelId.includes('cohere.command-r')) {\n if (responseBody.text !== undefined) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, Math.ceil(responseBody.text.length / 6));\n }\n } else if (currentModelId.includes('cohere.command')) {\n if (responseBody.generations?.[0]?.text !== undefined) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, Math.ceil(responseBody.generations[0].text.length / 6));\n }\n } else if (currentModelId.includes('mistral')) {\n if (responseBody.outputs?.[0]?.text !== undefined) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, Math.ceil(responseBody.outputs[0].text.length / 6));\n }\n }\n if (this._recordingOptions().recordOutputs) {\n setOutputMessages(span, getInvokeModelOutputParts(responseBody));\n }\n }\n }\n\n private _responseHookInvokeModelWithResponseStream(response: NormalizedResponse, span: Span): void {\n const stream = response.data?.body;\n const modelId = response.request.commandInput?.modelId;\n if (!stream) {\n span.end();\n return;\n }\n\n // Resolved once: the model family is fixed for the whole stream, and for unrecognized families\n // the chunks don't need to be parsed at all.\n const processChunk = typeof modelId === 'string' ? resolveStreamProcessor(modelId) : undefined;\n\n // Replace the original response body with our instrumented stream, deferring span.end() until the\n // entire stream is consumed. Downstream consumers still receive the full stream.\n response.data.body = instrumentStream(\n stream as AsyncIterable<{ chunk?: { bytes?: Uint8Array } }>,\n span,\n response.request.abortSignal,\n this._recordingOptions().recordOutputs,\n (item, state) => {\n if (processChunk) {\n const parsedChunk = parseChunk(item?.chunk?.bytes);\n if (parsedChunk) {\n appendStreamPart(state.parts, 0, 'text', getResponseText(parsedChunk));\n processChunk(parsedChunk, state);\n }\n }\n },\n );\n }\n}\n\nfunction getInvokeModelOutputParts(responseBody: ParsedChunk): GenAiMessagePart[] {\n // Nova and Claude return content blocks, the other families one text.\n return contentBlocksToParts(\n responseBody.output?.message?.content ?? responseBody.content ?? [{ text: getResponseText(responseBody) }],\n );\n}\n\n/** The text of a Titan, Llama, Cohere Command R, Cohere Command, or Mistral response body or stream chunk. */\nfunction getResponseText(body: ParsedChunk): unknown {\n return (\n body.outputText ??\n body.results?.[0]?.outputText ??\n body.generation ??\n body.text ??\n body.generations?.[0]?.text ??\n body.outputs?.[0]?.text\n );\n}\n\nfunction getInvokeModelInputAttributes(modelId: string, requestBody: ParsedChunk): Record<string, unknown> {\n if (modelId.includes('amazon.nova')) return getConverseInputAttributes(requestBody);\n if (modelId.includes('anthropic.claude')) return getClaudeInputAttributes(requestBody);\n // The other families send one prompt string: Titan as `inputText`, Cohere Command R as `message`.\n return getPromptInputAttributes(requestBody.inputText ?? requestBody.message ?? requestBody.prompt);\n}\n\ntype StreamProcessor = (parsedChunk: ParsedChunk, state: BedrockStreamState) => void;\n\nfunction resolveStreamProcessor(modelId: string): StreamProcessor | undefined {\n if (modelId.includes('amazon.titan')) return processTitanChunk;\n if (modelId.includes('anthropic.claude')) return processClaudeChunk;\n if (modelId.includes('amazon.nova')) return processNovaChunk;\n if (modelId.includes('meta.llama')) return processLlamaChunk;\n if (modelId.includes('cohere.command-r')) return processCohereRChunk;\n if (modelId.includes('cohere.command')) return processCohereChunk;\n if (modelId.includes('mistral')) return processMistralChunk;\n return undefined;\n}\n\n/** Collects the stream items into a state and sets the span attributes from it when the stream ends. */\nasync function* instrumentStream<T>(\n stream: AsyncIterable<T>,\n span: Span,\n abortSignal: AbortSignal | undefined,\n recordOutputs: boolean,\n processItem: (item: T, state: BedrockStreamState) => void,\n): AsyncGenerator<T> {\n const state: BedrockStreamState = {\n finishReasons: [],\n responseTexts: [],\n toolCalls: [],\n parts: recordOutputs ? [] : undefined,\n };\n try {\n for await (const item of stream) {\n processItem(item, state);\n yield item;\n }\n } catch (error) {\n span.setStatus(getErrorStatus(abortSignal));\n throw error;\n } finally {\n if (state.parts) {\n setOutputMessages(span, state.parts);\n }\n endStreamSpan(span, state, false);\n }\n}\n\nfunction processConverseStreamEvent(event: ConverseStreamOutput, state: BedrockStreamState): void {\n appendConverseStreamContent(event, state);\n pushFinishReason(state, event.messageStop?.stopReason);\n const usage = event.metadata?.usage;\n if (usage) {\n // With prompt caching, `inputTokens` leaves out cache reads and writes, which the conventions count as input.\n state.promptTokens =\n typeof usage.inputTokens === 'number'\n ? usage.inputTokens + (usage.cacheReadInputTokens ?? 0) + (usage.cacheWriteInputTokens ?? 0)\n : undefined;\n state.completionTokens = usage.outputTokens;\n state.cacheReadInputTokens = usage.cacheReadInputTokens;\n state.cacheCreationInputTokens = usage.cacheWriteInputTokens;\n }\n}\n\n/** `ConverseStream` events, and Amazon Nova `InvokeModelWithResponseStream` chunks, which share their shape. */\nfunction appendConverseStreamContent(\n { contentBlockStart, contentBlockDelta }: ParsedChunk,\n state: BedrockStreamState,\n): void {\n const toolUse = contentBlockStart?.start?.toolUse;\n if (toolUse) {\n startStreamToolCall(state.parts, contentBlockStart.contentBlockIndex, toolUse.toolUseId, toolUse.name);\n }\n const delta = contentBlockDelta?.delta;\n const index = contentBlockDelta?.contentBlockIndex;\n appendStreamPart(state.parts, index, 'text', delta?.text);\n appendStreamPart(state.parts, index, 'tool_call', delta?.toolUse?.input);\n appendStreamPart(state.parts, index, 'reasoning', delta?.reasoningContent?.text);\n}\n\nfunction setStopReason(span: Span, stopReason: string | undefined): void {\n if (stopReason !== undefined) {\n span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, JSON.stringify([stopReason]));\n }\n}\n\nfunction pushFinishReason(state: StreamResponseState, reason: unknown): void {\n if (typeof reason === 'string') {\n state.finishReasons.push(reason);\n }\n}\n\nfunction parseRequestBody(body: unknown): ParsedChunk {\n // `InvokeModel` takes the body as a JSON string or as bytes.\n const text = typeof body === 'string' ? body : body instanceof Uint8Array ? textDecoder.decode(body) : undefined;\n if (!text) {\n return undefined;\n }\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\nfunction parseChunk(bytes?: Uint8Array): ParsedChunk {\n if (!bytes || !(bytes instanceof Uint8Array)) {\n return null;\n }\n try {\n const str = Buffer.from(bytes).toString('utf-8');\n return JSON.parse(str);\n } catch (err) {\n DEBUG_BUILD && debug.warn('[instrumentation:aws-sdk] failed to parse streamed bedrock chunk', err);\n return null;\n }\n}\n\nfunction processNovaChunk(parsedChunk: ParsedChunk, state: BedrockStreamState): void {\n appendConverseStreamContent(parsedChunk, state);\n const usage = parsedChunk.metadata?.usage;\n if (typeof usage?.inputTokens === 'number') {\n state.promptTokens = usage.inputTokens;\n }\n if (typeof usage?.outputTokens === 'number') {\n state.completionTokens = usage.outputTokens;\n }\n pushFinishReason(state, parsedChunk.messageStop?.stopReason);\n}\n\n/** Claude chunks are Anthropic Messages streaming events. */\nfunction processClaudeChunk(parsedChunk: ParsedChunk, state: BedrockStreamState): void {\n const { index, content_block: block, delta } = parsedChunk;\n if (block?.type === 'tool_use') {\n startStreamToolCall(state.parts, index, block.id, block.name);\n }\n appendStreamPart(state.parts, index, 'text', delta?.text);\n appendStreamPart(state.parts, index, 'tool_call', delta?.partial_json);\n appendStreamPart(state.parts, index, 'reasoning', delta?.thinking);\n const inputUsage = parsedChunk.message?.usage;\n if (typeof inputUsage?.cache_read_input_tokens === 'number') {\n state.cacheReadInputTokens = inputUsage.cache_read_input_tokens;\n }\n if (typeof inputUsage?.cache_creation_input_tokens === 'number') {\n state.cacheCreationInputTokens = inputUsage.cache_creation_input_tokens;\n }\n if (typeof inputUsage?.input_tokens === 'number') {\n // Anthropic's `input_tokens` leaves out cache reads and writes, which the conventions count as input.\n state.promptTokens =\n inputUsage.input_tokens + (state.cacheReadInputTokens ?? 0) + (state.cacheCreationInputTokens ?? 0);\n }\n // `message_start` carries only a placeholder output count. The final count arrives in `message_delta`.\n if (typeof parsedChunk.usage?.output_tokens === 'number') {\n state.completionTokens = parsedChunk.usage.output_tokens;\n }\n pushFinishReason(state, parsedChunk.delta?.stop_reason);\n}\n\nfunction processTitanChunk(parsedChunk: ParsedChunk, state: BedrockStreamState): void {\n if (typeof parsedChunk.inputTextTokenCount === 'number') {\n state.promptTokens = parsedChunk.inputTextTokenCount;\n }\n if (typeof parsedChunk.totalOutputTextTokenCount === 'number') {\n state.completionTokens = parsedChunk.totalOutputTextTokenCount;\n }\n pushFinishReason(state, parsedChunk.completionReason);\n}\n\nfunction processLlamaChunk(parsedChunk: ParsedChunk, state: BedrockStreamState): void {\n if (typeof parsedChunk.prompt_token_count === 'number') {\n state.promptTokens = parsedChunk.prompt_token_count;\n }\n if (typeof parsedChunk.generation_token_count === 'number') {\n state.completionTokens = parsedChunk.generation_token_count;\n }\n pushFinishReason(state, parsedChunk.stop_reason);\n}\n\n/**\n * Bedrock adds the token counts to the last chunk of a stream. For models that send no counts of their own,\n * this is the only real count.\n */\nfunction processInvocationMetrics(parsedChunk: ParsedChunk, state: StreamResponseState): void {\n const metrics = parsedChunk['amazon-bedrock-invocationMetrics'];\n if (typeof metrics?.inputTokenCount === 'number') {\n state.promptTokens = metrics.inputTokenCount;\n }\n if (typeof metrics?.outputTokenCount === 'number') {\n state.completionTokens = metrics.outputTokenCount;\n }\n}\n\nfunction processMistralChunk(parsedChunk: ParsedChunk, state: BedrockStreamState): void {\n processInvocationMetrics(parsedChunk, state);\n pushFinishReason(state, parsedChunk.outputs?.[0]?.stop_reason);\n}\n\nfunction processCohereChunk(parsedChunk: ParsedChunk, state: BedrockStreamState): void {\n processInvocationMetrics(parsedChunk, state);\n pushFinishReason(state, parsedChunk.generations?.[0]?.finish_reason);\n}\n\nfunction processCohereRChunk(parsedChunk: ParsedChunk, state: BedrockStreamState): void {\n processInvocationMetrics(parsedChunk, state);\n pushFinishReason(state, parsedChunk.finish_reason);\n}\n"],"mappings":";;;;;;;;;AAkEA,MAAM,cAAc,IAAI,YAAY;AAEpC,IAAa,iCAAb,MAAwE;CAK/D,YAA6B,WAAyB,CAAC,GAAG;EAA7B,KAAA,WAAA;EAFpC,KAAQ,gCAA4C,IAAI,QAAQ;CAEE;CAE1D,oBAA4C;EAClD,OAAO,0BAA0B,KAAK,QAAQ;CAChD;CAEO,mBAAmB,SAA6C;EACrE,IAAI,iBAAiB,GAAG;GACtB,KAAK,cAAc,IAAI,OAAO;GAC9B,OAAO,CAAC;EACV;EAEA,QAAQ,QAAQ,aAAhB;GACE,KAAK,YACH,OAAO,KAAK,4BAA4B,SAAS,KAAK;GACxD,KAAK,kBACH,OAAO,KAAK,4BAA4B,SAAS,IAAI;GACvD,KAAK,eACH,OAAO,KAAK,+BAA+B,SAAS,KAAK;GAC3D,KAAK,iCACH,OAAO,KAAK,+BAA+B,SAAS,IAAI;EAC5D;EAEA,OAAO,CAAC;CACV;CAEO,aAAa,UAA8B,MAAkB;EAClE,IAAI,KAAK,cAAc,IAAI,SAAS,OAAO,GACzC;EAGF,MAAM,cAAc,SAAS,QAAQ;EAErC,IAAI,CAAC,KAAK,YAAY,GAAG;GAIvB,IAAI,gBAAgB,oBAAoB,gBAAgB,iCACtD,KAAK,IAAI;GAEX;EACF;EAEA,QAAQ,aAAR;GACE,KAAK,YACH,OAAO,KAAK,sBAAsB,UAAU,IAAI;GAClD,KAAK,kBACH,OAAO,KAAK,4BAA4B,UAAU,IAAI;GACxD,KAAK,eACH,OAAO,KAAK,yBAAyB,UAAU,IAAI;GACrD,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CAGrG,IAAI,OAAO,YAAY,OAAO,kBAAkB,UAC9C,MAAM,mBAAmB,YAAY,MAAM;CAE7C,iBAAiB,OAAO,YAAY,OAAO,WAAW;AACxD;AAEA,SAAS,kBAAkB,aAA0B,OAAiC;CACpF,IAAI,OAAO,YAAY,wBAAwB,UAC7C,MAAM,eAAe,YAAY;CAEnC,IAAI,OAAO,YAAY,8BAA8B,UACnD,MAAM,mBAAmB,YAAY;CAEvC,iBAAiB,OAAO,YAAY,gBAAgB;AACtD;AAEA,SAAS,kBAAkB,aAA0B,OAAiC;CACpF,IAAI,OAAO,YAAY,uBAAuB,UAC5C,MAAM,eAAe,YAAY;CAEnC,IAAI,OAAO,YAAY,2BAA2B,UAChD,MAAM,mBAAmB,YAAY;CAEvC,iBAAiB,OAAO,YAAY,WAAW;AACjD;;;;;AAMA,SAAS,yBAAyB,aAA0B,OAAkC;CAC5F,MAAM,UAAU,YAAY;CAC5B,IAAI,OAAO,SAAS,oBAAoB,UACtC,MAAM,eAAe,QAAQ;CAE/B,IAAI,OAAO,SAAS,qBAAqB,UACvC,MAAM,mBAAmB,QAAQ;AAErC;AAEA,SAAS,oBAAoB,aAA0B,OAAiC;CACtF,yBAAyB,aAAa,KAAK;CAC3C,iBAAiB,OAAO,YAAY,UAAU,EAAE,EAAE,WAAW;AAC/D;AAEA,SAAS,mBAAmB,aAA0B,OAAiC;CACrF,yBAAyB,aAAa,KAAK;CAC3C,iBAAiB,OAAO,YAAY,cAAc,EAAE,EAAE,aAAa;AACrE;AAEA,SAAS,oBAAoB,aAA0B,OAAiC;CACtF,yBAAyB,aAAa,KAAK;CAC3C,iBAAiB,OAAO,YAAY,aAAa;AACnD"}
|
|
1
|
+
{"version":3,"file":"bedrock-runtime.js","names":["ATTR_GEN_AI_REQUEST_STOP_SEQUENCES"],"sources":["../../../../../src/integrations/aws-sdk/services/bedrock-runtime.ts"],"sourcesContent":["import type { Span } from '@sentry/core';\nimport { debug } from '@sentry/core';\nimport {\n GEN_AI_OPERATION_NAME,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_MAX_TOKENS,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_REQUEST_STOP_SEQUENCES as ATTR_GEN_AI_REQUEST_STOP_SEQUENCES,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_REQUEST_TOP_P,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_CHAT, GEN_AI_GENERATE_CONTENT } from '@sentry/conventions/op';\nimport type { GenAiSpanHooks, GenAiSpanResult } from '../../../ai/core/span-hooks';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../../../ai/core/span-hooks';\nimport type { GenAiCallOptions, StreamResponseState } from '../../../ai/core/utils';\nimport type { GenAiMessagePart } from '../../../ai/types';\nimport {\n endStreamSpan,\n getErrorStatus,\n getTokenUsageAttributes,\n resolveGenAiCallRecording,\n} from '../../../ai/core/utils';\nimport { isInsidePiAiSpan } from '../../../ai/pi-ai/providers';\nimport { DEBUG_BUILD } from '../../../debug-build';\nimport {\n GEN_AI_OPERATION_NAME_VALUE_CHAT,\n GEN_AI_OPERATION_NAME_VALUE_GENERATE_CONTENT,\n GEN_AI_SYSTEM_VALUE_AWS_BEDROCK,\n} from '../constants';\nimport type { CommandInput, NormalizedRequest, NormalizedResponse } from '../types';\nimport {\n appendStreamPart,\n contentBlocksToParts,\n getClaudeInputAttributes,\n getConverseInputAttributes,\n getPromptInputAttributes,\n setOutputMessages,\n startStreamToolCall,\n} from './bedrock-runtime-content';\nimport type { RequestMetadata, ServiceExtension } from './ServiceExtension';\n\n// Simplified types inlined from @aws-sdk/client-bedrock-runtime\n// Only the fields accessed by this instrumentation are included\ninterface TokenUsage {\n inputTokens: number | undefined;\n outputTokens: number | undefined;\n totalTokens: number | undefined;\n cacheReadInputTokens?: number;\n cacheWriteInputTokens?: number;\n}\n\ninterface ConverseStreamOutput {\n messageStop?: { stopReason?: string };\n metadata?: { usage?: TokenUsage };\n [key: string]: unknown;\n}\n\n// Streamed `InvokeModel` chunks and response bodies are model-family-specific JSON (titan, nova,\n// claude, llama, cohere, mistral); the record helpers probe the shapes defensively, so `any` instead\n// of one structural type per family.\ntype ParsedChunk = any;\n\n/** The output parts are only collected when outputs are recorded. */\ntype BedrockStreamState = StreamResponseState & { parts?: GenAiMessagePart[] };\n\nconst textDecoder = new TextDecoder();\n\n/**\n * The call that `recordInputs`/`recordOutputs` decide on, and that the span hooks get: a Bedrock Runtime\n * command as sent.\n */\nexport interface BedrockRuntimeCallInfo {\n /** The command name, such as `Converse` or `InvokeModelWithResponseStream`. */\n commandName: string;\n /** The command input as passed. */\n input: CommandInput;\n}\n\n/**\n * Options for the Bedrock Runtime instrumentation of the AWS integration. `onSpanEnd` gets the command\n * output; for `ConverseStream` and `InvokeModelWithResponseStream` it is `undefined`.\n */\nexport type BedrockRuntimeOptions = GenAiCallOptions<BedrockRuntimeCallInfo> & GenAiSpanHooks<BedrockRuntimeCallInfo>;\n\ninterface BedrockRuntimeCall {\n info: BedrockRuntimeCallInfo;\n recordOutputs: boolean;\n}\n\nexport class BedrockRuntimeServiceExtension implements ServiceExtension {\n // Requests pi-ai sends, which its own `gen_ai.chat` span already reports. They keep the plain AWS\n // client span, without the model call on it.\n private _piAiRequests: WeakSet<NormalizedRequest> = new WeakSet();\n\n // Decided when the request starts, in the caller's async context, and reused by the response hooks.\n private _calls: WeakMap<NormalizedRequest, BedrockRuntimeCall> = new WeakMap();\n\n public constructor(private readonly _options: BedrockRuntimeOptions = {}) {}\n\n private _resolveRecording(request: NormalizedRequest): boolean {\n const info: BedrockRuntimeCallInfo = { commandName: request.commandName, input: request.commandInput };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(this._options, info);\n this._calls.set(request, { info, recordOutputs });\n return recordInputs;\n }\n\n private _shouldRecordOutputs(response: NormalizedResponse): boolean {\n return this._calls.get(response.request)?.recordOutputs ?? false;\n }\n\n private _runSpanEnd(request: NormalizedRequest, span: Span, result: GenAiSpanResult<unknown>): void {\n const call = this._calls.get(request);\n if (call) {\n runGenAiSpanEnd(this._options, span, call.info, result);\n }\n }\n\n public requestPostSpanHook(request: NormalizedRequest, span: Span): void {\n const call = this._calls.get(request);\n if (call) {\n runGenAiSpanStart(this._options, span, call.info);\n }\n }\n\n public errorHook(request: NormalizedRequest, error: unknown, span: Span): void {\n this._runSpanEnd(request, span, { error });\n }\n\n public requestPreSpanHook(request: NormalizedRequest): RequestMetadata {\n if (isInsidePiAiSpan()) {\n this._piAiRequests.add(request);\n return {};\n }\n\n switch (request.commandName) {\n case 'Converse':\n return this._requestPreSpanHookConverse(request, false);\n case 'ConverseStream':\n return this._requestPreSpanHookConverse(request, true);\n case 'InvokeModel':\n return this._requestPreSpanHookInvokeModel(request, false);\n case 'InvokeModelWithResponseStream':\n return this._requestPreSpanHookInvokeModel(request, true);\n }\n\n return {};\n }\n\n public responseHook(response: NormalizedResponse, span: Span): void {\n if (this._piAiRequests.has(response.request)) {\n return;\n }\n\n const commandName = response.request.commandName;\n\n if (!span.isRecording()) {\n // Streaming spans are ended by the wrapped stream (the subscriber's `deferSpanEnd` suppresses\n // the helper's own `end()`). When the span isn't recording we skip wrapping, so end it here to\n // avoid leaking an open span. Non-streaming commands are ended by the helper, so leave them.\n if (commandName === 'ConverseStream' || commandName === 'InvokeModelWithResponseStream') {\n span.end();\n }\n return;\n }\n\n switch (commandName) {\n case 'Converse':\n return this._responseHookConverse(response, span);\n case 'ConverseStream':\n return this._responseHookConverseStream(response, span);\n case 'InvokeModel':\n return this._responseHookInvokeModel(response, span);\n case 'InvokeModelWithResponseStream':\n return this._responseHookInvokeModelWithResponseStream(response, span);\n }\n }\n\n private _requestPreSpanHookConverse(request: NormalizedRequest, isStream: boolean): RequestMetadata {\n let spanName = GEN_AI_OPERATION_NAME_VALUE_CHAT;\n const spanAttributes: Record<string, unknown> = {\n [GEN_AI_PROVIDER_NAME]: GEN_AI_SYSTEM_VALUE_AWS_BEDROCK,\n [GEN_AI_OPERATION_NAME]: GEN_AI_OPERATION_NAME_VALUE_CHAT,\n };\n\n const recordInputs = this._resolveRecording(request);\n\n const modelId = request.commandInput.modelId;\n if (modelId) {\n spanAttributes[GEN_AI_REQUEST_MODEL] = modelId;\n if (spanName) {\n spanName += ` ${modelId}`;\n }\n }\n\n const inferenceConfig = request.commandInput.inferenceConfig;\n if (inferenceConfig) {\n const { maxTokens, temperature, topP, stopSequences } = inferenceConfig;\n if (maxTokens !== undefined) {\n spanAttributes[GEN_AI_REQUEST_MAX_TOKENS] = maxTokens;\n }\n if (temperature !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TEMPERATURE] = temperature;\n }\n if (topP !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TOP_P] = topP;\n }\n if (stopSequences !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] = stopSequences;\n }\n }\n\n if (recordInputs) {\n Object.assign(spanAttributes, getConverseInputAttributes(request.commandInput));\n }\n\n return {\n spanName,\n spanOp: GEN_AI_CHAT,\n isStream,\n spanAttributes,\n };\n }\n\n private _requestPreSpanHookInvokeModel(request: NormalizedRequest, isStream: boolean): RequestMetadata {\n let spanName = GEN_AI_OPERATION_NAME_VALUE_GENERATE_CONTENT;\n const spanAttributes: Record<string, unknown> = {\n [GEN_AI_PROVIDER_NAME]: GEN_AI_SYSTEM_VALUE_AWS_BEDROCK,\n [GEN_AI_OPERATION_NAME]: GEN_AI_OPERATION_NAME_VALUE_GENERATE_CONTENT,\n };\n\n const recordInputs = this._resolveRecording(request);\n const modelId = request.commandInput?.modelId;\n if (modelId) {\n spanAttributes[GEN_AI_REQUEST_MODEL] = modelId;\n spanName += ` ${modelId}`;\n }\n\n const requestBody = parseRequestBody(request.commandInput?.body);\n if (requestBody && typeof modelId === 'string') {\n if (modelId.includes('amazon.titan')) {\n if (requestBody.textGenerationConfig?.temperature !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TEMPERATURE] = requestBody.textGenerationConfig.temperature;\n }\n if (requestBody.textGenerationConfig?.topP !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TOP_P] = requestBody.textGenerationConfig.topP;\n }\n if (requestBody.textGenerationConfig?.maxTokenCount !== undefined) {\n spanAttributes[GEN_AI_REQUEST_MAX_TOKENS] = requestBody.textGenerationConfig.maxTokenCount;\n }\n if (requestBody.textGenerationConfig?.stopSequences !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] = requestBody.textGenerationConfig.stopSequences;\n }\n } else if (modelId.includes('amazon.nova')) {\n if (requestBody.inferenceConfig?.temperature !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TEMPERATURE] = requestBody.inferenceConfig.temperature;\n }\n if (requestBody.inferenceConfig?.top_p !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TOP_P] = requestBody.inferenceConfig.top_p;\n }\n if (requestBody.inferenceConfig?.max_new_tokens !== undefined) {\n spanAttributes[GEN_AI_REQUEST_MAX_TOKENS] = requestBody.inferenceConfig.max_new_tokens;\n }\n if (requestBody.inferenceConfig?.stopSequences !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] = requestBody.inferenceConfig.stopSequences;\n }\n } else if (modelId.includes('anthropic.claude')) {\n if (requestBody.max_tokens !== undefined) {\n spanAttributes[GEN_AI_REQUEST_MAX_TOKENS] = requestBody.max_tokens;\n }\n if (requestBody.temperature !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TEMPERATURE] = requestBody.temperature;\n }\n if (requestBody.top_p !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TOP_P] = requestBody.top_p;\n }\n if (requestBody.stop_sequences !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] = requestBody.stop_sequences;\n }\n } else if (modelId.includes('meta.llama')) {\n if (requestBody.max_gen_len !== undefined) {\n spanAttributes[GEN_AI_REQUEST_MAX_TOKENS] = requestBody.max_gen_len;\n }\n if (requestBody.temperature !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TEMPERATURE] = requestBody.temperature;\n }\n if (requestBody.top_p !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TOP_P] = requestBody.top_p;\n }\n // request for meta llama models does not contain stop_sequences field\n } else if (modelId.includes('cohere.command-r')) {\n if (requestBody.max_tokens !== undefined) {\n spanAttributes[GEN_AI_REQUEST_MAX_TOKENS] = requestBody.max_tokens;\n }\n if (requestBody.temperature !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TEMPERATURE] = requestBody.temperature;\n }\n if (requestBody.p !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TOP_P] = requestBody.p;\n }\n if (requestBody.message !== undefined) {\n // NOTE: We approximate the token count since this value is not directly available in the body.\n // According to Bedrock docs they use (total_chars / 6) to approximate token count for pricing.\n spanAttributes[GEN_AI_USAGE_INPUT_TOKENS] = Math.ceil(requestBody.message.length / 6);\n }\n if (requestBody.stop_sequences !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] = requestBody.stop_sequences;\n }\n } else if (modelId.includes('cohere.command')) {\n if (requestBody.max_tokens !== undefined) {\n spanAttributes[GEN_AI_REQUEST_MAX_TOKENS] = requestBody.max_tokens;\n }\n if (requestBody.temperature !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TEMPERATURE] = requestBody.temperature;\n }\n if (requestBody.p !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TOP_P] = requestBody.p;\n }\n if (requestBody.prompt !== undefined) {\n spanAttributes[GEN_AI_USAGE_INPUT_TOKENS] = Math.ceil(requestBody.prompt.length / 6);\n }\n if (requestBody.stop_sequences !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] = requestBody.stop_sequences;\n }\n } else if (modelId.includes('mistral')) {\n if (requestBody.prompt !== undefined) {\n spanAttributes[GEN_AI_USAGE_INPUT_TOKENS] = Math.ceil(requestBody.prompt.length / 6);\n }\n if (requestBody.max_tokens !== undefined) {\n spanAttributes[GEN_AI_REQUEST_MAX_TOKENS] = requestBody.max_tokens;\n }\n if (requestBody.temperature !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TEMPERATURE] = requestBody.temperature;\n }\n if (requestBody.top_p !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TOP_P] = requestBody.top_p;\n }\n if (requestBody.stop !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] = requestBody.stop;\n }\n }\n\n if (recordInputs) {\n Object.assign(spanAttributes, getInvokeModelInputAttributes(modelId, requestBody));\n }\n }\n\n return {\n spanName,\n spanOp: GEN_AI_GENERATE_CONTENT,\n isStream,\n spanAttributes,\n };\n }\n\n private _responseHookConverse(response: NormalizedResponse, span: Span): void {\n const { stopReason, usage, output } = response.data;\n\n setStopReason(span, stopReason);\n if (this._shouldRecordOutputs(response)) {\n setOutputMessages(span, contentBlocksToParts(output?.message?.content));\n }\n span.setAttributes(\n getTokenUsageAttributes(\n // With prompt caching, `inputTokens` leaves out cache reads and writes, which the conventions count as input.\n typeof usage?.inputTokens === 'number'\n ? usage.inputTokens + (usage.cacheReadInputTokens ?? 0) + (usage.cacheWriteInputTokens ?? 0)\n : undefined,\n usage?.outputTokens,\n usage?.cacheWriteInputTokens,\n usage?.cacheReadInputTokens,\n ),\n );\n this._runSpanEnd(response.request, span, { response: response.data });\n }\n\n private _responseHookConverseStream(response: NormalizedResponse, span: Span): void {\n if (!response.data?.stream) {\n this._runSpanEnd(response.request, span, { response: response.data });\n span.end();\n return;\n }\n\n // Wrap and replace the response stream in place to process events into telemetry\n // before yielding to the user.\n response.data.stream = instrumentStream(\n response.data.stream as AsyncIterable<ConverseStreamOutput>,\n span,\n response.request.abortSignal,\n this._shouldRecordOutputs(response),\n processConverseStreamEvent,\n result => this._runSpanEnd(response.request, span, result),\n );\n }\n\n private _responseHookInvokeModel(response: NormalizedResponse, span: Span): void {\n const currentModelId = response.request.commandInput?.modelId;\n if (response.data?.body) {\n const decodedResponseBody = textDecoder.decode(response.data.body);\n const responseBody = JSON.parse(decodedResponseBody);\n // Nova; Claude and Llama; Cohere Command R; Titan; Cohere Command; Mistral.\n const finishReason =\n responseBody.stopReason ??\n responseBody.stop_reason ??\n responseBody.finish_reason ??\n responseBody.results?.[0]?.completionReason ??\n responseBody.generations?.[0]?.finish_reason ??\n responseBody.outputs?.[0]?.stop_reason;\n setStopReason(span, finishReason);\n if (currentModelId.includes('amazon.titan')) {\n if (responseBody.inputTextTokenCount !== undefined) {\n span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, responseBody.inputTextTokenCount);\n }\n if (responseBody.results?.[0]?.tokenCount !== undefined) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, responseBody.results[0].tokenCount);\n }\n } else if (currentModelId.includes('amazon.nova')) {\n if (responseBody.usage !== undefined) {\n if (responseBody.usage.inputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, responseBody.usage.inputTokens);\n }\n if (responseBody.usage.outputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, responseBody.usage.outputTokens);\n }\n }\n } else if (currentModelId.includes('anthropic.claude')) {\n const usage = responseBody.usage;\n span.setAttributes(\n getTokenUsageAttributes(\n // Anthropic's `input_tokens` leaves out cache reads and writes, which the conventions count as input.\n typeof usage?.input_tokens === 'number'\n ? usage.input_tokens + (usage.cache_read_input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0)\n : undefined,\n usage?.output_tokens,\n usage?.cache_creation_input_tokens,\n usage?.cache_read_input_tokens,\n ),\n );\n } else if (currentModelId.includes('meta.llama')) {\n if (responseBody.prompt_token_count !== undefined) {\n span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, responseBody.prompt_token_count);\n }\n if (responseBody.generation_token_count !== undefined) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, responseBody.generation_token_count);\n }\n } else if (currentModelId.includes('cohere.command-r')) {\n if (responseBody.text !== undefined) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, Math.ceil(responseBody.text.length / 6));\n }\n } else if (currentModelId.includes('cohere.command')) {\n if (responseBody.generations?.[0]?.text !== undefined) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, Math.ceil(responseBody.generations[0].text.length / 6));\n }\n } else if (currentModelId.includes('mistral')) {\n if (responseBody.outputs?.[0]?.text !== undefined) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, Math.ceil(responseBody.outputs[0].text.length / 6));\n }\n }\n if (this._shouldRecordOutputs(response)) {\n setOutputMessages(span, getInvokeModelOutputParts(responseBody));\n }\n }\n this._runSpanEnd(response.request, span, { response: response.data });\n }\n\n private _responseHookInvokeModelWithResponseStream(response: NormalizedResponse, span: Span): void {\n const stream = response.data?.body;\n const modelId = response.request.commandInput?.modelId;\n if (!stream) {\n this._runSpanEnd(response.request, span, { response: response.data });\n span.end();\n return;\n }\n\n // Resolved once: the model family is fixed for the whole stream, and for unrecognized families\n // the chunks don't need to be parsed at all.\n const processChunk = typeof modelId === 'string' ? resolveStreamProcessor(modelId) : undefined;\n\n // Replace the original response body with our instrumented stream, deferring span.end() until the\n // entire stream is consumed. Downstream consumers still receive the full stream.\n response.data.body = instrumentStream(\n stream as AsyncIterable<{ chunk?: { bytes?: Uint8Array } }>,\n span,\n response.request.abortSignal,\n this._shouldRecordOutputs(response),\n (item, state) => {\n if (processChunk) {\n const parsedChunk = parseChunk(item?.chunk?.bytes);\n if (parsedChunk) {\n appendStreamPart(state.parts, 0, 'text', getResponseText(parsedChunk));\n processChunk(parsedChunk, state);\n }\n }\n },\n result => this._runSpanEnd(response.request, span, result),\n );\n }\n}\n\nfunction getInvokeModelOutputParts(responseBody: ParsedChunk): GenAiMessagePart[] {\n // Nova and Claude return content blocks, the other families one text.\n return contentBlocksToParts(\n responseBody.output?.message?.content ?? responseBody.content ?? [{ text: getResponseText(responseBody) }],\n );\n}\n\n/** The text of a Titan, Llama, Cohere Command R, Cohere Command, or Mistral response body or stream chunk. */\nfunction getResponseText(body: ParsedChunk): unknown {\n return (\n body.outputText ??\n body.results?.[0]?.outputText ??\n body.generation ??\n body.text ??\n body.generations?.[0]?.text ??\n body.outputs?.[0]?.text\n );\n}\n\nfunction getInvokeModelInputAttributes(modelId: string, requestBody: ParsedChunk): Record<string, unknown> {\n if (modelId.includes('amazon.nova')) return getConverseInputAttributes(requestBody);\n if (modelId.includes('anthropic.claude')) return getClaudeInputAttributes(requestBody);\n // The other families send one prompt string: Titan as `inputText`, Cohere Command R as `message`.\n return getPromptInputAttributes(requestBody.inputText ?? requestBody.message ?? requestBody.prompt);\n}\n\ntype StreamProcessor = (parsedChunk: ParsedChunk, state: BedrockStreamState) => void;\n\nfunction resolveStreamProcessor(modelId: string): StreamProcessor | undefined {\n if (modelId.includes('amazon.titan')) return processTitanChunk;\n if (modelId.includes('anthropic.claude')) return processClaudeChunk;\n if (modelId.includes('amazon.nova')) return processNovaChunk;\n if (modelId.includes('meta.llama')) return processLlamaChunk;\n if (modelId.includes('cohere.command-r')) return processCohereRChunk;\n if (modelId.includes('cohere.command')) return processCohereChunk;\n if (modelId.includes('mistral')) return processMistralChunk;\n return undefined;\n}\n\n/** Collects the stream items into a state and sets the span attributes from it when the stream ends. */\nasync function* instrumentStream<T>(\n stream: AsyncIterable<T>,\n span: Span,\n abortSignal: AbortSignal | undefined,\n recordOutputs: boolean,\n processItem: (item: T, state: BedrockStreamState) => void,\n beforeSpanEnd: (result: GenAiSpanResult<never>) => void,\n): AsyncGenerator<T> {\n const state: BedrockStreamState = {\n finishReasons: [],\n responseTexts: [],\n toolCalls: [],\n parts: recordOutputs ? [] : undefined,\n };\n const result: GenAiSpanResult<never> = {};\n try {\n for await (const item of stream) {\n processItem(item, state);\n yield item;\n }\n } catch (error) {\n span.setStatus(getErrorStatus(abortSignal));\n result.error = error;\n throw error;\n } finally {\n if (state.parts) {\n setOutputMessages(span, state.parts);\n }\n endStreamSpan(span, state, false, () => beforeSpanEnd(result));\n }\n}\n\nfunction processConverseStreamEvent(event: ConverseStreamOutput, state: BedrockStreamState): void {\n appendConverseStreamContent(event, state);\n pushFinishReason(state, event.messageStop?.stopReason);\n const usage = event.metadata?.usage;\n if (usage) {\n // With prompt caching, `inputTokens` leaves out cache reads and writes, which the conventions count as input.\n state.promptTokens =\n typeof usage.inputTokens === 'number'\n ? usage.inputTokens + (usage.cacheReadInputTokens ?? 0) + (usage.cacheWriteInputTokens ?? 0)\n : undefined;\n state.completionTokens = usage.outputTokens;\n state.cacheReadInputTokens = usage.cacheReadInputTokens;\n state.cacheCreationInputTokens = usage.cacheWriteInputTokens;\n }\n}\n\n/** `ConverseStream` events, and Amazon Nova `InvokeModelWithResponseStream` chunks, which share their shape. */\nfunction appendConverseStreamContent(\n { contentBlockStart, contentBlockDelta }: ParsedChunk,\n state: BedrockStreamState,\n): void {\n const toolUse = contentBlockStart?.start?.toolUse;\n if (toolUse) {\n startStreamToolCall(state.parts, contentBlockStart.contentBlockIndex, toolUse.toolUseId, toolUse.name);\n }\n const delta = contentBlockDelta?.delta;\n const index = contentBlockDelta?.contentBlockIndex;\n appendStreamPart(state.parts, index, 'text', delta?.text);\n appendStreamPart(state.parts, index, 'tool_call', delta?.toolUse?.input);\n appendStreamPart(state.parts, index, 'reasoning', delta?.reasoningContent?.text);\n}\n\nfunction setStopReason(span: Span, stopReason: string | undefined): void {\n if (stopReason !== undefined) {\n span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, JSON.stringify([stopReason]));\n }\n}\n\nfunction pushFinishReason(state: StreamResponseState, reason: unknown): void {\n if (typeof reason === 'string') {\n state.finishReasons.push(reason);\n }\n}\n\nfunction parseRequestBody(body: unknown): ParsedChunk {\n // `InvokeModel` takes the body as a JSON string or as bytes.\n const text = typeof body === 'string' ? body : body instanceof Uint8Array ? textDecoder.decode(body) : undefined;\n if (!text) {\n return undefined;\n }\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\nfunction parseChunk(bytes?: Uint8Array): ParsedChunk {\n if (!bytes || !(bytes instanceof Uint8Array)) {\n return null;\n }\n try {\n const str = Buffer.from(bytes).toString('utf-8');\n return JSON.parse(str);\n } catch (err) {\n DEBUG_BUILD && debug.warn('[instrumentation:aws-sdk] failed to parse streamed bedrock chunk', err);\n return null;\n }\n}\n\nfunction processNovaChunk(parsedChunk: ParsedChunk, state: BedrockStreamState): void {\n appendConverseStreamContent(parsedChunk, state);\n const usage = parsedChunk.metadata?.usage;\n if (typeof usage?.inputTokens === 'number') {\n state.promptTokens = usage.inputTokens;\n }\n if (typeof usage?.outputTokens === 'number') {\n state.completionTokens = usage.outputTokens;\n }\n pushFinishReason(state, parsedChunk.messageStop?.stopReason);\n}\n\n/** Claude chunks are Anthropic Messages streaming events. */\nfunction processClaudeChunk(parsedChunk: ParsedChunk, state: BedrockStreamState): void {\n const { index, content_block: block, delta } = parsedChunk;\n if (block?.type === 'tool_use') {\n startStreamToolCall(state.parts, index, block.id, block.name);\n }\n appendStreamPart(state.parts, index, 'text', delta?.text);\n appendStreamPart(state.parts, index, 'tool_call', delta?.partial_json);\n appendStreamPart(state.parts, index, 'reasoning', delta?.thinking);\n const inputUsage = parsedChunk.message?.usage;\n if (typeof inputUsage?.cache_read_input_tokens === 'number') {\n state.cacheReadInputTokens = inputUsage.cache_read_input_tokens;\n }\n if (typeof inputUsage?.cache_creation_input_tokens === 'number') {\n state.cacheCreationInputTokens = inputUsage.cache_creation_input_tokens;\n }\n if (typeof inputUsage?.input_tokens === 'number') {\n // Anthropic's `input_tokens` leaves out cache reads and writes, which the conventions count as input.\n state.promptTokens =\n inputUsage.input_tokens + (state.cacheReadInputTokens ?? 0) + (state.cacheCreationInputTokens ?? 0);\n }\n // `message_start` carries only a placeholder output count. The final count arrives in `message_delta`.\n if (typeof parsedChunk.usage?.output_tokens === 'number') {\n state.completionTokens = parsedChunk.usage.output_tokens;\n }\n pushFinishReason(state, parsedChunk.delta?.stop_reason);\n}\n\nfunction processTitanChunk(parsedChunk: ParsedChunk, state: BedrockStreamState): void {\n if (typeof parsedChunk.inputTextTokenCount === 'number') {\n state.promptTokens = parsedChunk.inputTextTokenCount;\n }\n if (typeof parsedChunk.totalOutputTextTokenCount === 'number') {\n state.completionTokens = parsedChunk.totalOutputTextTokenCount;\n }\n pushFinishReason(state, parsedChunk.completionReason);\n}\n\nfunction processLlamaChunk(parsedChunk: ParsedChunk, state: BedrockStreamState): void {\n if (typeof parsedChunk.prompt_token_count === 'number') {\n state.promptTokens = parsedChunk.prompt_token_count;\n }\n if (typeof parsedChunk.generation_token_count === 'number') {\n state.completionTokens = parsedChunk.generation_token_count;\n }\n pushFinishReason(state, parsedChunk.stop_reason);\n}\n\n/**\n * Bedrock adds the token counts to the last chunk of a stream. For models that send no counts of their own,\n * this is the only real count.\n */\nfunction processInvocationMetrics(parsedChunk: ParsedChunk, state: StreamResponseState): void {\n const metrics = parsedChunk['amazon-bedrock-invocationMetrics'];\n if (typeof metrics?.inputTokenCount === 'number') {\n state.promptTokens = metrics.inputTokenCount;\n }\n if (typeof metrics?.outputTokenCount === 'number') {\n state.completionTokens = metrics.outputTokenCount;\n }\n}\n\nfunction processMistralChunk(parsedChunk: ParsedChunk, state: BedrockStreamState): void {\n processInvocationMetrics(parsedChunk, state);\n pushFinishReason(state, parsedChunk.outputs?.[0]?.stop_reason);\n}\n\nfunction processCohereChunk(parsedChunk: ParsedChunk, state: BedrockStreamState): void {\n processInvocationMetrics(parsedChunk, state);\n pushFinishReason(state, parsedChunk.generations?.[0]?.finish_reason);\n}\n\nfunction processCohereRChunk(parsedChunk: ParsedChunk, state: BedrockStreamState): void {\n processInvocationMetrics(parsedChunk, state);\n pushFinishReason(state, parsedChunk.finish_reason);\n}\n"],"mappings":";;;;;;;;;;AAoEA,MAAM,cAAc,IAAI,YAAY;AAwBpC,IAAa,iCAAb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iBAAiB,OAAO,YAAY,WAAW;AACjD;;;;;AAMA,SAAS,yBAAyB,aAA0B,OAAkC;CAC5F,MAAM,UAAU,YAAY;CAC5B,IAAI,OAAO,SAAS,oBAAoB,UACtC,MAAM,eAAe,QAAQ;CAE/B,IAAI,OAAO,SAAS,qBAAqB,UACvC,MAAM,mBAAmB,QAAQ;AAErC;AAEA,SAAS,oBAAoB,aAA0B,OAAiC;CACtF,yBAAyB,aAAa,KAAK;CAC3C,iBAAiB,OAAO,YAAY,UAAU,EAAE,EAAE,WAAW;AAC/D;AAEA,SAAS,mBAAmB,aAA0B,OAAiC;CACrF,yBAAyB,aAAa,KAAK;CAC3C,iBAAiB,OAAO,YAAY,cAAc,EAAE,EAAE,aAAa;AACrE;AAEA,SAAS,oBAAoB,aAA0B,OAAiC;CACtF,yBAAyB,aAAa,KAAK;CAC3C,iBAAiB,OAAO,YAAY,aAAa;AACnD"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { extractTraceparentData, getActiveSpan, getCurrentScope, spanToTraceHeader, withActiveSpan, withIsolationScope } from "@sentry/core";
|
|
2
|
+
// src/integrations/bullmq/contextManager.ts
|
|
3
|
+
var SentryBullMQContextManager = class {
|
|
4
|
+
active() {
|
|
5
|
+
return {
|
|
6
|
+
span: getActiveSpan(),
|
|
7
|
+
scope: getCurrentScope()
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
with(context, fn) {
|
|
11
|
+
if (context.span) return withIsolationScope(() => {
|
|
12
|
+
return withActiveSpan(context.span, fn);
|
|
13
|
+
});
|
|
14
|
+
return withIsolationScope(() => withActiveSpan(null, fn));
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Returns a context without a span. BullMQ 6.3.11+ runs the stalled jobs checker in it, so the
|
|
18
|
+
* checker does not stay attached to the span that was active when the worker started.
|
|
19
|
+
*/
|
|
20
|
+
root() {
|
|
21
|
+
return {
|
|
22
|
+
span: void 0,
|
|
23
|
+
scope: getCurrentScope()
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
getMetadata(context) {
|
|
27
|
+
if (context.span) return spanToTraceHeader(context.span);
|
|
28
|
+
return "";
|
|
29
|
+
}
|
|
30
|
+
fromMetadata(activeContext, metadata) {
|
|
31
|
+
const traceparent = extractTraceparentData(metadata);
|
|
32
|
+
if (!traceparent?.traceId || !traceparent?.parentSpanId) return activeContext;
|
|
33
|
+
return {
|
|
34
|
+
...activeContext,
|
|
35
|
+
producerSpanContext: {
|
|
36
|
+
traceId: traceparent.traceId,
|
|
37
|
+
spanId: traceparent.parentSpanId,
|
|
38
|
+
sampled: traceparent.parentSampled === true
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
export { SentryBullMQContextManager };
|
|
44
|
+
|
|
45
|
+
//# sourceMappingURL=contextManager.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"contextManager.js","names":[],"sources":["../../../../src/integrations/bullmq/contextManager.ts"],"sourcesContent":["import type { Span } from '@opentelemetry/api';\nimport {\n extractTraceparentData,\n getActiveSpan,\n getCurrentScope,\n spanToTraceHeader,\n withActiveSpan,\n withIsolationScope,\n} from '@sentry/core';\nimport type { ContextManager, SentryContext } from './types';\n\nexport class SentryBullMQContextManager implements ContextManager<SentryContext> {\n public active(): SentryContext {\n return {\n span: getActiveSpan(),\n scope: getCurrentScope(),\n };\n }\n\n public with<A extends (...args: unknown[]) => unknown>(context: SentryContext, fn: A): ReturnType<A> {\n if (context.span) {\n return withIsolationScope(() => {\n return withActiveSpan(context.span as Span, fn) as ReturnType<A>;\n });\n }\n return withIsolationScope(() => withActiveSpan(null, fn)) as ReturnType<A>;\n }\n\n /**\n * Returns a context without a span. BullMQ 6.3.11+ runs the stalled jobs checker in it, so the\n * checker does not stay attached to the span that was active when the worker started.\n */\n public root(): SentryContext {\n return {\n span: undefined,\n scope: getCurrentScope(),\n };\n }\n\n public getMetadata(context: SentryContext): string {\n if (context.span) {\n return spanToTraceHeader(context.span);\n }\n return '';\n }\n\n public fromMetadata(activeContext: SentryContext, metadata: string): SentryContext {\n const traceparent = extractTraceparentData(metadata);\n if (!traceparent?.traceId || !traceparent?.parentSpanId) {\n return activeContext;\n }\n\n return {\n ...activeContext,\n producerSpanContext: {\n traceId: traceparent.traceId,\n spanId: traceparent.parentSpanId,\n sampled: traceparent.parentSampled === true,\n },\n };\n }\n}\n"],"mappings":";;AAWA,IAAa,6BAAb,MAAiF;CACxE,SAAwB;EAC7B,OAAO;GACL,MAAM,cAAc;GACpB,OAAO,gBAAgB;EACzB;CACF;CAEO,KAAgD,SAAwB,IAAsB;EACnG,IAAI,QAAQ,MACV,OAAO,yBAAyB;GAC9B,OAAO,eAAe,QAAQ,MAAc,EAAE;EAChD,CAAC;EAEH,OAAO,yBAAyB,eAAe,MAAM,EAAE,CAAC;CAC1D;;;;;CAMO,OAAsB;EAC3B,OAAO;GACL,MAAM,KAAA;GACN,OAAO,gBAAgB;EACzB;CACF;CAEO,YAAY,SAAgC;EACjD,IAAI,QAAQ,MACV,OAAO,kBAAkB,QAAQ,IAAI;EAEvC,OAAO;CACT;CAEO,aAAa,eAA8B,UAAiC;EACjF,MAAM,cAAc,uBAAuB,QAAQ;EACnD,IAAI,CAAC,aAAa,WAAW,CAAC,aAAa,cACzC,OAAO;EAGT,OAAO;GACL,GAAG;GACH,qBAAqB;IACnB,SAAS,YAAY;IACrB,QAAQ,YAAY;IACpB,SAAS,YAAY,kBAAkB;GACzC;EACF;CACF;AACF"}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { SentryBullMQContextManager } from "./contextManager.js";
|
|
2
|
+
import { SentryBullMQMeter } from "./meter.js";
|
|
3
|
+
import { SentryBullMQTracer } from "./tracer.js";
|
|
4
|
+
// src/integrations/bullmq/index.ts
|
|
5
|
+
/**
|
|
6
|
+
* A Sentry-specific telemetry implementation for BullMQ.
|
|
7
|
+
*
|
|
8
|
+
* This implements BullMQ's Telemetry interface to provide automatic tracing
|
|
9
|
+
* for queue operations with proper Queue Insights attributes.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```javascript
|
|
13
|
+
* import * as Sentry from '@sentry/node';
|
|
14
|
+
* import { Queue, Worker } from 'bullmq';
|
|
15
|
+
*
|
|
16
|
+
* const telemetry = new Sentry.BullMQTelemetry();
|
|
17
|
+
*
|
|
18
|
+
* const queue = new Queue('myQueue', {
|
|
19
|
+
* connection: { host: '127.0.0.1', port: 6379 },
|
|
20
|
+
* telemetry,
|
|
21
|
+
* });
|
|
22
|
+
*
|
|
23
|
+
* const worker = new Worker('myQueue', async (job) => {
|
|
24
|
+
* // Process job
|
|
25
|
+
* }, {
|
|
26
|
+
* connection: { host: '127.0.0.1', port: 6379 },
|
|
27
|
+
* telemetry,
|
|
28
|
+
* });
|
|
29
|
+
* ```
|
|
30
|
+
*
|
|
31
|
+
* To also send BullMQ's job metrics to Sentry, use `new Sentry.BullMQTelemetry({ enableMetrics: true })`.
|
|
32
|
+
*
|
|
33
|
+
* @see https://docs.bullmq.io/guide/telemetry
|
|
34
|
+
*/
|
|
35
|
+
var BullMQTelemetry = class {
|
|
36
|
+
constructor(options = {}) {
|
|
37
|
+
this.tracer = new SentryBullMQTracer();
|
|
38
|
+
this.contextManager = new SentryBullMQContextManager();
|
|
39
|
+
if (options.enableMetrics) this.meter = new SentryBullMQMeter();
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
export { BullMQTelemetry };
|
|
43
|
+
|
|
44
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/integrations/bullmq/index.ts"],"sourcesContent":["import { SentryBullMQContextManager } from './contextManager';\nimport { SentryBullMQMeter } from './meter';\nimport { SentryBullMQTracer } from './tracer';\nimport type { ContextManager, Meter, Telemetry, Tracer, SentryContext } from './types';\n\n/**\n * A Sentry-specific telemetry implementation for BullMQ.\n *\n * This implements BullMQ's Telemetry interface to provide automatic tracing\n * for queue operations with proper Queue Insights attributes.\n *\n * @example\n * ```javascript\n * import * as Sentry from '@sentry/node';\n * import { Queue, Worker } from 'bullmq';\n *\n * const telemetry = new Sentry.BullMQTelemetry();\n *\n * const queue = new Queue('myQueue', {\n * connection: { host: '127.0.0.1', port: 6379 },\n * telemetry,\n * });\n *\n * const worker = new Worker('myQueue', async (job) => {\n * // Process job\n * }, {\n * connection: { host: '127.0.0.1', port: 6379 },\n * telemetry,\n * });\n * ```\n *\n * To also send BullMQ's job metrics to Sentry, use `new Sentry.BullMQTelemetry({ enableMetrics: true })`.\n *\n * @see https://docs.bullmq.io/guide/telemetry\n */\nexport class BullMQTelemetry implements Telemetry<SentryContext> {\n public tracer: Tracer<SentryContext>;\n public contextManager: ContextManager<SentryContext>;\n public meter?: Meter;\n\n public constructor(\n options: {\n /**\n * Sends BullMQ's job metrics, such as `messaging.bullmq.jobs.completed` and `messaging.process.duration`, to Sentry. Defaults to `false`.\n */\n enableMetrics?: boolean;\n } = {},\n ) {\n this.tracer = new SentryBullMQTracer();\n this.contextManager = new SentryBullMQContextManager();\n\n if (options.enableMetrics) {\n this.meter = new SentryBullMQMeter();\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,IAAa,kBAAb,MAAiE;CAKxD,YACL,UAKI,CAAC,GACL;EACA,KAAK,SAAS,IAAI,mBAAmB;EACrC,KAAK,iBAAiB,IAAI,2BAA2B;EAErD,IAAI,QAAQ,eACV,KAAK,QAAQ,IAAI,kBAAkB;CAEvC;AACF"}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { toMessagingKey, toSentryAttributes } from "./span.js";
|
|
2
|
+
import { MESSAGING_OPERATION_NAME, MESSAGING_SYSTEM } from "@sentry/conventions/attributes";
|
|
3
|
+
import { metrics } from "@sentry/core";
|
|
4
|
+
import { MESSAGING_PROCESS_DURATION } from "@sentry/conventions/metrics";
|
|
5
|
+
// src/integrations/bullmq/meter.ts
|
|
6
|
+
function toMetricAttributes(attributes) {
|
|
7
|
+
if (!attributes) return;
|
|
8
|
+
const result = {};
|
|
9
|
+
for (const [key, value] of Object.entries(toSentryAttributes(attributes))) if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") result[key] = value;
|
|
10
|
+
return result;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Converts the OpenTelemetry (UCUM) unit that BullMQ passes to the matching Sentry unit.
|
|
14
|
+
*/
|
|
15
|
+
function toSentryUnit(unit) {
|
|
16
|
+
if (unit === "ms") return "millisecond";
|
|
17
|
+
if (unit === "1" || unit?.startsWith("{")) return "none";
|
|
18
|
+
return unit;
|
|
19
|
+
}
|
|
20
|
+
var SentryBullMQCounter = class {
|
|
21
|
+
constructor(name, unit) {
|
|
22
|
+
this._name = name;
|
|
23
|
+
this._unit = unit;
|
|
24
|
+
}
|
|
25
|
+
add(value, attributes) {
|
|
26
|
+
metrics.count(this._name, value, {
|
|
27
|
+
unit: this._unit,
|
|
28
|
+
attributes: toMetricAttributes(attributes)
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
var SentryBullMQHistogram = class {
|
|
33
|
+
constructor(name, unit) {
|
|
34
|
+
this._name = name;
|
|
35
|
+
this._unit = unit;
|
|
36
|
+
}
|
|
37
|
+
record(value, attributes) {
|
|
38
|
+
metrics.distribution(this._name, value, {
|
|
39
|
+
unit: this._unit,
|
|
40
|
+
attributes: toMetricAttributes(attributes)
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
var SentryBullMQGauge = class {
|
|
45
|
+
constructor(name, unit) {
|
|
46
|
+
this._name = name;
|
|
47
|
+
this._unit = unit;
|
|
48
|
+
}
|
|
49
|
+
record(value, attributes) {
|
|
50
|
+
metrics.gauge(this._name, value, {
|
|
51
|
+
unit: this._unit,
|
|
52
|
+
attributes: toMetricAttributes(attributes)
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* Records BullMQ's `bullmq.job.duration` histogram, which is in milliseconds, as the OTel
|
|
58
|
+
* `messaging.process.duration` metric in seconds.
|
|
59
|
+
*/
|
|
60
|
+
var SentryBullMQProcessDuration = class {
|
|
61
|
+
record(value, attributes) {
|
|
62
|
+
metrics.distribution(MESSAGING_PROCESS_DURATION, value / 1e3, {
|
|
63
|
+
unit: "second",
|
|
64
|
+
attributes: {
|
|
65
|
+
...toMetricAttributes(attributes),
|
|
66
|
+
[MESSAGING_SYSTEM]: "bullmq",
|
|
67
|
+
[MESSAGING_OPERATION_NAME]: "process"
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
var SentryBullMQMeter = class {
|
|
73
|
+
createCounter(name, options) {
|
|
74
|
+
return new SentryBullMQCounter(toMessagingKey(name), toSentryUnit(options?.unit));
|
|
75
|
+
}
|
|
76
|
+
createHistogram(name, options) {
|
|
77
|
+
if (name === "bullmq.job.duration") return new SentryBullMQProcessDuration();
|
|
78
|
+
return new SentryBullMQHistogram(toMessagingKey(name), toSentryUnit(options?.unit));
|
|
79
|
+
}
|
|
80
|
+
createGauge(name, options) {
|
|
81
|
+
return new SentryBullMQGauge(toMessagingKey(name), toSentryUnit(options?.unit));
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
export { SentryBullMQMeter };
|
|
85
|
+
|
|
86
|
+
//# sourceMappingURL=meter.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"meter.js","names":[],"sources":["../../../../src/integrations/bullmq/meter.ts"],"sourcesContent":["import { MESSAGING_OPERATION_NAME, MESSAGING_SYSTEM } from '@sentry/conventions/attributes';\nimport { MESSAGING_PROCESS_DURATION } from '@sentry/conventions/metrics';\nimport { metrics } from '@sentry/core';\nimport { toMessagingKey, toSentryAttributes } from './span';\nimport type { AttributeValue, Counter, Gauge, Histogram, Meter, MetricOptions } from './types';\n\nfunction toMetricAttributes(\n attributes?: Record<string, AttributeValue>,\n): Record<string, string | number | boolean> | undefined {\n if (!attributes) {\n return undefined;\n }\n const result: Record<string, string | number | boolean> = {};\n for (const [key, value] of Object.entries(toSentryAttributes(attributes))) {\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n result[key] = value;\n }\n }\n return result;\n}\n\n/**\n * Converts the OpenTelemetry (UCUM) unit that BullMQ passes to the matching Sentry unit.\n */\nfunction toSentryUnit(unit?: string): string | undefined {\n if (unit === 'ms') {\n return 'millisecond';\n }\n\n // In UCUM, `1` and annotations such as `{jobs}` mark a value without a unit.\n if (unit === '1' || unit?.startsWith('{')) {\n return 'none';\n }\n\n return unit;\n}\n\nclass SentryBullMQCounter implements Counter {\n private _name: string;\n private _unit?: string;\n\n public constructor(name: string, unit?: string) {\n this._name = name;\n this._unit = unit;\n }\n\n public add(value: number, attributes?: Record<string, AttributeValue>): void {\n metrics.count(this._name, value, {\n unit: this._unit,\n attributes: toMetricAttributes(attributes),\n });\n }\n}\n\nclass SentryBullMQHistogram implements Histogram {\n private _name: string;\n private _unit?: string;\n\n public constructor(name: string, unit?: string) {\n this._name = name;\n this._unit = unit;\n }\n\n public record(value: number, attributes?: Record<string, AttributeValue>): void {\n metrics.distribution(this._name, value, {\n unit: this._unit,\n attributes: toMetricAttributes(attributes),\n });\n }\n}\n\nclass SentryBullMQGauge implements Gauge {\n private _name: string;\n private _unit?: string;\n\n public constructor(name: string, unit?: string) {\n this._name = name;\n this._unit = unit;\n }\n\n public record(value: number, attributes?: Record<string, AttributeValue>): void {\n metrics.gauge(this._name, value, {\n unit: this._unit,\n attributes: toMetricAttributes(attributes),\n });\n }\n}\n\n/**\n * Records BullMQ's `bullmq.job.duration` histogram, which is in milliseconds, as the OTel\n * `messaging.process.duration` metric in seconds.\n */\nclass SentryBullMQProcessDuration implements Histogram {\n public record(value: number, attributes?: Record<string, AttributeValue>): void {\n metrics.distribution(MESSAGING_PROCESS_DURATION, value / 1000, {\n unit: 'second',\n attributes: {\n ...toMetricAttributes(attributes),\n [MESSAGING_SYSTEM]: 'bullmq',\n [MESSAGING_OPERATION_NAME]: 'process',\n },\n });\n }\n}\n\nexport class SentryBullMQMeter implements Meter {\n public createCounter(name: string, options?: MetricOptions): Counter {\n return new SentryBullMQCounter(toMessagingKey(name), toSentryUnit(options?.unit));\n }\n\n public createHistogram(name: string, options?: MetricOptions): Histogram {\n if (name === 'bullmq.job.duration') {\n return new SentryBullMQProcessDuration();\n }\n\n return new SentryBullMQHistogram(toMessagingKey(name), toSentryUnit(options?.unit));\n }\n\n public createGauge(name: string, options?: MetricOptions): Gauge {\n return new SentryBullMQGauge(toMessagingKey(name), toSentryUnit(options?.unit));\n }\n}\n"],"mappings":";;;;;AAMA,SAAS,mBACP,YACuD;CACvD,IAAI,CAAC,YACH;CAEF,MAAM,SAAoD,CAAC;CAC3D,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,mBAAmB,UAAU,CAAC,GACtE,IAAI,OAAO,UAAU,YAAY,OAAO,UAAU,YAAY,OAAO,UAAU,WAC7E,OAAO,OAAO;CAGlB,OAAO;AACT;;;;AAKA,SAAS,aAAa,MAAmC;CACvD,IAAI,SAAS,MACX,OAAO;CAIT,IAAI,SAAS,OAAO,MAAM,WAAW,GAAG,GACtC,OAAO;CAGT,OAAO;AACT;AAEA,IAAM,sBAAN,MAA6C;CAIpC,YAAY,MAAc,MAAe;EAC9C,KAAK,QAAQ;EACb,KAAK,QAAQ;CACf;CAEO,IAAI,OAAe,YAAmD;EAC3E,QAAQ,MAAM,KAAK,OAAO,OAAO;GAC/B,MAAM,KAAK;GACX,YAAY,mBAAmB,UAAU;EAC3C,CAAC;CACH;AACF;AAEA,IAAM,wBAAN,MAAiD;CAIxC,YAAY,MAAc,MAAe;EAC9C,KAAK,QAAQ;EACb,KAAK,QAAQ;CACf;CAEO,OAAO,OAAe,YAAmD;EAC9E,QAAQ,aAAa,K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