@sentry/server-utils 11.14.0 → 11.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/cjs/chunks/exports.js +604 -219
- package/build/cjs/chunks/exports.js.map +1 -1
- package/build/cjs/index.js +1028 -120
- package/build/cjs/index.js.map +1 -1
- package/build/cjs/index.request-handler.js +1 -0
- package/build/cjs/index.request-handler.js.map +1 -1
- package/build/esm/ai/anthropic-ai/index.js +32 -56
- package/build/esm/ai/anthropic-ai/index.js.map +1 -1
- package/build/esm/ai/anthropic-ai/streaming.js +10 -6
- package/build/esm/ai/anthropic-ai/streaming.js.map +1 -1
- package/build/esm/ai/anthropic-ai/tool-runner.js +18 -3
- package/build/esm/ai/anthropic-ai/tool-runner.js.map +1 -1
- package/build/esm/ai/anthropic-ai/utils.js +41 -3
- package/build/esm/ai/anthropic-ai/utils.js.map +1 -1
- package/build/esm/ai/core/span-hooks.js +23 -0
- package/build/esm/ai/core/span-hooks.js.map +1 -0
- package/build/esm/ai/core/time-to-first-chunk.js +14 -0
- package/build/esm/ai/core/time-to-first-chunk.js.map +1 -0
- package/build/esm/ai/core/utils.js +29 -3
- package/build/esm/ai/core/utils.js.map +1 -1
- package/build/esm/ai/flue/index.js +15 -12
- package/build/esm/ai/flue/index.js.map +1 -1
- package/build/esm/ai/flue/utils.js +25 -17
- package/build/esm/ai/flue/utils.js.map +1 -1
- package/build/esm/ai/google-genai/decisions.js +29 -1
- package/build/esm/ai/google-genai/decisions.js.map +1 -1
- package/build/esm/ai/google-genai/index.js +21 -8
- package/build/esm/ai/google-genai/index.js.map +1 -1
- package/build/esm/ai/google-genai/streaming.js +6 -2
- package/build/esm/ai/google-genai/streaming.js.map +1 -1
- package/build/esm/ai/langchain/embeddings.js +5 -2
- package/build/esm/ai/langchain/embeddings.js.map +1 -1
- package/build/esm/ai/langchain/index.js +82 -24
- package/build/esm/ai/langchain/index.js.map +1 -1
- package/build/esm/ai/langchain/utils.js +9 -1
- package/build/esm/ai/langchain/utils.js.map +1 -1
- package/build/esm/ai/langgraph/agent-span.js +13 -5
- package/build/esm/ai/langgraph/agent-span.js.map +1 -1
- package/build/esm/ai/langgraph/index.js +13 -15
- package/build/esm/ai/langgraph/index.js.map +1 -1
- package/build/esm/ai/langgraph/stream.js +4 -3
- package/build/esm/ai/langgraph/stream.js.map +1 -1
- package/build/esm/ai/langgraph/utils.js +17 -8
- package/build/esm/ai/langgraph/utils.js.map +1 -1
- package/build/esm/ai/mastra/classifier-evaluation.js.map +1 -1
- package/build/esm/ai/mastra/index.js +33 -16
- package/build/esm/ai/mastra/index.js.map +1 -1
- package/build/esm/ai/mastra/utils.js +3 -5
- package/build/esm/ai/mastra/utils.js.map +1 -1
- package/build/esm/ai/mistral/index.js +21 -7
- package/build/esm/ai/mistral/index.js.map +1 -1
- package/build/esm/ai/mistral/streaming.js +4 -2
- package/build/esm/ai/mistral/streaming.js.map +1 -1
- package/build/esm/ai/openai/index.js +19 -8
- package/build/esm/ai/openai/index.js.map +1 -1
- package/build/esm/ai/openai/mapping.js +48 -1
- package/build/esm/ai/openai/mapping.js.map +1 -1
- package/build/esm/ai/openai/streaming.js +7 -2
- package/build/esm/ai/openai/streaming.js.map +1 -1
- package/build/esm/ai/pi-ai/chat.js +18 -1
- package/build/esm/ai/pi-ai/chat.js.map +1 -1
- package/build/esm/ai/pi-ai/recording.js +34 -15
- package/build/esm/ai/pi-ai/recording.js.map +1 -1
- package/build/esm/ai/pi-durable/index.js +7 -2
- package/build/esm/ai/pi-durable/index.js.map +1 -1
- package/build/esm/ai/pi-durable/runs.js.map +1 -1
- package/build/esm/ai/pi-durable/tools.js +18 -3
- package/build/esm/ai/pi-durable/tools.js.map +1 -1
- package/build/esm/ai/typesafe/index.js +14 -6
- package/build/esm/ai/typesafe/index.js.map +1 -1
- package/build/esm/ai/workers-ai/index.js +26 -9
- package/build/esm/ai/workers-ai/index.js.map +1 -1
- package/build/esm/ai/workers-ai/streaming.js +6 -4
- package/build/esm/ai/workers-ai/streaming.js.map +1 -1
- package/build/esm/cron/common.js +16 -0
- package/build/esm/cron/common.js.map +1 -0
- package/build/esm/cron/cron.js +82 -0
- package/build/esm/cron/cron.js.map +1 -0
- package/build/esm/cron/index.js +13 -0
- package/build/esm/cron/index.js.map +1 -0
- package/build/esm/cron/node-cron.js +66 -0
- package/build/esm/cron/node-cron.js.map +1 -0
- package/build/esm/cron/node-schedule.js +43 -0
- package/build/esm/cron/node-schedule.js.map +1 -0
- package/build/esm/index.js +6 -2
- package/build/esm/index.js.map +1 -1
- package/build/esm/integrations/anthropic.js +25 -16
- package/build/esm/integrations/anthropic.js.map +1 -1
- package/build/esm/integrations/aws-sdk/index.js +1 -0
- package/build/esm/integrations/aws-sdk/index.js.map +1 -1
- package/build/esm/integrations/aws-sdk/services/ServicesExtensions.js +3 -0
- package/build/esm/integrations/aws-sdk/services/ServicesExtensions.js.map +1 -1
- package/build/esm/integrations/aws-sdk/services/bedrock-runtime.js +45 -12
- package/build/esm/integrations/aws-sdk/services/bedrock-runtime.js.map +1 -1
- package/build/esm/integrations/bullmq/contextManager.js +45 -0
- package/build/esm/integrations/bullmq/contextManager.js.map +1 -0
- package/build/esm/integrations/bullmq/index.js +44 -0
- package/build/esm/integrations/bullmq/index.js.map +1 -0
- package/build/esm/integrations/bullmq/meter.js +86 -0
- package/build/esm/integrations/bullmq/meter.js.map +1 -0
- package/build/esm/integrations/bullmq/span.js +114 -0
- package/build/esm/integrations/bullmq/span.js.map +1 -0
- package/build/esm/integrations/bullmq/tracer.js +62 -0
- package/build/esm/integrations/bullmq/tracer.js.map +1 -0
- package/build/esm/integrations/express/instrumentation.js +10 -1
- package/build/esm/integrations/express/instrumentation.js.map +1 -1
- package/build/esm/integrations/google-genai.js +17 -9
- package/build/esm/integrations/google-genai.js.map +1 -1
- package/build/esm/integrations/langgraph.js +5 -7
- package/build/esm/integrations/langgraph.js.map +1 -1
- package/build/esm/integrations/mastra-classifier.js +1 -1
- package/build/esm/integrations/mastra-classifier.js.map +1 -1
- package/build/esm/integrations/mistral.js +13 -4
- package/build/esm/integrations/mistral.js.map +1 -1
- package/build/esm/integrations/openai-compatible.js +16 -8
- package/build/esm/integrations/openai-compatible.js.map +1 -1
- package/build/esm/integrations/openai.js +16 -8
- package/build/esm/integrations/openai.js.map +1 -1
- package/build/esm/integrations/pi-ai.js +39 -18
- package/build/esm/integrations/pi-ai.js.map +1 -1
- package/build/esm/integrations/pino.js +131 -0
- package/build/esm/integrations/pino.js.map +1 -0
- package/build/esm/integrations/typesafe.js +17 -3
- package/build/esm/integrations/typesafe.js.map +1 -1
- package/build/esm/integrations/vercel-ai/index.js.map +1 -1
- package/build/esm/integrations/vercel-ai/util.js +3 -2
- package/build/esm/integrations/vercel-ai/util.js.map +1 -1
- package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js +44 -17
- package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -1
- package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js +22 -16
- package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js.map +1 -1
- package/build/esm/integrations/winston.js +90 -0
- package/build/esm/integrations/winston.js.map +1 -0
- package/build/esm/orchestrion/detect.js +1 -1
- package/build/esm/orchestrion/detect.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/esm/utils/wrapServerRequestHandler.js +2 -1
- package/build/esm/utils/wrapServerRequestHandler.js.map +1 -1
- package/build/types/ai/anthropic-ai/index.d.ts +1 -5
- package/build/types/ai/anthropic-ai/index.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/streaming.d.ts +3 -2
- package/build/types/ai/anthropic-ai/streaming.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/tool-runner.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/types.d.ts +24 -3
- package/build/types/ai/anthropic-ai/types.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/utils.d.ts +2 -3
- package/build/types/ai/anthropic-ai/utils.d.ts.map +1 -1
- package/build/types/ai/core/span-hooks.d.ts +31 -0
- package/build/types/ai/core/span-hooks.d.ts.map +1 -0
- package/build/types/ai/core/time-to-first-chunk.d.ts +7 -0
- package/build/types/ai/core/time-to-first-chunk.d.ts.map +1 -0
- package/build/types/ai/core/utils.d.ts +30 -1
- package/build/types/ai/core/utils.d.ts.map +1 -1
- package/build/types/ai/flue/index.d.ts +13 -5
- package/build/types/ai/flue/index.d.ts.map +1 -1
- package/build/types/ai/flue/types.d.ts +20 -2
- package/build/types/ai/flue/types.d.ts.map +1 -1
- package/build/types/ai/flue/utils.d.ts +5 -9
- package/build/types/ai/flue/utils.d.ts.map +1 -1
- package/build/types/ai/google-genai/decisions.d.ts.map +1 -1
- package/build/types/ai/google-genai/index.d.ts.map +1 -1
- package/build/types/ai/google-genai/streaming.d.ts +2 -1
- package/build/types/ai/google-genai/streaming.d.ts.map +1 -1
- package/build/types/ai/google-genai/types.d.ts +17 -3
- package/build/types/ai/google-genai/types.d.ts.map +1 -1
- package/build/types/ai/langchain/index.d.ts.map +1 -1
- package/build/types/ai/langchain/types.d.ts +49 -3
- package/build/types/ai/langchain/types.d.ts.map +1 -1
- package/build/types/ai/langchain/utils.d.ts +6 -0
- package/build/types/ai/langchain/utils.d.ts.map +1 -1
- package/build/types/ai/langgraph/agent-span.d.ts +4 -1
- package/build/types/ai/langgraph/agent-span.d.ts.map +1 -1
- package/build/types/ai/langgraph/index.d.ts +1 -1
- package/build/types/ai/langgraph/index.d.ts.map +1 -1
- package/build/types/ai/langgraph/stream.d.ts.map +1 -1
- package/build/types/ai/langgraph/types.d.ts +14 -3
- package/build/types/ai/langgraph/types.d.ts.map +1 -1
- package/build/types/ai/langgraph/utils.d.ts +3 -0
- package/build/types/ai/langgraph/utils.d.ts.map +1 -1
- package/build/types/ai/mastra/classifier-evaluation.d.ts +3 -3
- package/build/types/ai/mastra/classifier-evaluation.d.ts.map +1 -1
- package/build/types/ai/mastra/index.d.ts +17 -3
- package/build/types/ai/mastra/index.d.ts.map +1 -1
- package/build/types/ai/mastra/types.d.ts +2 -0
- package/build/types/ai/mastra/types.d.ts.map +1 -1
- package/build/types/ai/mastra/utils.d.ts.map +1 -1
- package/build/types/ai/mistral/index.d.ts.map +1 -1
- package/build/types/ai/mistral/streaming.d.ts +2 -1
- package/build/types/ai/mistral/streaming.d.ts.map +1 -1
- package/build/types/ai/mistral/types.d.ts +14 -3
- package/build/types/ai/mistral/types.d.ts.map +1 -1
- package/build/types/ai/openai/index.d.ts.map +1 -1
- package/build/types/ai/openai/mapping.d.ts.map +1 -1
- package/build/types/ai/openai/streaming.d.ts +3 -1
- package/build/types/ai/openai/streaming.d.ts.map +1 -1
- package/build/types/ai/openai/types.d.ts +14 -3
- package/build/types/ai/openai/types.d.ts.map +1 -1
- package/build/types/ai/pi-ai/chat.d.ts +7 -1
- package/build/types/ai/pi-ai/chat.d.ts.map +1 -1
- package/build/types/ai/pi-ai/recording.d.ts +21 -9
- package/build/types/ai/pi-ai/recording.d.ts.map +1 -1
- package/build/types/ai/pi-ai/types.d.ts +16 -0
- package/build/types/ai/pi-ai/types.d.ts.map +1 -1
- package/build/types/ai/pi-durable/index.d.ts +12 -3
- package/build/types/ai/pi-durable/index.d.ts.map +1 -1
- package/build/types/ai/pi-durable/runs.d.ts +2 -0
- package/build/types/ai/pi-durable/runs.d.ts.map +1 -1
- package/build/types/ai/pi-durable/tools.d.ts +4 -3
- package/build/types/ai/pi-durable/tools.d.ts.map +1 -1
- package/build/types/ai/pi-durable/types.d.ts +15 -0
- package/build/types/ai/pi-durable/types.d.ts.map +1 -1
- package/build/types/ai/types.d.ts +1 -1
- package/build/types/ai/types.d.ts.map +1 -1
- package/build/types/ai/typesafe/index.d.ts +10 -2
- package/build/types/ai/typesafe/index.d.ts.map +1 -1
- package/build/types/ai/workers-ai/index.d.ts.map +1 -1
- package/build/types/ai/workers-ai/streaming.d.ts +2 -1
- package/build/types/ai/workers-ai/streaming.d.ts.map +1 -1
- package/build/types/ai/workers-ai/types.d.ts +18 -3
- package/build/types/ai/workers-ai/types.d.ts.map +1 -1
- package/build/types/cron/common.d.ts +8 -0
- package/build/types/cron/common.d.ts.map +1 -0
- package/build/types/cron/cron.d.ts +45 -0
- package/build/types/cron/cron.d.ts.map +1 -0
- package/build/types/cron/index.d.ts +10 -0
- package/build/types/cron/index.d.ts.map +1 -0
- package/build/types/cron/node-cron.d.ts +33 -0
- package/build/types/cron/node-cron.d.ts.map +1 -0
- package/build/types/cron/node-schedule.d.ts +19 -0
- package/build/types/cron/node-schedule.d.ts.map +1 -0
- package/build/types/index.d.ts +5 -2
- package/build/types/index.d.ts.map +1 -1
- package/build/types/integrations/anthropic.d.ts +2 -1
- package/build/types/integrations/anthropic.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/index.d.ts +3 -3
- package/build/types/integrations/aws-sdk/index.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/services/ServiceExtension.d.ts +1 -0
- package/build/types/integrations/aws-sdk/services/ServiceExtension.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/services/ServicesExtensions.d.ts +3 -2
- package/build/types/integrations/aws-sdk/services/ServicesExtensions.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/services/bedrock-runtime.d.ts +25 -4
- package/build/types/integrations/aws-sdk/services/bedrock-runtime.d.ts.map +1 -1
- package/build/types/integrations/bullmq/contextManager.d.ts +13 -0
- package/build/types/integrations/bullmq/contextManager.d.ts.map +1 -0
- package/build/types/integrations/bullmq/index.d.ts +43 -0
- package/build/types/integrations/bullmq/index.d.ts.map +1 -0
- package/build/types/integrations/bullmq/meter.d.ts +7 -0
- package/build/types/integrations/bullmq/meter.d.ts.map +1 -0
- package/build/types/integrations/bullmq/span.d.ts +35 -0
- package/build/types/integrations/bullmq/span.d.ts.map +1 -0
- package/build/types/integrations/bullmq/tracer.d.ts +5 -0
- package/build/types/integrations/bullmq/tracer.d.ts.map +1 -0
- package/build/types/integrations/bullmq/types.d.ts +72 -0
- package/build/types/integrations/bullmq/types.d.ts.map +1 -0
- package/build/types/integrations/express/types.d.ts +1 -0
- package/build/types/integrations/express/types.d.ts.map +1 -1
- package/build/types/integrations/flue.d.ts +2 -1
- package/build/types/integrations/flue.d.ts.map +1 -1
- package/build/types/integrations/google-genai.d.ts +2 -1
- package/build/types/integrations/google-genai.d.ts.map +1 -1
- package/build/types/integrations/groq.d.ts +1 -1
- package/build/types/integrations/langchain.d.ts +2 -1
- package/build/types/integrations/langchain.d.ts.map +1 -1
- package/build/types/integrations/langgraph.d.ts +2 -1
- package/build/types/integrations/langgraph.d.ts.map +1 -1
- package/build/types/integrations/mistral.d.ts +2 -1
- package/build/types/integrations/mistral.d.ts.map +1 -1
- package/build/types/integrations/openai-compatible.d.ts.map +1 -1
- package/build/types/integrations/openai.d.ts +2 -1
- package/build/types/integrations/openai.d.ts.map +1 -1
- package/build/types/integrations/pi-ai.d.ts +6 -3
- package/build/types/integrations/pi-ai.d.ts.map +1 -1
- package/build/types/integrations/pi-durable.d.ts +2 -1
- package/build/types/integrations/pi-durable.d.ts.map +1 -1
- package/build/types/integrations/pino.d.ts +61 -0
- package/build/types/integrations/pino.d.ts.map +1 -0
- package/build/types/integrations/together-ai.d.ts +1 -1
- package/build/types/integrations/typesafe.d.ts +2 -2
- package/build/types/integrations/typesafe.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/index.d.ts +3 -3
- package/build/types/integrations/vercel-ai/index.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/util.d.ts +2 -1
- package/build/types/integrations/vercel-ai/util.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts +20 -4
- package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.d.ts.map +1 -1
- package/build/types/integrations/winston.d.ts +55 -0
- package/build/types/integrations/winston.d.ts.map +1 -0
- package/build/types/utils/wrapServerRequestHandler.d.ts.map +1 -1
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-runner.js","names":[],"sources":["../../../../src/ai/anthropic-ai/tool-runner.ts"],"sourcesContent":["import type { Span, WrappedFunction } from '@sentry/core';\nimport {\n captureException,\n fill,\n getActiveSpan,\n getCurrentScope,\n getDefaultCurrentScope,\n getDefaultIsolationScope,\n getIsolationScope,\n getOriginalFunction,\n handleCallbackErrors,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n startNewTrace,\n startSpan,\n stringify,\n withActiveSpan,\n withScope,\n} from '@sentry/core';\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_OPERATION_NAME,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DESCRIPTION,\n GEN_AI_TOOL_NAME,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_EXECUTE_TOOL, GEN_AI_INVOKE_AGENT } from '@sentry/conventions/op';\nimport { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport { getErrorStatus, resolveAIRecordingOptions } from '../core/utils';\nimport { withCleanScopes } from '../../utils/withCleanScopes';\nimport { ANTHROPIC_AI_ORIGIN } from './constants';\nimport type { AnthropicAiOptions } from './types';\n\ntype AnyFunction = (...args: unknown[]) => unknown;\ntype RunnableTool = { name: string; description?: unknown };\ntype RunContext = { toolUse?: { id?: unknown }; toolUseBlock?: { id?: unknown }; signal?: AbortSignal } | undefined;\ntype ToolRunner = { params?: { tools?: unknown } };\ntype SessionToolRunner = { tools?: unknown; sessionId?: unknown };\n\n/** Wrap the `toolRunner()` method of `owner` so the runners it returns trace their tool calls. */\nexport function instrumentToolRunnerFactory(\n owner: object,\n instrumentRunner: (runner: unknown, options: AnthropicAiOptions) => void,\n options: AnthropicAiOptions,\n): void {\n wrapInPlace(owner, 'toolRunner', (toolRunner, thisArg, args) => {\n const runner = toolRunner.apply(thisArg, args);\n instrumentRunner(runner, options);\n return runner;\n });\n}\n\n/** Give each tool call of a tool runner a `gen_ai.execute_tool` span. */\nexport function instrumentToolRunner(runner: unknown, options: AnthropicAiOptions): void {\n if (!runner || typeof runner !== 'object') {\n return;\n }\n\n instrumentTools((runner as ToolRunner).params?.tools, options);\n\n // `addTools()` keeps its tools out of `params`.\n wrapInPlace(runner, 'addTools', (addTools, thisArg, tools) => {\n instrumentTools(tools, options);\n return addTools.apply(thisArg, tools);\n });\n wrapInPlace(runner, 'setMessagesParams', (setMessagesParams, thisArg, args) => {\n const result = setMessagesParams.apply(thisArg, args);\n instrumentTools((runner as ToolRunner).params?.tools, options);\n return result;\n });\n}\n\n/** Give each tool call of a Managed Agents session runner an `execute_tool` span, under one `invoke_agent` span per session. */\nexport function instrumentSessionToolRunner(runner: unknown, options: AnthropicAiOptions): void {\n if (!runner || typeof runner !== 'object') {\n return;\n }\n\n const { tools, sessionId } = runner as SessionToolRunner;\n // The session runner has no `addTools()`: it only runs the tools it was created with.\n instrumentTools(tools, options);\n wrapInPlace(runner, Symbol.asyncIterator, (iterate, thisArg) =>\n traceSessionLoop(\n iterate.call(thisArg) as AsyncIterator<unknown>,\n typeof sessionId === 'string' ? sessionId : undefined,\n ),\n );\n}\n\n/** Wraps the SDK's session iterator so the whole session runs inside one `invoke_agent` span. */\nasync function* traceSessionLoop(\n sdkIterator: AsyncIterator<unknown>,\n sessionId: string | undefined,\n): AsyncGenerator<unknown> {\n const { span, firstResult } = startSession(sdkIterator, sessionId);\n\n try {\n let result = await firstResult;\n while (!result.done) {\n yield result.value;\n result = await sdkIterator.next();\n }\n } catch (error) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n throw error;\n } finally {\n try {\n // After a `break`, closing the SDK loop waits for its in-flight tools, so the span ends after them.\n await sdkIterator.return?.();\n } finally {\n span.end();\n }\n }\n}\n\n// The SDK starts its tool loop on the first `next()`, so that call runs in the session and every tool inherits it.\nfunction startSession(\n sdkIterator: AsyncIterator<unknown>,\n sessionId: string | undefined,\n): { span: Span; firstResult: Promise<IteratorResult<unknown>> } {\n const start = (): { span: Span; firstResult: Promise<IteratorResult<unknown>> } =>\n withScope(scope => {\n // A tool shared between runners can't tell its session, so the id reaches its spans through the scope, unless\n // the app set one with `Sentry.setConversationId()`.\n if (sessionId && !scope.getScopeData().conversationId && !getIsolationScope().getScopeData().conversationId) {\n scope.setConversationId(sessionId);\n }\n\n const span = startInactiveSpan({\n name: 'invoke_agent',\n op: GEN_AI_INVOKE_AGENT,\n attributes: {\n [SENTRY_ORIGIN]: ANTHROPIC_AI_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'invoke_agent',\n [GEN_AI_PROVIDER_NAME]: 'anthropic',\n ...(sessionId ? { [GEN_AI_CONVERSATION_ID]: sessionId } : {}),\n },\n });\n // `async`, so a `next()` that throws rejects `firstResult` and still ends the span.\n return { span, firstResult: withActiveSpan(span, async () => sdkIterator.next()) };\n });\n\n // At top level all sessions would share the process's trace, so each gets its own; anywhere else it stays in the\n // caller's.\n return !getActiveSpan() && getCurrentScope() === getDefaultCurrentScope()\n ? withCleanScopes(getDefaultIsolationScope().clone(), () => startNewTrace(start))\n : start();\n}\n\nfunction instrumentTools(tools: unknown, options: AnthropicAiOptions): void {\n if (!Array.isArray(tools)) {\n return;\n }\n\n for (const tool of tools) {\n // Toolsets are nameless entries whose `run` takes `(ctx, toolUse)`, so only named tools are wrapped.\n if (tool && typeof tool === 'object' && typeof (tool as RunnableTool).name === 'string') {\n wrapInPlace(tool, 'run', (run, thisArg, args) => runWithSpan(tool as RunnableTool, run, thisArg, args, options));\n }\n }\n}\n\nfunction wrapInPlace(\n owner: object,\n key: string | symbol,\n call: (original: AnyFunction, thisArg: unknown, args: unknown[]) => unknown,\n): void {\n const current = (owner as Record<string | symbol, unknown>)[key];\n if (typeof current === 'function' && !getOriginalFunction(current as WrappedFunction)) {\n fill(\n owner,\n key,\n (original: AnyFunction) =>\n function (this: unknown, ...args: unknown[]): unknown {\n return call(original, this, args);\n },\n );\n }\n}\n\nfunction runWithSpan(\n tool: RunnableTool,\n run: AnyFunction,\n thisArg: unknown,\n args: unknown[],\n options: AnthropicAiOptions,\n): unknown {\n const { recordInputs, recordOutputs } = resolveAIRecordingOptions(options);\n const [input, context] = args as [unknown, RunContext];\n // SDK versions before `toolUse` existed pass only `toolUseBlock`.\n const callId = (context?.toolUse ?? context?.toolUseBlock)?.id;\n\n return startSpan(\n {\n name: `execute_tool ${tool.name}`,\n op: GEN_AI_EXECUTE_TOOL,\n attributes: {\n [SENTRY_ORIGIN]: ANTHROPIC_AI_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'execute_tool',\n [GEN_AI_TOOL_NAME]: tool.name,\n ...(typeof tool.description === 'string' ? { [GEN_AI_TOOL_DESCRIPTION]: tool.description } : {}),\n ...(typeof callId === 'string' ? { [GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: callId } : {}),\n ...(recordInputs ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(input) } : {}),\n },\n },\n span =>\n handleCallbackErrors(\n () => run.apply(thisArg, args),\n error => handleToolError(span, error, context),\n undefined,\n result => recordOutputs && span.setAttribute(GEN_AI_TOOL_CALL_RESULT, stringify(result)),\n ),\n );\n}\n\nfunction handleToolError(span: Span, error: unknown, context: RunContext): void {\n span.setStatus(getErrorStatus(context?.signal));\n // An aborted tool, caller abort or timeout, throws because the run stopped, not because the tool failed.\n if (context?.signal?.aborted) {\n return;\n }\n\n // Only a runner passes `toolUse`/`toolUseBlock` (SDK 0.85+), and it hands the throw to the model as a result.\n // A direct call rethrows to its caller, and a `ToolError` is sent on purpose, so neither is captured.\n const fromRunner = !!(context?.toolUse ?? context?.toolUseBlock);\n if (fromRunner && (error as Error | undefined)?.name !== 'ToolError') {\n captureException(error, { mechanism: { handled: true, type: ANTHROPIC_AI_ORIGIN } });\n }\n}\n"],"mappings":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AO,UACL;EACE,MAAM,gBAAgB,KAAK;EAC3B,IAAI;EACJ,YAAY;IACT,gBAAgB;IAChB,wBAAwB;IACxB,mBAAmB,KAAK;GACzB,GAAI,OAAO,KAAK,gBAAgB,WAAW,GAAG,0BAA0B,KAAK,YAAY,IAAI,CAAC;GAC9F,GAAI,OAAO,WAAW,WAAW,GAAG,gCAAgC,OAAO,IAAI,CAAC;GAChF,GAAI,eAAe,GAAG,6BAA6B,UAAU,KAAK,EAAE,IAAI,CAAC;EAC3E;CACF,IACA,SACE,2BACQ,IAAI,MAAM,SAAS,IAAI,IAC7B,UAAS,gBAAgB,MAAM,OAAO,OAAO,GAC7C,KAAA,IACA,WAAU,iBAAiB,KAAK,aAAa,yBAAyB,UAAU,MAAM,CAAC,CACzF,CACJ;AACF;AAEA,SAAS,gBAAgB,MAAY,OAAgB,SAA2B;CAC9E,KAAK,UAAU,eAAe,SAAS,MAAM,CAAC;CAE9C,IAAI,SAAS,QAAQ,SACnB;CAMF,IAAI,CADgB,EAAE,SAAS,WAAW,SAAS,iBAChC,OAA6B,SAAS,aACvD,iBAAiB,OAAO,EAAE,WAAW;EAAE,SAAS;EAAM,MAAM;CAAoB,EAAE,CAAC;AAEvF"}
|
|
1
|
+
{"version":3,"file":"tool-runner.js","names":[],"sources":["../../../../src/ai/anthropic-ai/tool-runner.ts"],"sourcesContent":["import type { Span, WrappedFunction } from '@sentry/core';\nimport {\n captureException,\n fill,\n getActiveSpan,\n getCurrentScope,\n getDefaultCurrentScope,\n getDefaultIsolationScope,\n getIsolationScope,\n getOriginalFunction,\n handleCallbackErrors,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n startNewTrace,\n startSpan,\n stringify,\n withActiveSpan,\n withScope,\n} from '@sentry/core';\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_OPERATION_NAME,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DESCRIPTION,\n GEN_AI_TOOL_NAME,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_EXECUTE_TOOL, GEN_AI_INVOKE_AGENT } from '@sentry/conventions/op';\nimport { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport { getErrorStatus, resolveGenAiCallRecording } from '../core/utils';\nimport { withCleanScopes } from '../../utils/withCleanScopes';\nimport { ANTHROPIC_AI_ORIGIN } from './constants';\nimport type { AnthropicAiCallInfo, AnthropicAiOptions } from './types';\n\ntype AnyFunction = (...args: unknown[]) => unknown;\ntype RunnableTool = { name: string; description?: unknown };\ntype RunContext = { toolUse?: { id?: unknown }; toolUseBlock?: { id?: unknown }; signal?: AbortSignal } | undefined;\ntype ToolRunner = { params?: { tools?: unknown } };\ntype SessionToolRunner = { tools?: unknown; sessionId?: unknown };\n\n/** Wrap the `toolRunner()` method of `owner` so the runners it returns trace their tool calls. */\nexport function instrumentToolRunnerFactory(\n owner: object,\n instrumentRunner: (runner: unknown, options: AnthropicAiOptions) => void,\n options: AnthropicAiOptions,\n): void {\n wrapInPlace(owner, 'toolRunner', (toolRunner, thisArg, args) => {\n const runner = toolRunner.apply(thisArg, args);\n instrumentRunner(runner, options);\n return runner;\n });\n}\n\n/** Give each tool call of a tool runner a `gen_ai.execute_tool` span. */\nexport function instrumentToolRunner(runner: unknown, options: AnthropicAiOptions): void {\n if (!runner || typeof runner !== 'object') {\n return;\n }\n\n instrumentTools((runner as ToolRunner).params?.tools, options);\n\n // `addTools()` keeps its tools out of `params`.\n wrapInPlace(runner, 'addTools', (addTools, thisArg, tools) => {\n instrumentTools(tools, options);\n return addTools.apply(thisArg, tools);\n });\n wrapInPlace(runner, 'setMessagesParams', (setMessagesParams, thisArg, args) => {\n const result = setMessagesParams.apply(thisArg, args);\n instrumentTools((runner as ToolRunner).params?.tools, options);\n return result;\n });\n}\n\n/** Give each tool call of a Managed Agents session runner an `execute_tool` span, under one `invoke_agent` span per session. */\nexport function instrumentSessionToolRunner(runner: unknown, options: AnthropicAiOptions): void {\n if (!runner || typeof runner !== 'object') {\n return;\n }\n\n const { tools, sessionId } = runner as SessionToolRunner;\n // The session runner has no `addTools()`: it only runs the tools it was created with.\n instrumentTools(tools, options);\n wrapInPlace(runner, Symbol.asyncIterator, (iterate, thisArg) =>\n traceSessionLoop(\n iterate.call(thisArg) as AsyncIterator<unknown>,\n typeof sessionId === 'string' ? sessionId : undefined,\n ),\n );\n}\n\n/** Wraps the SDK's session iterator so the whole session runs inside one `invoke_agent` span. */\nasync function* traceSessionLoop(\n sdkIterator: AsyncIterator<unknown>,\n sessionId: string | undefined,\n): AsyncGenerator<unknown> {\n const { span, firstResult } = startSession(sdkIterator, sessionId);\n\n try {\n let result = await firstResult;\n while (!result.done) {\n yield result.value;\n result = await sdkIterator.next();\n }\n } catch (error) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n throw error;\n } finally {\n try {\n // After a `break`, closing the SDK loop waits for its in-flight tools, so the span ends after them.\n await sdkIterator.return?.();\n } finally {\n span.end();\n }\n }\n}\n\n// The SDK starts its tool loop on the first `next()`, so that call runs in the session and every tool inherits it.\nfunction startSession(\n sdkIterator: AsyncIterator<unknown>,\n sessionId: string | undefined,\n): { span: Span; firstResult: Promise<IteratorResult<unknown>> } {\n const start = (): { span: Span; firstResult: Promise<IteratorResult<unknown>> } =>\n withScope(scope => {\n // A tool shared between runners can't tell its session, so the id reaches its spans through the scope, unless\n // the app set one with `Sentry.setConversationId()`.\n if (sessionId && !scope.getScopeData().conversationId && !getIsolationScope().getScopeData().conversationId) {\n scope.setConversationId(sessionId);\n }\n\n const span = startInactiveSpan({\n name: 'invoke_agent',\n op: GEN_AI_INVOKE_AGENT,\n attributes: {\n [SENTRY_ORIGIN]: ANTHROPIC_AI_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'invoke_agent',\n [GEN_AI_PROVIDER_NAME]: 'anthropic',\n ...(sessionId ? { [GEN_AI_CONVERSATION_ID]: sessionId } : {}),\n },\n });\n // `async`, so a `next()` that throws rejects `firstResult` and still ends the span.\n return { span, firstResult: withActiveSpan(span, async () => sdkIterator.next()) };\n });\n\n // At top level all sessions would share the process's trace, so each gets its own; anywhere else it stays in the\n // caller's.\n return !getActiveSpan() && getCurrentScope() === getDefaultCurrentScope()\n ? withCleanScopes(getDefaultIsolationScope().clone(), () => startNewTrace(start))\n : start();\n}\n\nfunction instrumentTools(tools: unknown, options: AnthropicAiOptions): void {\n if (!Array.isArray(tools)) {\n return;\n }\n\n for (const tool of tools) {\n // Toolsets are nameless entries whose `run` takes `(ctx, toolUse)`, so only named tools are wrapped.\n if (tool && typeof tool === 'object' && typeof (tool as RunnableTool).name === 'string') {\n wrapInPlace(tool, 'run', (run, thisArg, args) => runWithSpan(tool as RunnableTool, run, thisArg, args, options));\n }\n }\n}\n\nfunction wrapInPlace(\n owner: object,\n key: string | symbol,\n call: (original: AnyFunction, thisArg: unknown, args: unknown[]) => unknown,\n): void {\n const current = (owner as Record<string | symbol, unknown>)[key];\n if (typeof current === 'function' && !getOriginalFunction(current as WrappedFunction)) {\n fill(\n owner,\n key,\n (original: AnyFunction) =>\n function (this: unknown, ...args: unknown[]): unknown {\n return call(original, this, args);\n },\n );\n }\n}\n\nfunction runWithSpan(\n tool: RunnableTool,\n run: AnyFunction,\n thisArg: unknown,\n args: unknown[],\n options: AnthropicAiOptions,\n): unknown {\n const [input, context] = args as [unknown, RunContext];\n const call: AnthropicAiCallInfo = { operation: 'execute_tool', tool, input };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n // SDK versions before `toolUse` existed pass only `toolUseBlock`.\n const callId = (context?.toolUse ?? context?.toolUseBlock)?.id;\n\n return startSpan(\n {\n name: `execute_tool ${tool.name}`,\n op: GEN_AI_EXECUTE_TOOL,\n attributes: {\n [SENTRY_ORIGIN]: ANTHROPIC_AI_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'execute_tool',\n [GEN_AI_TOOL_NAME]: tool.name,\n ...(typeof tool.description === 'string' ? { [GEN_AI_TOOL_DESCRIPTION]: tool.description } : {}),\n ...(typeof callId === 'string' ? { [GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: callId } : {}),\n ...(recordInputs ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(input) } : {}),\n },\n },\n span => {\n runGenAiSpanStart(options, span, call);\n return handleCallbackErrors(\n () => run.apply(thisArg, args),\n error => {\n handleToolError(span, error, context);\n runGenAiSpanEnd(options, span, call, { error });\n },\n undefined,\n result => {\n if (recordOutputs) {\n span.setAttribute(GEN_AI_TOOL_CALL_RESULT, stringify(result));\n }\n runGenAiSpanEnd(options, span, call, { response: result });\n },\n );\n },\n );\n}\n\nfunction handleToolError(span: Span, error: unknown, context: RunContext): void {\n span.setStatus(getErrorStatus(context?.signal));\n // An aborted tool, caller abort or timeout, throws because the run stopped, not because the tool failed.\n if (context?.signal?.aborted) {\n return;\n }\n\n // Only a runner passes `toolUse`/`toolUseBlock` (SDK 0.85+), and it hands the throw to the model as a result.\n // A direct call rethrows to its caller, and a `ToolError` is sent on purpose, so neither is captured.\n const fromRunner = !!(context?.toolUse ?? context?.toolUseBlock);\n if (fromRunner && (error as Error | undefined)?.name !== 'ToolError') {\n captureException(error, { mechanism: { handled: true, type: ANTHROPIC_AI_ORIGIN } });\n }\n}\n"],"mappings":";;;;;;;;;;AA4CA,SAAgB,4BACd,OACA,kBACA,SACM;CACN,YAAY,OAAO,eAAe,YAAY,SAAS,SAAS;EAC9D,MAAM,SAAS,WAAW,MAAM,SAAS,IAAI;EAC7C,iBAAiB,QAAQ,OAAO;EAChC,OAAO;CACT,CAAC;AACH;;AAGA,SAAgB,qBAAqB,QAAiB,SAAmC;CACvF,IAAI,CAAC,UAAU,OAAO,WAAW,UAC/B;CAGF,gBAAiB,OAAsB,QAAQ,OAAO,OAAO;CAG7D,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,eAAe,GAAG,6BAA6B,UAAU,KAAK,EAAE,IAAI,CAAC;EAC3E;CACF,IACA,SAAQ;EACN,kBAAkB,SAAS,MAAM,IAAI;EACrC,OAAO,2BACC,IAAI,MAAM,SAAS,IAAI,IAC7B,UAAS;GACP,gBAAgB,MAAM,OAAO,OAAO;GACpC,gBAAgB,SAAS,MAAM,MAAM,EAAE,MAAM,CAAC;EAChD,GACA,KAAA,IACA,WAAU;GACR,IAAI,eACF,KAAK,aAAa,yBAAyB,UAAU,MAAM,CAAC;GAE9D,gBAAgB,SAAS,MAAM,MAAM,EAAE,UAAU,OAAO,CAAC;EAC3D,CACF;CACF,CACF;AACF;AAEA,SAAS,gBAAgB,MAAY,OAAgB,SAA2B;CAC9E,KAAK,UAAU,eAAe,SAAS,MAAM,CAAC;CAE9C,IAAI,SAAS,QAAQ,SACnB;CAMF,IAAI,CADgB,EAAE,SAAS,WAAW,SAAS,iBAChC,OAA6B,SAAS,aACvD,iBAAiB,OAAO,EAAE,WAAW;EAAE,SAAS;EAAM,MAAM;CAAoB,EAAE,CAAC;AAEvF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { extractSystemInstructions } from "../core/utils.js";
|
|
2
|
-
import { GEN_AI_INPUT_MESSAGES, GEN_AI_SYSTEM_INSTRUCTIONS } from "@sentry/conventions/attributes";
|
|
1
|
+
import { extractSystemInstructions, getTokenUsageAttributes } from "../core/utils.js";
|
|
2
|
+
import { GEN_AI_INPUT_MESSAGES, GEN_AI_RESPONSE_ID, GEN_AI_RESPONSE_MODEL, GEN_AI_RESPONSE_TEXT, GEN_AI_RESPONSE_TOOL_CALLS, GEN_AI_SYSTEM_INSTRUCTIONS } from "@sentry/conventions/attributes";
|
|
3
3
|
import { SPAN_STATUS_ERROR, captureException, isObjectLike, stringify } from "@sentry/core";
|
|
4
4
|
// src/ai/anthropic-ai/utils.ts
|
|
5
5
|
/**
|
|
@@ -55,6 +55,44 @@ function handleResponseError(span, response) {
|
|
|
55
55
|
} });
|
|
56
56
|
}
|
|
57
57
|
}
|
|
58
|
+
/**
|
|
59
|
+
* Add content attributes when recordOutputs is enabled
|
|
60
|
+
*/
|
|
61
|
+
function addContentAttributes(span, response) {
|
|
62
|
+
if ("content" in response) {
|
|
63
|
+
if (Array.isArray(response.content)) {
|
|
64
|
+
span.setAttributes({ [GEN_AI_RESPONSE_TEXT]: response.content.map((item) => item.text).filter((text) => !!text).join("") });
|
|
65
|
+
const toolCalls = [];
|
|
66
|
+
for (const item of response.content) if (item.type === "tool_use" || item.type === "server_tool_use") toolCalls.push(item);
|
|
67
|
+
if (toolCalls.length > 0) span.setAttributes({ [GEN_AI_RESPONSE_TOOL_CALLS]: JSON.stringify(toolCalls) });
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if ("completion" in response) span.setAttributes({ [GEN_AI_RESPONSE_TEXT]: response.completion });
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Add basic metadata attributes from the response
|
|
74
|
+
*/
|
|
75
|
+
function addMetadataAttributes(span, response) {
|
|
76
|
+
if ("id" in response && "model" in response) {
|
|
77
|
+
span.setAttributes({
|
|
78
|
+
[GEN_AI_RESPONSE_ID]: response.id,
|
|
79
|
+
[GEN_AI_RESPONSE_MODEL]: response.model
|
|
80
|
+
});
|
|
81
|
+
if ("usage" in response && response.usage) span.setAttributes(getTokenUsageAttributes(response.usage.input_tokens + (response.usage.cache_creation_input_tokens ?? 0) + (response.usage.cache_read_input_tokens ?? 0), response.usage.output_tokens, response.usage.cache_creation_input_tokens, response.usage.cache_read_input_tokens));
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Add response attributes to spans
|
|
86
|
+
*/
|
|
87
|
+
function addResponseAttributes(span, response, recordOutputs) {
|
|
88
|
+
if (!response || typeof response !== "object") return;
|
|
89
|
+
if ("type" in response && response.type === "error") {
|
|
90
|
+
handleResponseError(span, response);
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
if (recordOutputs) addContentAttributes(span, response);
|
|
94
|
+
addMetadataAttributes(span, response);
|
|
95
|
+
}
|
|
58
96
|
/** Anthropic accepts the system prompt as a string or as an array of text blocks. */
|
|
59
97
|
function systemToText(system) {
|
|
60
98
|
if (!Array.isArray(system)) return typeof system === "string" ? system : void 0;
|
|
@@ -79,6 +117,6 @@ function messagesFromParams(params) {
|
|
|
79
117
|
const userMessages = inputParamMessages ?? (messagesParamMessages.length ? messagesParamMessages : promptMessages);
|
|
80
118
|
return [...systemMessages, ...userMessages];
|
|
81
119
|
}
|
|
82
|
-
export { getMessagesAttributes, getProviderName,
|
|
120
|
+
export { addResponseAttributes, getMessagesAttributes, getProviderName, mapAnthropicErrorToStatusMessage, messagesFromParams };
|
|
83
121
|
|
|
84
122
|
//# sourceMappingURL=utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":[],"sources":["../../../../src/ai/anthropic-ai/utils.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"utils.js","names":[],"sources":["../../../../src/ai/anthropic-ai/utils.ts"],"sourcesContent":["/* eslint-disable typescript-eslint/no-deprecated */\nimport { captureException, isObjectLike, SPAN_STATUS_ERROR, stringify } from '@sentry/core';\nimport type { Span, SpanStatusType } from '@sentry/core';\nimport {\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n} from '@sentry/conventions/attributes';\nimport { extractSystemInstructions, getTokenUsageAttributes } from '../core/utils';\nimport type { AnthropicAiResponse, ContentBlock } from './types';\n\n/**\n * The `gen_ai.provider.name` of the client that owns an SDK resource such as `messages`. The SDK's clients\n * for other platforms set their own, e.g. `aws.bedrock` for `AnthropicBedrock`.\n */\nexport function getProviderName(resource: unknown): string {\n const name = (resource as { _client?: { _genAIProviderName?: unknown } } | null | undefined)?._client\n ?._genAIProviderName;\n return typeof name === 'string' && name ? name : 'anthropic';\n}\n\n/**\n * Get the input messages attribute, with system instructions extracted into their own attribute.\n */\nexport function getMessagesAttributes(messages: unknown): Record<string, string | undefined> {\n if (Array.isArray(messages) && messages.length === 0) {\n return {};\n }\n\n const { systemInstructions, filteredMessages } = extractSystemInstructions(messages);\n\n const attributes: Record<string, string | undefined> = {};\n if (systemInstructions) {\n attributes[GEN_AI_SYSTEM_INSTRUCTIONS] = systemInstructions;\n }\n attributes[GEN_AI_INPUT_MESSAGES] = stringify(filteredMessages);\n return attributes;\n}\n\nconst ANTHROPIC_ERROR_TYPE_TO_SPAN_STATUS: Record<string, SpanStatusType> = {\n invalid_request_error: 'invalid_argument',\n authentication_error: 'unauthenticated',\n permission_error: 'permission_denied',\n not_found_error: 'not_found',\n request_too_large: 'failed_precondition',\n rate_limit_error: 'resource_exhausted',\n api_error: 'internal_error',\n overloaded_error: 'unavailable',\n};\n\n/**\n * Map an Anthropic API error type to a SpanStatusType value.\n * @see https://docs.anthropic.com/en/api/errors#error-shapes\n */\nexport function mapAnthropicErrorToStatusMessage(errorType: string | undefined): SpanStatusType {\n if (!errorType) {\n return 'internal_error';\n }\n return ANTHROPIC_ERROR_TYPE_TO_SPAN_STATUS[errorType] || 'internal_error';\n}\n\n/**\n * Capture error information from the response\n * @see https://docs.anthropic.com/en/api/errors#error-shapes\n */\nfunction handleResponseError(span: Span, response: AnthropicAiResponse): void {\n if (response.error) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: mapAnthropicErrorToStatusMessage(response.error.type) });\n\n captureException(response.error, {\n mechanism: {\n handled: false,\n type: 'auto.ai.anthropic.anthropic_error',\n },\n });\n }\n}\n\n/**\n * Add content attributes when recordOutputs is enabled\n */\nfunction addContentAttributes(span: Span, response: AnthropicAiResponse): void {\n // Messages.create\n if ('content' in response) {\n if (Array.isArray(response.content)) {\n span.setAttributes({\n [GEN_AI_RESPONSE_TEXT]: response.content\n .map((item: ContentBlock) => item.text)\n .filter(text => !!text)\n .join(''),\n });\n\n const toolCalls: Array<ContentBlock> = [];\n\n for (const item of response.content) {\n if (item.type === 'tool_use' || item.type === 'server_tool_use') {\n toolCalls.push(item);\n }\n }\n if (toolCalls.length > 0) {\n span.setAttributes({ [GEN_AI_RESPONSE_TOOL_CALLS]: JSON.stringify(toolCalls) });\n }\n }\n }\n // Completions.create\n if ('completion' in response) {\n span.setAttributes({ [GEN_AI_RESPONSE_TEXT]: response.completion });\n }\n}\n\n/**\n * Add basic metadata attributes from the response\n */\nfunction addMetadataAttributes(span: Span, response: AnthropicAiResponse): void {\n if ('id' in response && 'model' in response) {\n span.setAttributes({\n [GEN_AI_RESPONSE_ID]: response.id,\n [GEN_AI_RESPONSE_MODEL]: response.model,\n });\n\n if ('usage' in response && response.usage) {\n span.setAttributes(\n getTokenUsageAttributes(\n response.usage.input_tokens +\n (response.usage.cache_creation_input_tokens ?? 0) +\n (response.usage.cache_read_input_tokens ?? 0),\n response.usage.output_tokens,\n response.usage.cache_creation_input_tokens,\n response.usage.cache_read_input_tokens,\n ),\n );\n }\n }\n}\n\n/**\n * Add response attributes to spans\n */\nexport function addResponseAttributes(span: Span, response: AnthropicAiResponse, recordOutputs?: boolean): void {\n if (!response || typeof response !== 'object') return;\n\n // capture error, do not add attributes if error (they shouldn't exist)\n if ('type' in response && response.type === 'error') {\n handleResponseError(span, response);\n return;\n }\n\n // Private response attributes that are only recorded if recordOutputs is true.\n if (recordOutputs) {\n addContentAttributes(span, response);\n }\n\n // Add basic metadata attributes\n addMetadataAttributes(span, response);\n}\n\n/** Anthropic accepts the system prompt as a string or as an array of text blocks. */\nfunction systemToText(system: unknown): string | undefined {\n if (!Array.isArray(system)) {\n return typeof system === 'string' ? system : undefined;\n }\n return system\n .map(block => (isObjectLike(block) ? block.text : undefined))\n .filter(text => typeof text === 'string' && text)\n .join('\\n');\n}\n\n/**\n * Include the system prompt in the messages list, if available\n */\nexport function messagesFromParams(params: Record<string, unknown>): unknown[] {\n const { system, messages, input, prompt } = params;\n\n const systemText = systemToText(system);\n const systemMessages = systemText ? [{ role: 'system', content: systemText }] : [];\n\n const inputParamMessages = Array.isArray(input) ? input : input != null ? [input] : undefined;\n\n const messagesParamMessages = Array.isArray(messages) ? messages : messages != null ? [messages] : [];\n\n // The legacy Completions API takes a single raw `prompt` string instead of a message list. Model\n // it as one user message so it lands on `gen_ai.input.messages` like every other request shape.\n const promptMessages = prompt != null ? [{ role: 'user', content: stringify(prompt, String) }] : [];\n\n const userMessages = inputParamMessages ?? (messagesParamMessages.length ? messagesParamMessages : promptMessages);\n\n return [...systemMessages, ...userMessages];\n}\n"],"mappings":";;;;;;;;AAkBA,SAAgB,gBAAgB,UAA2B;CACzD,MAAM,OAAQ,UAAgF,SAC1F;CACJ,OAAO,OAAO,SAAS,YAAY,OAAO,OAAO;AACnD;;;;AAKA,SAAgB,sBAAsB,UAAuD;CAC3F,IAAI,MAAM,QAAQ,QAAQ,KAAK,SAAS,WAAW,GACjD,OAAO,CAAC;CAGV,MAAM,EAAE,oBAAoB,qBAAqB,0BAA0B,QAAQ;CAEnF,MAAM,aAAiD,CAAC;CACxD,IAAI,oBACF,WAAW,8BAA8B;CAE3C,WAAW,yBAAyB,UAAU,gBAAgB;CAC9D,OAAO;AACT;AAEA,MAAM,sCAAsE;CAC1E,uBAAuB;CACvB,sBAAsB;CACtB,kBAAkB;CAClB,iBAAiB;CACjB,mBAAmB;CACnB,kBAAkB;CAClB,WAAW;CACX,kBAAkB;AACpB;;;;;AAMA,SAAgB,iCAAiC,WAA+C;CAC9F,IAAI,CAAC,WACH,OAAO;CAET,OAAO,oCAAoC,cAAc;AAC3D;;;;;AAMA,SAAS,oBAAoB,MAAY,UAAqC;CAC5E,IAAI,SAAS,OAAO;EAClB,KAAK,UAAU;GAAE,MAAM;GAAmB,SAAS,iCAAiC,SAAS,MAAM,IAAI;EAAE,CAAC;EAE1G,iBAAiB,SAAS,OAAO,EAC/B,WAAW;G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M,QAAQ,MAAM,GACvB,OAAO,OAAO,WAAW,WAAW,SAAS,KAAA;CAE/C,OAAO,OACJ,KAAI,UAAU,aAAa,KAAK,IAAI,MAAM,OAAO,KAAA,CAAU,CAAC,CAC5D,QAAO,SAAQ,OAAO,SAAS,YAAY,IAAI,CAAC,CAChD,KAAK,IAAI;AACd;;;;AAKA,SAAgB,mBAAmB,QAA4C;CAC7E,MAAM,EAAE,QAAQ,UAAU,OAAO,WAAW;CAE5C,MAAM,aAAa,aAAa,MAAM;CACtC,MAAM,iBAAiB,aAAa,CAAC;EAAE,MAAM;EAAU,SAAS;CAAW,CAAC,IAAI,CAAC;CAEjF,MAAM,qBAAqB,MAAM,QAAQ,KAAK,IAAI,QAAQ,SAAS,OAAO,CAAC,KAAK,IAAI,KAAA;CAEpF,MAAM,wBAAwB,MAAM,QAAQ,QAAQ,IAAI,WAAW,YAAY,OAAO,CAAC,QAAQ,IAAI,CAAC;CAIpG,MAAM,iBAAiB,UAAU,OAAO,CAAC;EAAE,MAAM;EAAQ,SAAS,UAAU,QAAQ,MAAM;CAAE,CAAC,IAAI,CAAC;CAElG,MAAM,eAAe,uBAAuB,sBAAsB,SAAS,wBAAwB;CAEnG,OAAO,CAAC,GAAG,gBAAgB,GAAG,YAAY;AAC5C"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { DEBUG_BUILD } from "../../debug-build.js";
|
|
2
|
+
import { debug } from "@sentry/core";
|
|
3
|
+
// src/ai/core/span-hooks.ts
|
|
4
|
+
/** Runs {@link GenAiSpanHooks.onSpanStart}. */
|
|
5
|
+
function runGenAiSpanStart(hooks, span, call) {
|
|
6
|
+
const onSpanStart = hooks.onSpanStart;
|
|
7
|
+
if (onSpanStart && span.isRecording()) runGenAiSpanHook("onSpanStart", () => onSpanStart(span, call));
|
|
8
|
+
}
|
|
9
|
+
/** Runs {@link GenAiSpanHooks.onSpanEnd}. Call it right before the span ends. */
|
|
10
|
+
function runGenAiSpanEnd(hooks, span, call, result) {
|
|
11
|
+
const onSpanEnd = hooks.onSpanEnd;
|
|
12
|
+
if (onSpanEnd && span.isRecording()) runGenAiSpanHook("onSpanEnd", () => onSpanEnd(span, call, result));
|
|
13
|
+
}
|
|
14
|
+
function runGenAiSpanHook(name, hook) {
|
|
15
|
+
try {
|
|
16
|
+
hook();
|
|
17
|
+
} catch (error) {
|
|
18
|
+
DEBUG_BUILD && debug.warn(`[gen_ai] \`${name}\` threw`, error);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export { runGenAiSpanEnd, runGenAiSpanStart };
|
|
22
|
+
|
|
23
|
+
//# sourceMappingURL=span-hooks.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"span-hooks.js","names":[],"sources":["../../../../src/ai/core/span-hooks.ts"],"sourcesContent":["import { debug } from '@sentry/core';\nimport type { Span } from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\n\n/** How a gen_ai call ended, as passed to {@link GenAiSpanHooks.onSpanEnd}. */\nexport interface GenAiSpanResult<TResponse> {\n /** The response as the library returned it. `undefined` for streams and failed calls. */\n response?: TResponse;\n /** Set when the call failed. */\n error?: unknown;\n}\n\n/**\n * Hooks that let an integration's users add their own attributes to its gen_ai spans. `TCall` is the same\n * call info that `recordInputs`/`recordOutputs` get, and both hooks get the same object.\n *\n * They only run for spans that are recorded. A hook that throws is logged and does not affect the call.\n */\nexport interface GenAiSpanHooks<TCall, TResponse = unknown> {\n /**\n * Runs after the span started and the SDK set its request attributes, in the caller's async context, so\n * it can read request-scoped state.\n */\n onSpanStart?: (span: Span, call: TCall) => void;\n /**\n * Runs after the SDK set its response attributes, right before the span ends. That can be in another\n * async context than the call, for example when a stream is consumed later.\n */\n onSpanEnd?: (span: Span, call: TCall, result: GenAiSpanResult<TResponse>) => void;\n}\n\n/** Runs {@link GenAiSpanHooks.onSpanStart}. */\nexport function runGenAiSpanStart<TCall>(\n hooks: Pick<GenAiSpanHooks<TCall>, 'onSpanStart'>,\n span: Span,\n call: TCall,\n): void {\n const onSpanStart = hooks.onSpanStart;\n if (onSpanStart && span.isRecording()) {\n runGenAiSpanHook('onSpanStart', () => onSpanStart(span, call));\n }\n}\n\n/** Runs {@link GenAiSpanHooks.onSpanEnd}. Call it right before the span ends. */\nexport function runGenAiSpanEnd<TCall, TResponse>(\n hooks: GenAiSpanHooks<TCall, TResponse>,\n span: Span,\n call: TCall,\n result: GenAiSpanResult<TResponse>,\n): void {\n const onSpanEnd = hooks.onSpanEnd;\n if (onSpanEnd && span.isRecording()) {\n runGenAiSpanHook('onSpanEnd', () => onSpanEnd(span, call, result));\n }\n}\n\nfunction runGenAiSpanHook(name: string, hook: () => void): void {\n try {\n hook();\n } catch (error) {\n DEBUG_BUILD && debug.warn(`[gen_ai] \\`${name}\\` threw`, error);\n }\n}\n"],"mappings":";;;;AAgCA,SAAgB,kBACd,OACA,MACA,MACM;CACN,MAAM,cAAc,MAAM;CAC1B,IAAI,eAAe,KAAK,YAAY,GAClC,iBAAiB,qBAAqB,YAAY,MAAM,IAAI,CAAC;AAEjE;;AAGA,SAAgB,gBACd,OACA,MACA,MACA,QACM;CACN,MAAM,YAAY,MAAM;CACxB,IAAI,aAAa,KAAK,YAAY,GAChC,iBAAiB,mBAAmB,UAAU,MAAM,MAAM,MAAM,CAAC;AAErE;AAEA,SAAS,iBAAiB,MAAc,MAAwB;CAC9D,IAAI;EACF,KAAK;CACP,SAAS,OAAO;EACd,eAAe,MAAM,KAAK,cAAc,KAAK,WAAW,KAAK;CAC/D;AACF"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK } from "@sentry/conventions/attributes";
|
|
2
|
+
import { spanToJSON, timestampInSeconds } from "@sentry/core";
|
|
3
|
+
// src/ai/core/time-to-first-chunk.ts
|
|
4
|
+
/**
|
|
5
|
+
* Sets `gen_ai.response.time_to_first_chunk` on a streamed span, in seconds from the span start.
|
|
6
|
+
* Call it for each received chunk. Only the first call per span records a value.
|
|
7
|
+
*/
|
|
8
|
+
function recordTimeToFirstChunk(span) {
|
|
9
|
+
const { attributes, start_timestamp } = spanToJSON(span);
|
|
10
|
+
if (attributes[GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK] === void 0) span.setAttribute(GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK, timestampInSeconds() - start_timestamp);
|
|
11
|
+
}
|
|
12
|
+
export { recordTimeToFirstChunk };
|
|
13
|
+
|
|
14
|
+
//# sourceMappingURL=time-to-first-chunk.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"time-to-first-chunk.js","names":[],"sources":["../../../../src/ai/core/time-to-first-chunk.ts"],"sourcesContent":["import { spanToJSON, timestampInSeconds } from '@sentry/core';\nimport type { Span } from '@sentry/core';\nimport { GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK } from '@sentry/conventions/attributes';\n\n/**\n * Sets `gen_ai.response.time_to_first_chunk` on a streamed span, in seconds from the span start.\n * Call it for each received chunk. Only the first call per span records a value.\n */\nexport function recordTimeToFirstChunk(span: Span): void {\n const { attributes, start_timestamp } = spanToJSON(span);\n if (attributes[GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK] === undefined) {\n span.setAttribute(GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK, timestampInSeconds() - start_timestamp);\n }\n}\n"],"mappings":";;;;;;;AAQA,SAAgB,uBAAuB,MAAkB;CACvD,MAAM,EAAE,YAAY,oBAAoB,WAAW,IAAI;CACvD,IAAI,WAAW,yCAAyC,KAAA,GACtD,KAAK,aAAa,qCAAqC,mBAAmB,IAAI,eAAe;AAEjG"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import { DEBUG_BUILD } from "../../debug-build.js";
|
|
1
2
|
import { GEN_AI_OUTPUT_MESSAGES, GEN_AI_RESPONSE_FINISH_REASONS, GEN_AI_RESPONSE_ID, GEN_AI_RESPONSE_MODEL, GEN_AI_RESPONSE_STREAMING, GEN_AI_RESPONSE_TEXT, GEN_AI_RESPONSE_TOOL_CALLS, GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, GEN_AI_USAGE_INPUT_TOKENS, GEN_AI_USAGE_OUTPUT_TOKENS, GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, GEN_AI_USAGE_TOTAL_TOKENS } from "@sentry/conventions/attributes";
|
|
2
|
-
import { SPAN_STATUS_ERROR, getClient, isObjectLike, isThenable, stringify } from "@sentry/core";
|
|
3
|
+
import { SPAN_STATUS_ERROR, debug, getClient, isObjectLike, isThenable, stringify } from "@sentry/core";
|
|
3
4
|
import { FUNCTION } from "@sentry/conventions/op";
|
|
4
5
|
// src/ai/core/utils.ts
|
|
5
6
|
/**
|
|
@@ -26,6 +27,29 @@ function resolveAIRecordingOptions(options) {
|
|
|
26
27
|
};
|
|
27
28
|
}
|
|
28
29
|
/**
|
|
30
|
+
* Resolves the recording options of one call, like {@link resolveAIRecordingOptions}, and calls the
|
|
31
|
+
* options that are functions with `call`. Call it once when the call starts, so the functions run in the
|
|
32
|
+
* caller's async context.
|
|
33
|
+
*/
|
|
34
|
+
function resolveGenAiCallRecording(options, call) {
|
|
35
|
+
const genAI = getClient()?.getDataCollectionOptions().genAI;
|
|
36
|
+
return {
|
|
37
|
+
recordInputs: resolveRecordingOption(options?.recordInputs, call) ?? genAI?.inputs ?? true,
|
|
38
|
+
recordOutputs: resolveRecordingOption(options?.recordOutputs, call) ?? genAI?.outputs ?? true
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
/** Calls `option` with `call` when it is a function; `undefined` means the option does not decide. */
|
|
42
|
+
function resolveRecordingOption(option, call) {
|
|
43
|
+
if (typeof option !== "function") return option;
|
|
44
|
+
try {
|
|
45
|
+
const result = option(call);
|
|
46
|
+
return result === void 0 ? void 0 : result === true;
|
|
47
|
+
} catch (error) {
|
|
48
|
+
DEBUG_BUILD && debug.warn("[gen_ai] `recordInputs`/`recordOutputs` threw, not recording content", error);
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
29
53
|
* Build method path from current traversal
|
|
30
54
|
*/
|
|
31
55
|
function buildMethodPath(currentPath, prop) {
|
|
@@ -145,8 +169,9 @@ function markCancelledIfAborted(span, abortSignal) {
|
|
|
145
169
|
/**
|
|
146
170
|
* Ends a streaming span by setting all accumulated response attributes and ending the span.
|
|
147
171
|
* Shared across OpenAI, Anthropic, and Google GenAI streaming implementations.
|
|
172
|
+
* `beforeSpanEnd` runs after the attributes are set, right before the span ends.
|
|
148
173
|
*/
|
|
149
|
-
function endStreamSpan(span, state, recordOutputs) {
|
|
174
|
+
function endStreamSpan(span, state, recordOutputs, beforeSpanEnd) {
|
|
150
175
|
if (!span.isRecording()) return;
|
|
151
176
|
const attrs = { [GEN_AI_RESPONSE_STREAMING]: true };
|
|
152
177
|
if (state.responseId) attrs[GEN_AI_RESPONSE_ID] = state.responseId;
|
|
@@ -157,6 +182,7 @@ function endStreamSpan(span, state, recordOutputs) {
|
|
|
157
182
|
if (recordOutputs && state.responseTexts.length) attrs[GEN_AI_RESPONSE_TEXT] = state.responseTexts.join("");
|
|
158
183
|
if (recordOutputs && state.toolCalls.length) attrs[GEN_AI_RESPONSE_TOOL_CALLS] = JSON.stringify(state.toolCalls);
|
|
159
184
|
span.setAttributes(attrs);
|
|
185
|
+
beforeSpanEnd?.();
|
|
160
186
|
span.end();
|
|
161
187
|
}
|
|
162
188
|
/**
|
|
@@ -221,6 +247,6 @@ function wrapPromiseWithMethods(originalPromiseLike, instrumentedPromise) {
|
|
|
221
247
|
return typeof value === "function" ? value.bind(source) : value;
|
|
222
248
|
} });
|
|
223
249
|
}
|
|
224
|
-
export { buildMethodPath, endStreamSpan, extractSystemInstructions, getErrorStatus, getEvaluationInputMessages, getEvaluationOutputMessages, getGenAiSpanOp, getRequestSignal, getTokenUsageAttributes, isCallerAbort, isReadableStream, markCancelledIfAborted, resolveAIRecordingOptions, setOutputMessagesAttribute, wrapPromiseWithMethods };
|
|
250
|
+
export { buildMethodPath, endStreamSpan, extractSystemInstructions, getErrorStatus, getEvaluationInputMessages, getEvaluationOutputMessages, getGenAiSpanOp, getRequestSignal, getTokenUsageAttributes, isCallerAbort, isReadableStream, markCancelledIfAborted, resolveAIRecordingOptions, resolveGenAiCallRecording, resolveRecordingOption, setOutputMessagesAttribute, wrapPromiseWithMethods };
|
|
225
251
|
|
|
226
252
|
//# sourceMappingURL=utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":[],"sources":["../../../../src/ai/core/utils.ts"],"sourcesContent":["/* eslint-disable typescript-eslint/no-deprecated */\n/**\n * Shared utils for AI integrations (OpenAI, Anthropic, Verce.AI, etc.)\n */\nimport { getClient, isObjectLike, isThenable, SPAN_STATUS_ERROR, stringify } from '@sentry/core';\nimport type { Span, SpanStatus } from '@sentry/core';\nimport {\n GEN_AI_OUTPUT_MESSAGES,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_STREAMING,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n} from '@sentry/conventions/attributes';\nimport { FUNCTION } from '@sentry/conventions/op';\n\nexport interface GenAiOptions {\n /**\n * Record input messages/prompts on gen_ai spans. Defaults to the global\n * `dataCollection.genAI.inputs` setting; an explicit value here takes precedence.\n */\n recordInputs?: boolean;\n /**\n * Record output text/responses on gen_ai spans. Defaults to the global\n * `dataCollection.genAI.outputs` setting; an explicit value here takes precedence.\n */\n recordOutputs?: boolean;\n}\n\n/**\n * A method registry entry describes a single instrumented method:\n * which gen_ai operation it maps to and whether it is intrinsically streaming.\n */\nexport interface InstrumentedMethodEntry {\n /** Operation name (e.g. 'chat', 'embeddings', 'generate_content'). Omit for factory methods that only need result proxying. */\n operation?: string;\n /** True if the method itself is always streaming (not param-based) */\n streaming?: boolean;\n /** When set, the method's return value is re-proxied with this as the base path */\n proxyResultPath?: string;\n}\n\n/**\n * Maps method paths to their registry entries.\n * Used by proxy-based AI client instrumentations to determine which methods\n * to instrument, what operation name to use, and whether they stream.\n */\nexport type InstrumentedMethodRegistry = Record<string, InstrumentedMethodEntry>;\n\n// Operation names that are not inference calls: `unknown` is the fallback for methods with no\n// registered operation. It should not surface as a `gen_ai.*` op (an unknown string must not\n// masquerade as a convention), so it maps to the generic `function` op. The operation name itself\n// is preserved on `gen_ai.operation.name`.\nconst NON_INFERENCE_OPERATIONS = new Set(['unknown']);\n\n/**\n * Derive the span op from a gen_ai operation name. Inference operations become `gen_ai.<operation>`;\n * non-inference operations (`unknown`) become the generic `function` op.\n */\nexport function getGenAiSpanOp(operationName: string): string {\n return NON_INFERENCE_OPERATIONS.has(operationName) ? FUNCTION : `gen_ai.${operationName}`;\n}\n\n/**\n * Resolves AI recording options by falling back to the client's `dataCollection.genAI` settings.\n * Precedence: explicit option > dataCollection.genAI > true (genAI data collected by default)\n */\nexport function resolveAIRecordingOptions<T extends GenAiOptions>(options?: T): T & Required<GenAiOptions> {\n const genAI = getClient()?.getDataCollectionOptions().genAI;\n return {\n ...options,\n recordInputs: options?.recordInputs ?? genAI?.inputs ?? true,\n recordOutputs: options?.recordOutputs ?? genAI?.outputs ?? true,\n } as T & Required<GenAiOptions>;\n}\n\n/**\n * Build method path from current traversal\n */\nexport function buildMethodPath(currentPath: string, prop: string): string {\n return currentPath ? `${currentPath}.${prop}` : prop;\n}\n\n/**\n * A minimal structural check for a web `ReadableStream`.\n *\n * The chunk type is the caller's assumption about the provider's stream (e.g. `Uint8Array` for SSE\n * byte streams); the check itself only looks for the `ReadableStream` methods we rely on.\n */\nexport function isReadableStream<T = unknown>(value: unknown): value is ReadableStream<T> {\n return (\n isObjectLike(value) &&\n typeof (value as { pipeThrough?: unknown }).pipeThrough === 'function' &&\n typeof (value as { getReader?: unknown }).getReader === 'function'\n );\n}\n\n/**\n * Build token usage attributes. Input tokens include cache reads and writes, which are subsets.\n */\nexport function getTokenUsageAttributes(\n promptTokens?: number,\n completionTokens?: number,\n cacheCreationInputTokens?: number,\n cacheReadInputTokens?: number,\n totalTokens?: number,\n): Record<string, number> {\n const attributes: Record<string, number> = {};\n\n if (typeof promptTokens === 'number') {\n attributes[GEN_AI_USAGE_INPUT_TOKENS] = promptTokens;\n }\n if (typeof cacheCreationInputTokens === 'number') {\n attributes[GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS] = cacheCreationInputTokens;\n }\n if (typeof cacheReadInputTokens === 'number') {\n attributes[GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS] = cacheReadInputTokens;\n }\n if (typeof completionTokens === 'number') {\n attributes[GEN_AI_USAGE_OUTPUT_TOKENS] = completionTokens;\n }\n if (typeof totalTokens === 'number') {\n attributes[GEN_AI_USAGE_TOTAL_TOKENS] = totalTokens;\n } else if (typeof promptTokens === 'number' || typeof completionTokens === 'number') {\n attributes[GEN_AI_USAGE_TOTAL_TOKENS] =\n (typeof promptTokens === 'number' ? promptTokens : 0) +\n (typeof completionTokens === 'number' ? completionTokens : 0);\n }\n return attributes;\n}\n\n/** Serialize the `state` and `questions` of an evaluation request (TypeSafe, Workers AI, Mastra classifiers). */\nexport function getEvaluationInputMessages(request: Record<string, unknown>): string | undefined {\n return stringify([{ type: 'evaluation', state: request.state, questions: request.questions }]);\n}\n\n/** Serialize the `answers` of an evaluation result (TypeSafe, Workers AI, Mastra classifiers). */\nexport function getEvaluationOutputMessages(answers: unknown): string | undefined {\n return stringify([{ type: 'evaluation', answers }]);\n}\n\n/** One assistant turn for {@link setOutputMessagesAttribute}. */\nexport interface GenAiOutputMessage {\n /** The message's text content, already flattened out of any content-part array. */\n responseText?: string;\n /** Tool calls in either the OpenAI-compatible (`function.name`) or flat (`name`) shape. */\n toolCalls?: unknown[];\n /** Recorded as `finish_reason` on the message, per the `gen_ai.output.messages` schema. */\n finishReason?: string;\n}\n\n/**\n * Build the `gen_ai.output.messages` value (assistant messages with text and/or tool-call parts).\n *\n * We set this in addition to the deprecated `gen_ai.response.text` / `gen_ai.response.tool_calls`\n * attributes because Sentry's product reads the model output from `gen_ai.output.messages` first.\n * Relay migrates `gen_ai.response.text` into `gen_ai.output.messages`, but the tool-calls half of\n * that migration is lossy — so tool-call turns would otherwise render an empty Output.\n *\n * Pass an array for providers that can return more than one choice per response; a single object is\n * the common case of one assistant turn.\n */\nexport function setOutputMessagesAttribute(span: Span, messages: GenAiOutputMessage | GenAiOutputMessage[]): void {\n const serialized = (Array.isArray(messages) ? messages : [messages])\n .map(buildOutputMessage)\n .filter((message): message is Record<string, unknown> => !!message);\n\n if (serialized.length > 0) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, JSON.stringify(serialized));\n }\n}\n\nfunction buildOutputMessage({\n responseText,\n toolCalls,\n finishReason,\n}: GenAiOutputMessage): Record<string, unknown> | undefined {\n const parts: Array<Record<string, unknown>> = [];\n\n if (typeof responseText === 'string' && responseText.length > 0) {\n parts.push({ type: 'text', content: responseText });\n }\n\n if (Array.isArray(toolCalls)) {\n for (const toolCall of toolCalls) {\n if (!toolCall || typeof toolCall !== 'object') {\n continue;\n }\n const call = toolCall as {\n id?: unknown;\n function?: { name?: unknown; arguments?: unknown };\n name?: unknown;\n arguments?: unknown;\n };\n // Normalize both the OpenAI-compatible shape (name/arguments nested under `function`)\n // and the flat shape some providers use.\n const name = call.function?.name ?? call.name;\n const args = call.function?.arguments ?? call.arguments;\n parts.push({\n type: 'tool_call',\n id: call.id,\n name,\n arguments: stringify(args ?? {}, String),\n });\n }\n }\n\n if (parts.length === 0) {\n return undefined;\n }\n\n return finishReason ? { role: 'assistant', parts, finish_reason: finishReason } : { role: 'assistant', parts };\n}\n\nexport interface StreamResponseState {\n responseId?: string;\n responseModel?: string;\n finishReasons: string[];\n responseTexts: string[];\n toolCalls: unknown[];\n promptTokens?: number;\n completionTokens?: number;\n totalTokens?: number;\n cacheCreationInputTokens?: number;\n cacheReadInputTokens?: number;\n reasoningOutputTokens?: number;\n}\n\n/**\n * Reads `signal` from the request options OpenAI and Anthropic take as their second argument.\n */\nexport function getRequestSignal(requestOptions: unknown): AbortSignal | undefined {\n return isObjectLike(requestOptions) ? (requestOptions.signal as AbortSignal | undefined) : undefined;\n}\n\n/**\n * Checks the signal rather than the error name, because SDK timeouts also throw an `AbortError`. A caller's\n * own `AbortSignal.timeout()` is a timeout too, not a cancellation.\n */\nexport function isCallerAbort(abortSignal: AbortSignal | undefined): boolean {\n return !!abortSignal?.aborted && (abortSignal.reason as { name?: unknown } | undefined)?.name !== 'TimeoutError';\n}\n\n/**\n * A caller's abort is `cancelled`, anything else `internal_error`.\n */\nexport function getErrorStatus(abortSignal: AbortSignal | undefined): SpanStatus {\n return { code: SPAN_STATUS_ERROR, message: isCallerAbort(abortSignal) ? 'cancelled' : 'internal_error' };\n}\n\n/**\n * Overrides the status of a span whose call the caller aborted.\n */\nexport function markCancelledIfAborted(span: Span, abortSignal: AbortSignal | undefined): void {\n if (isCallerAbort(abortSignal)) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n }\n}\n\n/**\n * Ends a streaming span by setting all accumulated response attributes and ending the span.\n * Shared across OpenAI, Anthropic, and Google GenAI streaming implementations.\n */\nexport function endStreamSpan(span: Span, state: StreamResponseState, recordOutputs: boolean): void {\n if (!span.isRecording()) {\n return;\n }\n\n const attrs: Record<string, string | number | boolean> = {\n [GEN_AI_RESPONSE_STREAMING]: true,\n };\n\n if (state.responseId) attrs[GEN_AI_RESPONSE_ID] = state.responseId;\n if (state.responseModel) attrs[GEN_AI_RESPONSE_MODEL] = state.responseModel;\n\n Object.assign(\n attrs,\n getTokenUsageAttributes(\n state.promptTokens,\n state.completionTokens,\n state.cacheCreationInputTokens,\n state.cacheReadInputTokens,\n state.totalTokens,\n ),\n );\n if (typeof state.reasoningOutputTokens === 'number') {\n attrs[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS] = state.reasoningOutputTokens;\n }\n\n if (state.finishReasons.length) {\n attrs[GEN_AI_RESPONSE_FINISH_REASONS] = JSON.stringify(state.finishReasons);\n }\n if (recordOutputs && state.responseTexts.length) {\n attrs[GEN_AI_RESPONSE_TEXT] = state.responseTexts.join('');\n }\n if (recordOutputs && state.toolCalls.length) {\n attrs[GEN_AI_RESPONSE_TOOL_CALLS] = JSON.stringify(state.toolCalls);\n }\n\n span.setAttributes(attrs);\n span.end();\n}\n\n/**\n * Extract system instructions from messages array.\n * Finds the first system message and formats it according to OpenTelemetry semantic conventions.\n *\n * @param messages - Array of messages to extract system instructions from\n * @returns systemInstructions (JSON string) and filteredMessages (without system message)\n */\nexport function extractSystemInstructions(messages: unknown[] | unknown): {\n systemInstructions: string | undefined;\n filteredMessages: unknown[] | unknown;\n} {\n if (!Array.isArray(messages)) {\n return { systemInstructions: undefined, filteredMessages: messages };\n }\n\n const systemMessageIndex = messages.findIndex(\n msg => msg && typeof msg === 'object' && 'role' in msg && (msg as { role: string }).role === 'system',\n );\n\n if (systemMessageIndex === -1) {\n return { systemInstructions: undefined, filteredMessages: messages };\n }\n\n const systemMessage = messages[systemMessageIndex] as { role: string; content?: string | unknown };\n const systemContent =\n typeof systemMessage.content === 'string'\n ? systemMessage.content\n : systemMessage.content !== undefined\n ? JSON.stringify(systemMessage.content)\n : undefined;\n\n if (!systemContent) {\n return { systemInstructions: undefined, filteredMessages: messages };\n }\n\n const systemInstructions = JSON.stringify([{ type: 'text', content: systemContent }]);\n const filteredMessages = [...messages.slice(0, systemMessageIndex), ...messages.slice(systemMessageIndex + 1)];\n\n return { systemInstructions, filteredMessages };\n}\n\n/**\n * Creates a wrapped version of .withResponse() that replaces the data field\n * with the instrumented result while preserving metadata (response, request_id).\n */\nasync function createWithResponseWrapper<T>(\n originalWithResponse: Promise<unknown>,\n instrumentedPromise: Promise<T>,\n): Promise<unknown> {\n // Awaited together rather than in sequence so both promises get a handler attached synchronously.\n // Awaiting them one after the other leaves the second unobserved when the first rejects, which\n // surfaces as an unhandled rejection.\n const [instrumentedResult, originalWrapper] = await Promise.all([instrumentedPromise, originalWithResponse]);\n\n // Combine instrumented result with original metadata\n if (originalWrapper && typeof originalWrapper === 'object' && 'data' in originalWrapper) {\n return {\n ...originalWrapper,\n data: instrumentedResult,\n };\n }\n return instrumentedResult;\n}\n\n/**\n * Wraps a promise-like object to preserve additional methods (like .withResponse())\n * that AI SDK clients (OpenAI, Anthropic) attach to their APIPromise return values.\n *\n * Standard Promise methods (.then, .catch, .finally) are routed to the instrumented\n * promise to preserve Sentry's span instrumentation, while custom SDK methods are\n * forwarded to the original promise to maintain the SDK's API surface.\n */\nexport function wrapPromiseWithMethods<R>(\n originalPromiseLike: Promise<R>,\n instrumentedPromise: Promise<R>,\n): Promise<R> {\n // If the original result is not thenable, return the instrumented promise\n if (!isThenable(originalPromiseLike)) {\n return instrumentedPromise;\n }\n\n // Create a proxy that forwards Promise methods to instrumentedPromise\n // and preserves additional methods from the original result\n return new Proxy(originalPromiseLike, {\n get(target: object, prop: string | symbol): unknown {\n // For standard Promise methods (.then, .catch, .finally, Symbol.toStringTag),\n // use instrumentedPromise to preserve Sentry instrumentation.\n // For custom methods (like .withResponse()), use the original target.\n const useInstrumentedPromise = prop in Promise.prototype || prop === Symbol.toStringTag;\n const source = useInstrumentedPromise ? instrumentedPromise : target;\n\n const value = Reflect.get(source, prop) as unknown;\n\n // Special handling for .withResponse() to preserve instrumentation\n // .withResponse() returns { data: T, response: Response, request_id: string }\n if (prop === 'withResponse' && typeof value === 'function') {\n return function wrappedWithResponse(this: unknown): unknown {\n const originalWithResponse = (value as (...args: unknown[]) => unknown).call(target);\n return createWithResponseWrapper(originalWithResponse, instrumentedPromise);\n };\n }\n\n return typeof value === 'function' ? value.bind(source) : value;\n },\n }) as Promise<R>;\n}\n"],"mappings":";;;;;;;AA4DA,MAAM,2CAA2B,IAAI,IAAI,CAAC,SAAS,CAAC;;;;;AAMpD,SAAgB,eAAe,eAA+B;CAC5D,OAAO,yBAAyB,IAAI,aAAa,IAAI,WAAW,UAAU;AAC5E;;;;;AAMA,SAAgB,0BAAkD,SAAyC;CACzG,MAAM,QAAQ,UAAU,CAAC,EAAE,yBAAyB,CAAC,CAAC;CACtD,OAAO;EACL,GAAG;EACH,cAAc,SAAS,gBAAgB,OAAO,UAAU;EACxD,eAAe,SAAS,iBAAiB,OAAO,WAAW;CAC7D;AACF;;;;AAKA,SAAgB,gBAAgB,aAAqB,MAAsB;CACzE,OAAO,cAAc,GAAG,YAAY,GAAG,SAAS;AAClD;;;;;;;AAQA,SAAgB,iBAA8B,OAA4C;CACxF,OACE,aAAa,KAAK,KAClB,OAAQ,MAAoC,gBAAgB,cAC5D,OAAQ,MAAkC,cAAc;AAE5D;;;;AAKA,SAAgB,wBACd,cACA,kBACA,0BACA,sBACA,aACwB;CACxB,MAAM,aAAqC,CAAC;CAE5C,IAAI,OAAO,iBAAiB,UAC1B,WAAW,6BAA6B;CAE1C,IAAI,OAAO,6BAA6B,UACtC,WAAW,4CAA4C;CAEzD,IAAI,OAAO,yBAAyB,UAClC,WAAW,wCAAwC;CAErD,IAAI,OAAO,qBAAqB,UAC9B,WAAW,8BAA8B;CAE3C,IAAI,OAAO,gBAAgB,UACzB,WAAW,6BAA6B;MACnC,IAAI,OAAO,iBAAiB,YAAY,OAAO,qBAAqB,UACzE,WAAW,8BACR,OAAO,iBAAiB,WAAW,eAAe,MAClD,OAAO,qBAAqB,WAAW,mBAAmB;CAE/D,OAAO;AACT;;AAGA,SAAgB,2BAA2B,SAAsD;CAC/F,OAAO,UAAU,CAAC;EAAE,M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,WAC7B,cAAc,UACd,cAAc,YAAY,KAAA,IACxB,KAAK,UAAU,cAAc,OAAO,IACpC,KAAA;CAER,IAAI,CAAC,eACH,OAAO;EAAE,oBAAoB,KAAA;EAAW,kBAAkB;CAAS;CAMrE,OAAO;EAAE,oBAHkB,KAAK,UAAU,CAAC;GAAE,MAAM;GAAQ,SAAS;EAAc,CAAC,CAGzD;EAAG,kBAAA,CAFH,GAAG,SAAS,MAAM,GAAG,kBAAkB,GAAG,GAAG,SAAS,MAAM,qBAAqB,CAAC,CAEhE;CAAE;AAChD;;;;;AAMA,eAAe,0BACb,sBACA,qBACkB;CAIlB,MAAM,CAAC,oBAAoB,mBAAmB,MAAM,QAAQ,IAAI,CAAC,qBAAqB,oBAAoB,CAAC;CAG3G,IAAI,mBAAmB,OAAO,oBAAoB,YAAY,UAAU,iBACtE,OAAO;EACL,GAAG;EACH,MAAM;CACR;CAEF,OAAO;AACT;;;;;;;;;AAUA,SAAgB,uBACd,qBACA,qBACY;CAEZ,IAAI,CAAC,WAAW,mBAAmB,GACjC,OAAO;CAKT,OAAO,IAAI,MAAM,qBAAqB,EACpC,IAAI,QAAgB,MAAgC;EAKlD,MAAM,SADyB,QAAQ,QAAQ,aAAa,SAAS,OAAO,cACpC,sBAAsB;EAE9D,MAAM,QAAQ,QAAQ,IAAI,QAAQ,IAAI;EAItC,IAAI,SAAS,kBAAkB,OAAO,UAAU,YAC9C,OAAO,SAAS,sBAA4C;GAE1D,OAAO,0BADuB,MAA0C,KAAK,MACzB,GAAG,mBAAmB;EAC5E;EAGF,OAAO,OAAO,UAAU,aAAa,MAAM,KAAK,MAAM,IAAI;CAC5D,EACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"utils.js","names":[],"sources":["../../../../src/ai/core/utils.ts"],"sourcesContent":["/* eslint-disable typescript-eslint/no-deprecated */\n/**\n * Shared utils for AI integrations (OpenAI, Anthropic, Verce.AI, etc.)\n */\nimport { debug, getClient, isObjectLike, isThenable, SPAN_STATUS_ERROR, stringify } from '@sentry/core';\nimport type { Span, SpanStatus } from '@sentry/core';\nimport {\n GEN_AI_OUTPUT_MESSAGES,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_STREAMING,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n} from '@sentry/conventions/attributes';\nimport { FUNCTION } from '@sentry/conventions/op';\nimport { DEBUG_BUILD } from '../../debug-build';\n\nexport interface GenAiOptions {\n /**\n * Record input messages/prompts on gen_ai spans. Defaults to the global\n * `dataCollection.genAI.inputs` setting; an explicit value here takes precedence.\n */\n recordInputs?: boolean;\n /**\n * Record output text/responses on gen_ai spans. Defaults to the global\n * `dataCollection.genAI.outputs` setting; an explicit value here takes precedence.\n */\n recordOutputs?: boolean;\n}\n\n/**\n * Whether to record the content of a gen_ai call: a boolean for every call, or a function that decides for\n * each call. The function runs once when the call starts, in the caller's async context, so it can read\n * request-scoped state. Returning `undefined` falls back to `dataCollection.genAI`. If it throws, the\n * content is not recorded.\n */\nexport type GenAiRecordingOption<TCall> = boolean | ((call: TCall) => boolean | undefined);\n\n/** {@link GenAiOptions} of an integration that can decide per call. `TCall` is what the function gets. */\nexport interface GenAiCallOptions<TCall> {\n /**\n * Record input messages/prompts on gen_ai spans. Defaults to the global\n * `dataCollection.genAI.inputs` setting; an explicit value here takes precedence.\n */\n recordInputs?: GenAiRecordingOption<TCall>;\n /**\n * Record output text/responses on gen_ai spans. Defaults to the global\n * `dataCollection.genAI.outputs` setting; an explicit value here takes precedence.\n */\n recordOutputs?: GenAiRecordingOption<TCall>;\n}\n\n/**\n * A method registry entry describes a single instrumented method:\n * which gen_ai operation it maps to and whether it is intrinsically streaming.\n */\nexport interface InstrumentedMethodEntry {\n /** Operation name (e.g. 'chat', 'embeddings', 'generate_content'). Omit for factory methods that only need result proxying. */\n operation?: string;\n /** True if the method itself is always streaming (not param-based) */\n streaming?: boolean;\n /** When set, the method's return value is re-proxied with this as the base path */\n proxyResultPath?: string;\n}\n\n/**\n * Maps method paths to their registry entries.\n * Used by proxy-based AI client instrumentations to determine which methods\n * to instrument, what operation name to use, and whether they stream.\n */\nexport type InstrumentedMethodRegistry = Record<string, InstrumentedMethodEntry>;\n\n// Operation names that are not inference calls: `unknown` is the fallback for methods with no\n// registered operation. It should not surface as a `gen_ai.*` op (an unknown string must not\n// masquerade as a convention), so it maps to the generic `function` op. The operation name itself\n// is preserved on `gen_ai.operation.name`.\nconst NON_INFERENCE_OPERATIONS = new Set(['unknown']);\n\n/**\n * Derive the span op from a gen_ai operation name. Inference operations become `gen_ai.<operation>`;\n * non-inference operations (`unknown`) become the generic `function` op.\n */\nexport function getGenAiSpanOp(operationName: string): string {\n return NON_INFERENCE_OPERATIONS.has(operationName) ? FUNCTION : `gen_ai.${operationName}`;\n}\n\n/**\n * Resolves AI recording options by falling back to the client's `dataCollection.genAI` settings.\n * Precedence: explicit option > dataCollection.genAI > true (genAI data collected by default)\n */\nexport function resolveAIRecordingOptions<T extends GenAiOptions>(options?: T): T & Required<GenAiOptions> {\n const genAI = getClient()?.getDataCollectionOptions().genAI;\n return {\n ...options,\n recordInputs: options?.recordInputs ?? genAI?.inputs ?? true,\n recordOutputs: options?.recordOutputs ?? genAI?.outputs ?? true,\n } as T & Required<GenAiOptions>;\n}\n\n/**\n * Resolves the recording options of one call, like {@link resolveAIRecordingOptions}, and calls the\n * options that are functions with `call`. Call it once when the call starts, so the functions run in the\n * caller's async context.\n */\nexport function resolveGenAiCallRecording<TCall>(\n options: GenAiCallOptions<TCall> | undefined,\n call: TCall,\n): Required<GenAiOptions> {\n const genAI = getClient()?.getDataCollectionOptions().genAI;\n return {\n recordInputs: resolveRecordingOption(options?.recordInputs, call) ?? genAI?.inputs ?? true,\n recordOutputs: resolveRecordingOption(options?.recordOutputs, call) ?? genAI?.outputs ?? true,\n };\n}\n\n/** Calls `option` with `call` when it is a function; `undefined` means the option does not decide. */\nexport function resolveRecordingOption<TCall>(\n option: GenAiRecordingOption<TCall> | undefined,\n call: TCall,\n): boolean | undefined {\n if (typeof option !== 'function') {\n return option;\n }\n try {\n const result = option(call);\n return result === undefined ? undefined : result === true;\n } catch (error) {\n DEBUG_BUILD && debug.warn('[gen_ai] `recordInputs`/`recordOutputs` threw, not recording content', error);\n return false;\n }\n}\n\n/**\n * Build method path from current traversal\n */\nexport function buildMethodPath(currentPath: string, prop: string): string {\n return currentPath ? `${currentPath}.${prop}` : prop;\n}\n\n/**\n * A minimal structural check for a web `ReadableStream`.\n *\n * The chunk type is the caller's assumption about the provider's stream (e.g. `Uint8Array` for SSE\n * byte streams); the check itself only looks for the `ReadableStream` methods we rely on.\n */\nexport function isReadableStream<T = unknown>(value: unknown): value is ReadableStream<T> {\n return (\n isObjectLike(value) &&\n typeof (value as { pipeThrough?: unknown }).pipeThrough === 'function' &&\n typeof (value as { getReader?: unknown }).getReader === 'function'\n );\n}\n\n/**\n * Build token usage attributes. Input tokens include cache reads and writes, which are subsets.\n */\nexport function getTokenUsageAttributes(\n promptTokens?: number,\n completionTokens?: number,\n cacheCreationInputTokens?: number,\n cacheReadInputTokens?: number,\n totalTokens?: number,\n): Record<string, number> {\n const attributes: Record<string, number> = {};\n\n if (typeof promptTokens === 'number') {\n attributes[GEN_AI_USAGE_INPUT_TOKENS] = promptTokens;\n }\n if (typeof cacheCreationInputTokens === 'number') {\n attributes[GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS] = cacheCreationInputTokens;\n }\n if (typeof cacheReadInputTokens === 'number') {\n attributes[GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS] = cacheReadInputTokens;\n }\n if (typeof completionTokens === 'number') {\n attributes[GEN_AI_USAGE_OUTPUT_TOKENS] = completionTokens;\n }\n if (typeof totalTokens === 'number') {\n attributes[GEN_AI_USAGE_TOTAL_TOKENS] = totalTokens;\n } else if (typeof promptTokens === 'number' || typeof completionTokens === 'number') {\n attributes[GEN_AI_USAGE_TOTAL_TOKENS] =\n (typeof promptTokens === 'number' ? promptTokens : 0) +\n (typeof completionTokens === 'number' ? completionTokens : 0);\n }\n return attributes;\n}\n\n/** Serialize the `state` and `questions` of an evaluation request (TypeSafe, Workers AI, Mastra classifiers). */\nexport function getEvaluationInputMessages(request: Record<string, unknown>): string | undefined {\n return stringify([{ type: 'evaluation', state: request.state, questions: request.questions }]);\n}\n\n/** Serialize the `answers` of an evaluation result (TypeSafe, Workers AI, Mastra classifiers). */\nexport function getEvaluationOutputMessages(answers: unknown): string | undefined {\n return stringify([{ type: 'evaluation', answers }]);\n}\n\n/** One assistant turn for {@link setOutputMessagesAttribute}. */\nexport interface GenAiOutputMessage {\n /** The message's text content, already flattened out of any content-part array. */\n responseText?: string;\n /** Tool calls in either the OpenAI-compatible (`function.name`) or flat (`name`) shape. */\n toolCalls?: unknown[];\n /** Recorded as `finish_reason` on the message, per the `gen_ai.output.messages` schema. */\n finishReason?: string;\n}\n\n/**\n * Build the `gen_ai.output.messages` value (assistant messages with text and/or tool-call parts).\n *\n * We set this in addition to the deprecated `gen_ai.response.text` / `gen_ai.response.tool_calls`\n * attributes because Sentry's product reads the model output from `gen_ai.output.messages` first.\n * Relay migrates `gen_ai.response.text` into `gen_ai.output.messages`, but the tool-calls half of\n * that migration is lossy — so tool-call turns would otherwise render an empty Output.\n *\n * Pass an array for providers that can return more than one choice per response; a single object is\n * the common case of one assistant turn.\n */\nexport function setOutputMessagesAttribute(span: Span, messages: GenAiOutputMessage | GenAiOutputMessage[]): void {\n const serialized = (Array.isArray(messages) ? messages : [messages])\n .map(buildOutputMessage)\n .filter((message): message is Record<string, unknown> => !!message);\n\n if (serialized.length > 0) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, JSON.stringify(serialized));\n }\n}\n\nfunction buildOutputMessage({\n responseText,\n toolCalls,\n finishReason,\n}: GenAiOutputMessage): Record<string, unknown> | undefined {\n const parts: Array<Record<string, unknown>> = [];\n\n if (typeof responseText === 'string' && responseText.length > 0) {\n parts.push({ type: 'text', content: responseText });\n }\n\n if (Array.isArray(toolCalls)) {\n for (const toolCall of toolCalls) {\n if (!toolCall || typeof toolCall !== 'object') {\n continue;\n }\n const call = toolCall as {\n id?: unknown;\n function?: { name?: unknown; arguments?: unknown };\n name?: unknown;\n arguments?: unknown;\n };\n // Normalize both the OpenAI-compatible shape (name/arguments nested under `function`)\n // and the flat shape some providers use.\n const name = call.function?.name ?? call.name;\n const args = call.function?.arguments ?? call.arguments;\n parts.push({\n type: 'tool_call',\n id: call.id,\n name,\n arguments: stringify(args ?? {}, String),\n });\n }\n }\n\n if (parts.length === 0) {\n return undefined;\n }\n\n return finishReason ? { role: 'assistant', parts, finish_reason: finishReason } : { role: 'assistant', parts };\n}\n\nexport interface StreamResponseState {\n responseId?: string;\n responseModel?: string;\n finishReasons: string[];\n responseTexts: string[];\n toolCalls: unknown[];\n promptTokens?: number;\n completionTokens?: number;\n totalTokens?: number;\n cacheCreationInputTokens?: number;\n cacheReadInputTokens?: number;\n reasoningOutputTokens?: number;\n}\n\n/**\n * Reads `signal` from the request options OpenAI and Anthropic take as their second argument.\n */\nexport function getRequestSignal(requestOptions: unknown): AbortSignal | undefined {\n return isObjectLike(requestOptions) ? (requestOptions.signal as AbortSignal | undefined) : undefined;\n}\n\n/**\n * Checks the signal rather than the error name, because SDK timeouts also throw an `AbortError`. A caller's\n * own `AbortSignal.timeout()` is a timeout too, not a cancellation.\n */\nexport function isCallerAbort(abortSignal: AbortSignal | undefined): boolean {\n return !!abortSignal?.aborted && (abortSignal.reason as { name?: unknown } | undefined)?.name !== 'TimeoutError';\n}\n\n/**\n * A caller's abort is `cancelled`, anything else `internal_error`.\n */\nexport function getErrorStatus(abortSignal: AbortSignal | undefined): SpanStatus {\n return { code: SPAN_STATUS_ERROR, message: isCallerAbort(abortSignal) ? 'cancelled' : 'internal_error' };\n}\n\n/**\n * Overrides the status of a span whose call the caller aborted.\n */\nexport function markCancelledIfAborted(span: Span, abortSignal: AbortSignal | undefined): void {\n if (isCallerAbort(abortSignal)) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n }\n}\n\n/**\n * Ends a streaming span by setting all accumulated response attributes and ending the span.\n * Shared across OpenAI, Anthropic, and Google GenAI streaming implementations.\n * `beforeSpanEnd` runs after the attributes are set, right before the span ends.\n */\nexport function endStreamSpan(\n span: Span,\n state: StreamResponseState,\n recordOutputs: boolean,\n beforeSpanEnd?: () => void,\n): void {\n if (!span.isRecording()) {\n return;\n }\n\n const attrs: Record<string, string | number | boolean> = {\n [GEN_AI_RESPONSE_STREAMING]: true,\n };\n\n if (state.responseId) attrs[GEN_AI_RESPONSE_ID] = state.responseId;\n if (state.responseModel) attrs[GEN_AI_RESPONSE_MODEL] = state.responseModel;\n\n Object.assign(\n attrs,\n getTokenUsageAttributes(\n state.promptTokens,\n state.completionTokens,\n state.cacheCreationInputTokens,\n state.cacheReadInputTokens,\n state.totalTokens,\n ),\n );\n if (typeof state.reasoningOutputTokens === 'number') {\n attrs[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS] = state.reasoningOutputTokens;\n }\n\n if (state.finishReasons.length) {\n attrs[GEN_AI_RESPONSE_FINISH_REASONS] = JSON.stringify(state.finishReasons);\n }\n if (recordOutputs && state.responseTexts.length) {\n attrs[GEN_AI_RESPONSE_TEXT] = state.responseTexts.join('');\n }\n if (recordOutputs && state.toolCalls.length) {\n attrs[GEN_AI_RESPONSE_TOOL_CALLS] = JSON.stringify(state.toolCalls);\n }\n\n span.setAttributes(attrs);\n beforeSpanEnd?.();\n span.end();\n}\n\n/**\n * Extract system instructions from messages array.\n * Finds the first system message and formats it according to OpenTelemetry semantic conventions.\n *\n * @param messages - Array of messages to extract system instructions from\n * @returns systemInstructions (JSON string) and filteredMessages (without system message)\n */\nexport function extractSystemInstructions(messages: unknown[] | unknown): {\n systemInstructions: string | undefined;\n filteredMessages: unknown[] | unknown;\n} {\n if (!Array.isArray(messages)) {\n return { systemInstructions: undefined, filteredMessages: messages };\n }\n\n const systemMessageIndex = messages.findIndex(\n msg => msg && typeof msg === 'object' && 'role' in msg && (msg as { role: string }).role === 'system',\n );\n\n if (systemMessageIndex === -1) {\n return { systemInstructions: undefined, filteredMessages: messages };\n }\n\n const systemMessage = messages[systemMessageIndex] as { role: string; content?: string | unknown };\n const systemContent =\n typeof systemMessage.content === 'string'\n ? systemMessage.content\n : systemMessage.content !== undefined\n ? JSON.stringify(systemMessage.content)\n : undefined;\n\n if (!systemContent) {\n return { systemInstructions: undefined, filteredMessages: messages };\n }\n\n const systemInstructions = JSON.stringify([{ type: 'text', content: systemContent }]);\n const filteredMessages = [...messages.slice(0, systemMessageIndex), ...messages.slice(systemMessageIndex + 1)];\n\n return { systemInstructions, filteredMessages };\n}\n\n/**\n * Creates a wrapped version of .withResponse() that replaces the data field\n * with the instrumented result while preserving metadata (response, request_id).\n */\nasync function createWithResponseWrapper<T>(\n originalWithResponse: Promise<unknown>,\n instrumentedPromise: Promise<T>,\n): Promise<unknown> {\n // Awaited together rather than in sequence so both promises get a handler attached synchronously.\n // Awaiting them one after the other leaves the second unobserved when the first rejects, which\n // surfaces as an unhandled rejection.\n const [instrumentedResult, originalWrapper] = await Promise.all([instrumentedPromise, originalWithResponse]);\n\n // Combine instrumented result with original metadata\n if (originalWrapper && typeof originalWrapper === 'object' && 'data' in originalWrapper) {\n return {\n ...originalWrapper,\n data: instrumentedResult,\n };\n }\n return instrumentedResult;\n}\n\n/**\n * Wraps a promise-like object to preserve additional methods (like .withResponse())\n * that AI SDK clients (OpenAI, Anthropic) attach to their APIPromise return values.\n *\n * Standard Promise methods (.then, .catch, .finally) are routed to the instrumented\n * promise to preserve Sentry's span instrumentation, while custom SDK methods are\n * forwarded to the original promise to maintain the SDK's API surface.\n */\nexport function wrapPromiseWithMethods<R>(\n originalPromiseLike: Promise<R>,\n instrumentedPromise: Promise<R>,\n): Promise<R> {\n // If the original result is not thenable, return the instrumented promise\n if (!isThenable(originalPromiseLike)) {\n return instrumentedPromise;\n }\n\n // Create a proxy that forwards Promise methods to instrumentedPromise\n // and preserves additional methods from the original result\n return new Proxy(originalPromiseLike, {\n get(target: object, prop: string | symbol): unknown {\n // For standard Promise methods (.then, .catch, .finally, Symbol.toStringTag),\n // use instrumentedPromise to preserve Sentry instrumentation.\n // For custom methods (like .withResponse()), use the original target.\n const useInstrumentedPromise = prop in Promise.prototype || prop === Symbol.toStringTag;\n const source = useInstrumentedPromise ? instrumentedPromise : target;\n\n const value = Reflect.get(source, prop) as unknown;\n\n // Special handling for .withResponse() to preserve instrumentation\n // .withResponse() returns { data: T, response: Response, request_id: string }\n if (prop === 'withResponse' && typeof value === 'function') {\n return function wrappedWithResponse(this: unknown): unknown {\n const originalWithResponse = (value as (...args: unknown[]) => unknown).call(target);\n return createWithResponseWrapper(originalWithResponse, instrumentedPromise);\n };\n }\n\n return typeof value === 'function' ? value.bind(source) : value;\n },\n }) as Promise<R>;\n}\n"],"mappings":";;;;;;;;AAmFA,MAAM,2CAA2B,IAAI,IAAI,CAAC,SAAS,CAAC;;;;;AAMpD,SAAgB,eAAe,eAA+B;CAC5D,OAAO,yBAAyB,IAAI,aAAa,IAAI,WAAW,UAAU;AAC5E;;;;;AAMA,SAAgB,0BAAkD,SAAyC;CACzG,MAAM,QAAQ,UAAU,CAAC,EAAE,yBAAyB,CAAC,CAAC;CACtD,OAAO;EACL,GAAG;EACH,cAAc,SAAS,gBAAgB,OAAO,UAAU;EACxD,eAAe,SAAS,iBAAiB,OAAO,WAAW;CAC7D;AACF;;;;;;AAOA,SAAgB,0BACd,SACA,MACwB;CACxB,MAAM,QAAQ,UAAU,C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,IAAI,CAAC,eACH,OAAO;EAAE,oBAAoB,KAAA;EAAW,kBAAkB;CAAS;CAMrE,OAAO;EAAE,oBAHkB,KAAK,UAAU,CAAC;GAAE,MAAM;GAAQ,SAAS;EAAc,CAAC,CAGzD;EAAG,kBAAA,CAFH,GAAG,SAAS,MAAM,GAAG,kBAAkB,GAAG,GAAG,SAAS,MAAM,qBAAqB,CAAC,CAEhE;CAAE;AAChD;;;;;AAMA,eAAe,0BACb,sBACA,qBACkB;CAIlB,MAAM,CAAC,oBAAoB,mBAAmB,MAAM,QAAQ,IAAI,CAAC,qBAAqB,oBAAoB,CAAC;CAG3G,IAAI,mBAAmB,OAAO,oBAAoB,YAAY,UAAU,iBACtE,OAAO;EACL,GAAG;EACH,MAAM;CACR;CAEF,OAAO;AACT;;;;;;;;;AAUA,SAAgB,uBACd,qBACA,qBACY;CAEZ,IAAI,CAAC,WAAW,mBAAmB,GACjC,OAAO;CAKT,OAAO,IAAI,MAAM,qBAAqB,EACpC,IAAI,QAAgB,MAAgC;EAKlD,MAAM,SADyB,QAAQ,QAAQ,aAAa,SAAS,OAAO,cACpC,sBAAsB;EAE9D,MAAM,QAAQ,QAAQ,IAAI,QAAQ,IAAI;EAItC,IAAI,SAAS,kBAAkB,OAAO,UAAU,YAC9C,OAAO,SAAS,sBAA4C;GAE1D,OAAO,0BADuB,MAA0C,KAAK,MACzB,GAAG,mBAAmB;EAC5E;EAGF,OAAO,OAAO,UAAU,aAAa,MAAM,KAAK,MAAM,IAAI;CAC5D,EACF,CAAC;AACH"}
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import { getGenAiSpanOp
|
|
1
|
+
import { getGenAiSpanOp } from "../core/utils.js";
|
|
2
2
|
import { getOrchestrionInjectedModules } from "../../orchestrion/detect.js";
|
|
3
3
|
import { piAiModuleNames } from "../../orchestrion/config/pi-ai.js";
|
|
4
|
-
import {
|
|
4
|
+
import { setPiAiDriverOptions } from "../pi-ai/recording.js";
|
|
5
5
|
import { isBun, isCloudflareWorkers, isDeno } from "../../utils/runtime.js";
|
|
6
6
|
import { withCleanScopes } from "../../utils/withCleanScopes.js";
|
|
7
7
|
import { FLUE_INSTRUMENTATION_KEY, FLUE_OPERATION, FLUE_ORIGIN, MAX_TRACKED_FLUE_SPANS } from "./constants.js";
|
|
8
|
-
import { endToolSpan,
|
|
8
|
+
import { endToolSpan, startToolSpan } from "./utils.js";
|
|
9
9
|
import { GEN_AI_AGENT_NAME, GEN_AI_CONVERSATION_ID, GEN_AI_OPERATION_NAME, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
|
|
10
|
-
import { LRUMap, consoleSandbox, continueTrace, getActiveSpan, getDefaultIsolationScope, getIsolationScope, startNewTrace, startSpan, withActiveSpan, withScope } from "@sentry/core";
|
|
10
|
+
import { LRUMap, consoleSandbox, continueTrace, getActiveSpan, getDefaultIsolationScope, getIsolationScope, sentryTraceFromTraceparent, startNewTrace, startSpan, withActiveSpan, withScope } from "@sentry/core";
|
|
11
11
|
// src/ai/flue/index.ts
|
|
12
12
|
let checkedPiAiInstrumentation = false;
|
|
13
13
|
/**
|
|
@@ -24,7 +24,7 @@ function warnIfPiAiNotInstrumented() {
|
|
|
24
24
|
});
|
|
25
25
|
}
|
|
26
26
|
function getPiAiInstrumentationHint() {
|
|
27
|
-
if (isBun()) return "
|
|
27
|
+
if (isBun()) return "On Bun 1.4.6 or later, run your app with `bun --preload @sentry/bun/import app.ts`. Or build it with `sentryBunPlugin()` from `@sentry/bun/plugin`.";
|
|
28
28
|
if (isDeno()) return "Run your app with `deno run --preload=npm:@sentry/deno/import app.ts`.";
|
|
29
29
|
if (isCloudflareWorkers()) return "Add `sentryCloudflareVitePlugin()` from `@sentry/cloudflare/vite` to your Vite config.";
|
|
30
30
|
return "Load Sentry with `--import`, for example `node --import ./instrument.mjs app.mjs`.";
|
|
@@ -53,8 +53,8 @@ function runInAdmissionContext(admission, next) {
|
|
|
53
53
|
* as a `gen_ai.chat` span under the agent span.
|
|
54
54
|
*
|
|
55
55
|
* Tool arguments and results are gated on `recordInputs`/`recordOutputs`, which fall back to the
|
|
56
|
-
* current client's `dataCollection.genAI` settings and are
|
|
57
|
-
* the message content of the `gen_ai.chat` spans.
|
|
56
|
+
* current client's `dataCollection.genAI` settings and are decided when each tool span starts. The
|
|
57
|
+
* same options apply to the message content of the `gen_ai.chat` spans.
|
|
58
58
|
*/
|
|
59
59
|
function createFlueInstrumentation(options = {}) {
|
|
60
60
|
const agentSpans = /* @__PURE__ */ new Map();
|
|
@@ -72,7 +72,11 @@ function createFlueInstrumentation(options = {}) {
|
|
|
72
72
|
const { conversationId } = ctx;
|
|
73
73
|
return withScope((scope) => {
|
|
74
74
|
if (conversationId) scope.setConversationId(conversationId);
|
|
75
|
-
|
|
75
|
+
setPiAiDriverOptions(scope, options, {
|
|
76
|
+
operation: "chat",
|
|
77
|
+
execution: operation,
|
|
78
|
+
context: ctx
|
|
79
|
+
});
|
|
76
80
|
return next();
|
|
77
81
|
});
|
|
78
82
|
}
|
|
@@ -103,8 +107,7 @@ function createFlueInstrumentation(options = {}) {
|
|
|
103
107
|
baggage: void 0
|
|
104
108
|
}, openAgentSpan) : openAgentSpan();
|
|
105
109
|
},
|
|
106
|
-
observe: (observation) => {
|
|
107
|
-
const { recordInputs, recordOutputs } = resolveAIRecordingOptions(options);
|
|
110
|
+
observe: (observation, ctx) => {
|
|
108
111
|
const agentSpan = observation.operationId ? agentSpans.get(observation.operationId) : void 0;
|
|
109
112
|
if (agentSpan) {
|
|
110
113
|
if (observation.conversationId) agentSpan.setAttribute(GEN_AI_CONVERSATION_ID, observation.conversationId);
|
|
@@ -124,10 +127,10 @@ function createFlueInstrumentation(options = {}) {
|
|
|
124
127
|
if (observation.submissionId) admissions.remove(observation.submissionId);
|
|
125
128
|
return;
|
|
126
129
|
case "tool_start":
|
|
127
|
-
startToolSpan(observation, toolSpans,
|
|
130
|
+
startToolSpan(observation, ctx, toolSpans, options);
|
|
128
131
|
return;
|
|
129
132
|
case "tool":
|
|
130
|
-
endToolSpan(observation, toolSpans
|
|
133
|
+
endToolSpan(observation, toolSpans);
|
|
131
134
|
return;
|
|
132
135
|
default: return;
|
|
133
136
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/ai/flue/index.ts"],"sourcesContent":["import type { Scope, Span } from '@sentry/core';\nimport {\n consoleSandbox,\n continueTrace,\n getActiveSpan,\n getDefaultIsolationScope,\n getIsolationScope,\n LRUMap,\n startNewTrace,\n startSpan,\n withActiveSpan,\n withScope,\n} from '@sentry/core';\nimport {\n GEN_AI_AGENT_NAME,\n GEN_AI_CONVERSATION_ID,\n GEN_AI_OPERATION_NAME,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport type { GenAiOptions } from '../core/utils';\nimport { getGenAiSpanOp, resolveAIRecordingOptions } from '../core/utils';\nimport { getOrchestrionInjectedModules } from '../../orchestrion/detect';\nimport { piAiModuleNames } from '../../orchestrion/config/pi-ai';\nimport { setPiAiRecordingOptions } from '../pi-ai/recording';\nimport { isBun, isCloudflareWorkers, isDeno } from '../../utils/runtime';\nimport { withCleanScopes } from '../../utils/withCleanScopes';\nimport { FLUE_INSTRUMENTATION_KEY, FLUE_OPERATION, FLUE_ORIGIN, MAX_TRACKED_FLUE_SPANS } from './constants';\nimport type { SpanTracker } from './utils';\nimport { endToolSpan, sentryTraceFromTraceparent, startToolSpan } from './utils';\nimport type { FlueInstrumentation } from './types';\n\nexport type FlueOptions = GenAiOptions;\n\ninterface Admission {\n isolationScope: Scope;\n span: Span | undefined;\n}\n\nlet checkedPiAiInstrumentation = false;\n\n/**\n * `instrument()` works without Sentry's module hook or bundler plugin, but the pi-ai integration that\n * spans Flue's model calls doesn't. Checked on the first model call, once pi-ai has loaded.\n */\nfunction warnIfPiAiNotInstrumented(): void {\n if (checkedPiAiInstrumentation) {\n return;\n }\n checkedPiAiInstrumentation = true;\n\n const injected = getOrchestrionInjectedModules();\n if (piAiModuleNames.some(name => injected.includes(name))) {\n return;\n }\n\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn(\n '[Sentry] Flue model calls are not being traced: `@earendil-works/pi-ai` was not instrumented, so ' +\n `Flue agents record agent and tool spans but no \\`gen_ai.chat\\` spans. ${getPiAiInstrumentationHint()}`,\n );\n });\n}\n\nfunction getPiAiInstrumentationHint(): string {\n if (isBun()) {\n return 'Build your app with `sentryBunPlugin()` from `@sentry/bun/plugin`; `bun run` cannot instrument it.';\n }\n if (isDeno()) {\n return 'Run your app with `deno run --preload=npm:@sentry/deno/import app.ts`.';\n }\n if (isCloudflareWorkers()) {\n return 'Add `sentryCloudflareVitePlugin()` from `@sentry/cloudflare/vite` to your Vite config.';\n }\n return 'Load Sentry with `--import`, for example `node --import ./instrument.mjs app.mjs`.';\n}\n\n/**\n * Flue's Node coordinator runs every submission from one long-lived claim loop, started by the\n * first admission and keeping that call's async context for the life of the process. Left alone,\n * every agent run lands in the trace of whichever request admitted the first one\n * (https://github.com/withastro/flue/issues/813).\n */\nfunction runInAdmissionContext<T>(admission: Admission | undefined, next: () => T): T {\n // Cloudflare runs each turn from a Durable Object alarm, which already starts a trace of its own,\n // so there is no leaked context to undo there.\n if (isCloudflareWorkers()) {\n return next();\n }\n if (!admission) {\n // Admitted by another process, replayed by idempotency key, or evicted: there is nothing to\n // restore, but the loop's context still belongs to an unrelated request.\n return withCleanScopes(getDefaultIsolationScope().clone(), () => startNewTrace(next));\n }\n return withCleanScopes(admission.isolationScope, () =>\n admission.span ? withActiveSpan(admission.span, next) : startNewTrace(next),\n );\n}\n\n/**\n * Build the object to hand to `instrument()` from `@flue/runtime`.\n *\n * The two callbacks own different halves of the result:\n *\n * - `interceptor` wraps agent execution, so the agent span is *active* for its duration and every\n * span opened underneath parents correctly.\n * - `observe` opens and closes the tool spans, and names the agent span.\n *\n * Model calls get no span here: Flue sends them through pi-ai, whose integration reports each one\n * as a `gen_ai.chat` span under the agent span.\n *\n * Tool arguments and results are gated on `recordInputs`/`recordOutputs`, which fall back to the\n * current client's `dataCollection.genAI` settings and are read per event. The same options apply to\n * the message content of the `gen_ai.chat` spans.\n */\nexport function createFlueInstrumentation(options: FlueOptions = {}): FlueInstrumentation {\n // Keyed by the agent operation's own id, which is what the observations carry. That keeps\n // concurrent runs apart and gives a delegated subagent its own span: Flue nests a second `agent`\n // operation inside the parent's for `task` delegation, and the nesting is not bounded at two.\n // A plain map: the entry is removed in a `finally`, so it is bounded by concurrent agent runs.\n const agentSpans = new Map<string, Span>();\n // Capped, unlike the above: these are keyed off ids that only a matching end observation removes.\n const toolSpans: SpanTracker = new LRUMap(MAX_TRACKED_FLUE_SPANS);\n // Capped: a submission admitted here but run by another process never settles here.\n const admissions = new LRUMap<string, Admission>(MAX_TRACKED_FLUE_SPANS);\n\n return {\n key: FLUE_INSTRUMENTATION_KEY,\n\n interceptor: async (operation, ctx, next) => {\n // `observe` has already opened the tool span; make it active for the duration so whatever the\n // tool does lands inside it rather than beside it.\n if (operation?.type === FLUE_OPERATION.TOOL) {\n const toolSpan = operation.toolCallId ? toolSpans.get(operation.toolCallId) : undefined;\n return toolSpan ? withActiveSpan(toolSpan, next) : next();\n }\n // The `gen_ai.chat` span of the model call comes from the pi-ai integration, which reads the\n // conversation and the recording options from the scope.\n if (operation?.type === FLUE_OPERATION.MODEL) {\n warnIfPiAiNotInstrumented();\n const { conversationId } = ctx;\n return withScope(scope => {\n if (conversationId) {\n scope.setConversationId(conversationId);\n }\n setPiAiRecordingOptions(scope, options);\n return next();\n });\n }\n\n if (operation?.type !== FLUE_OPERATION.AGENT) {\n return next();\n }\n\n // A submission opens with a wrapper operation whose id *is* the submission id; the run it\n // wraps gets its own operation id, and that is the one the observations reference. Spanning\n // the wrapper too would double-count every agent invocation, but it is the outermost point of\n // every attempt, so it is where the admitting context goes back in.\n const operationId = operation.operationId;\n if (operationId && operationId === ctx.submissionId) {\n return runInAdmissionContext(admissions.get(operationId), next);\n }\n if (!operationId || agentSpans.has(operationId)) {\n return next();\n }\n\n const openAgentSpan = () =>\n startSpan(\n {\n name: `invoke_agent ${ctx.agentName ?? 'agent'}`,\n op: getGenAiSpanOp('invoke_agent'),\n attributes: {\n [SENTRY_ORIGIN]: FLUE_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'invoke_agent',\n [GEN_AI_AGENT_NAME]: ctx.agentName,\n [GEN_AI_CONVERSATION_ID]: ctx.conversationId,\n },\n },\n async (span: Span) => {\n agentSpans.set(operationId, span);\n try {\n return await next();\n } finally {\n agentSpans.delete(operationId);\n }\n },\n );\n\n // A durable or dispatched submission is run later by the coordinator, possibly in another\n // isolate or process, where nothing links it back to the request that enqueued it. Flue\n // replays that request's `traceparent` here, so continue from it — but only when no trace is\n // already active, so an in-process dispatch keeps the trace it is genuinely part of.\n const sentryTrace = ctx.traceCarrier?.traceparent\n ? sentryTraceFromTraceparent(ctx.traceCarrier.traceparent)\n : undefined;\n\n return sentryTrace && !getActiveSpan()\n ? continueTrace({ sentryTrace, baggage: undefined }, openAgentSpan)\n : openAgentSpan();\n },\n\n observe: observation => {\n // Resolved per observation, not once at construction: `resolveAIRecordingOptions` reads the\n // current client's `dataCollection.genAI`, and Cloudflare replaces the client per request, so\n // values captured at isolate load would be the wrong ones for every later request.\n const { recordInputs, recordOutputs } = resolveAIRecordingOptions(options);\n\n // Observations are emitted synchronously from inside the agent operation, so the active span\n // here is the agent span the interceptor opened — tool spans parent off it without any\n // bookkeeping.\n //\n // The agent operation that gets the span is the one the observations reference, and it knows\n // neither the agent's name nor the conversation: the submission wrapper carries the name, the\n // re-entry carries the conversation, and neither opens a span. Both arrive here instead.\n const agentSpan = observation.operationId ? agentSpans.get(observation.operationId) : undefined;\n if (agentSpan) {\n if (observation.conversationId) {\n agentSpan.setAttribute(GEN_AI_CONVERSATION_ID, observation.conversationId);\n }\n if (observation.agentName) {\n agentSpan.setAttribute(GEN_AI_AGENT_NAME, observation.agentName);\n agentSpan.updateName(`invoke_agent ${observation.agentName}`);\n }\n }\n\n switch (observation.type) {\n // Emitted synchronously from inside the admitting call, so the active context is its own.\n case 'submission_queued':\n if (observation.submissionId && !isCloudflareWorkers()) {\n admissions.set(observation.submissionId, {\n isolationScope: getIsolationScope(),\n span: getActiveSpan(),\n });\n }\n return;\n case 'submission_settled':\n if (observation.submissionId) {\n admissions.remove(observation.submissionId);\n }\n return;\n case 'tool_start':\n startToolSpan(observation, toolSpans, recordInputs);\n return;\n case 'tool':\n endToolSpan(observation, toolSpans, recordOutputs);\n return;\n default:\n return;\n }\n },\n\n // Only the tool spans are ended here. They come from `startInactiveSpan`, so nothing else will.\n // The agent spans come from `startSpan`, which ends them when its callback settles — ending them\n // here would stamp an early end time on work that is still running, and the later `end()` would\n // be ignored.\n dispose: () => {\n for (const span of toolSpans.values()) {\n span.end();\n }\n agentSpans.clear();\n admissions.clear();\n toolSpans.clear();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;AAsCA,IAAI,6BAA6B;;;;;AAMjC,SAAS,4BAAkC;CACzC,IAAI,4BACF;CAEF,6BAA6B;CAE7B,MAAM,WAAW,8BAA8B;CAC/C,IAAI,gBAAgB,MAAK,SAAQ,SAAS,SAAS,IAAI,CAAC,GACtD;CAGF,qBAAqB;EAEnB,QAAQ,KACN,4KAC2E,2BAA2B,GACxG;CACF,CAAC;AACH;AAEA,SAAS,6BAAqC;CAC5C,IAAI,MAAM,GACR,OAAO;CAET,IAAI,OAAO,GACT,OAAO;CAET,IAAI,oBAAoB,GACtB,OAAO;CAET,OAAO;AACT;;;;;;;AAQA,SAAS,sBAAyB,WAAkC,MAAkB;CAGpF,IAAI,oBAAoB,GACtB,OAAO,KAAK;CAEd,IAAI,CAAC,WAGH,OAAO,gBAAgB,yBAAyB,CAAC,CAAC,MAAM,SAAS,cAAc,IAAI,CAAC;CAEtF,OAAO,gBAAgB,UAAU,sBAC/B,UAAU,OAAO,eAAe,UAAU,MAAM,IAAI,IAAI,cAAc,IAAI,CAC5E;AACF;;;;;;;;;;;;;;;;;A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Aa,SAAS,KAAA;GAAU,GAAG,aAAa,IAChE,cAAc;EACpB;EAEA,UAAS,gBAAe;GAItB,MAAM,EAAE,cAAc,kBAAkB,0BAA0B,OAAO;GASzE,MAAM,YAAY,YAAY,cAAc,WAAW,IAAI,YAAY,WAAW,IAAI,KAAA;GACtF,IAAI,WAAW;IACb,IAAI,YAAY,gBACd,UAAU,aAAa,wBAAwB,YAAY,cAAc;IAE3E,IAAI,YAAY,WAAW;KACzB,UAAU,aAAa,mBAAmB,YAAY,SAAS;KAC/D,UAAU,WAAW,gBAAgB,YAAY,WAAW;IAC9D;GACF;GAEA,QAAQ,YAAY,MAApB;IAEE,KAAK;KACH,IAAI,YAAY,gBAAgB,CAAC,oBAAoB,GACnD,WAAW,IAAI,YAAY,cAAc;MACvC,gBAAgB,kBAAkB;MAClC,MAAM,cAAc;KACtB,CAAC;KAEH;IACF,KAAK;KACH,IAAI,YAAY,cACd,WAAW,OAAO,YAAY,YAAY;KAE5C;IACF,KAAK;KACH,cAAc,aAAa,WAAW,YAAY;KAClD;IACF,KAAK;KACH,YAAY,aAAa,WAAW,aAAa;KACjD;IACF,SACE;GACJ;EACF;EAMA,eAAe;GACb,KAAK,MAAM,QAAQ,UAAU,OAAO,GAClC,KAAK,IAAI;GAEX,WAAW,MAAM;GACjB,WAAW,MAAM;GACjB,UAAU,MAAM;EAClB;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/ai/flue/index.ts"],"sourcesContent":["import type { Scope, Span } from '@sentry/core';\nimport {\n consoleSandbox,\n continueTrace,\n getActiveSpan,\n getDefaultIsolationScope,\n getIsolationScope,\n LRUMap,\n sentryTraceFromTraceparent,\n startNewTrace,\n startSpan,\n withActiveSpan,\n withScope,\n} from '@sentry/core';\nimport {\n GEN_AI_AGENT_NAME,\n GEN_AI_CONVERSATION_ID,\n GEN_AI_OPERATION_NAME,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport type { GenAiSpanHooks } from '../core/span-hooks';\nimport type { GenAiCallOptions } from '../core/utils';\nimport { getGenAiSpanOp } from '../core/utils';\nimport { getOrchestrionInjectedModules } from '../../orchestrion/detect';\nimport { piAiModuleNames } from '../../orchestrion/config/pi-ai';\nimport { setPiAiDriverOptions } from '../pi-ai/recording';\nimport type { PiAssistantMessage } from '../pi-ai/types';\nimport { isBun, isCloudflareWorkers, isDeno } from '../../utils/runtime';\nimport { withCleanScopes } from '../../utils/withCleanScopes';\nimport { FLUE_INSTRUMENTATION_KEY, FLUE_OPERATION, FLUE_ORIGIN, MAX_TRACKED_FLUE_SPANS } from './constants';\nimport type { SpanTracker } from './utils';\nimport { endToolSpan, startToolSpan } from './utils';\nimport type { FlueCallInfo, FlueInstrumentation, FlueObservation } from './types';\n\n/**\n * The span hooks run for the `gen_ai.chat` spans of the model calls, which pi-ai reports, and for the\n * tool spans. `onSpanEnd` gets the `AssistantMessage` of a model call, and the `tool` observation of a\n * tool call, whose `errorInfo` is also the `error` of a failed tool. A tool call that never ends, whose\n * span is ended when the tracker evicts it or Flue disposes the instrumentation, does not run `onSpanEnd`.\n */\nexport type FlueOptions = GenAiCallOptions<FlueCallInfo> &\n GenAiSpanHooks<FlueCallInfo, PiAssistantMessage | FlueObservation>;\n\ninterface Admission {\n isolationScope: Scope;\n span: Span | undefined;\n}\n\nlet checkedPiAiInstrumentation = false;\n\n/**\n * `instrument()` works without Sentry's module hook or bundler plugin, but the pi-ai integration that\n * spans Flue's model calls doesn't. Checked on the first model call, once pi-ai has loaded.\n */\nfunction warnIfPiAiNotInstrumented(): void {\n if (checkedPiAiInstrumentation) {\n return;\n }\n checkedPiAiInstrumentation = true;\n\n const injected = getOrchestrionInjectedModules();\n if (piAiModuleNames.some(name => injected.includes(name))) {\n return;\n }\n\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn(\n '[Sentry] Flue model calls are not being traced: `@earendil-works/pi-ai` was not instrumented, so ' +\n `Flue agents record agent and tool spans but no \\`gen_ai.chat\\` spans. ${getPiAiInstrumentationHint()}`,\n );\n });\n}\n\nfunction getPiAiInstrumentationHint(): string {\n if (isBun()) {\n return 'On Bun 1.4.6 or later, run your app with `bun --preload @sentry/bun/import app.ts`. Or build it with `sentryBunPlugin()` from `@sentry/bun/plugin`.';\n }\n if (isDeno()) {\n return 'Run your app with `deno run --preload=npm:@sentry/deno/import app.ts`.';\n }\n if (isCloudflareWorkers()) {\n return 'Add `sentryCloudflareVitePlugin()` from `@sentry/cloudflare/vite` to your Vite config.';\n }\n return 'Load Sentry with `--import`, for example `node --import ./instrument.mjs app.mjs`.';\n}\n\n/**\n * Flue's Node coordinator runs every submission from one long-lived claim loop, started by the\n * first admission and keeping that call's async context for the life of the process. Left alone,\n * every agent run lands in the trace of whichever request admitted the first one\n * (https://github.com/withastro/flue/issues/813).\n */\nfunction runInAdmissionContext<T>(admission: Admission | undefined, next: () => T): T {\n // Cloudflare runs each turn from a Durable Object alarm, which already starts a trace of its own,\n // so there is no leaked context to undo there.\n if (isCloudflareWorkers()) {\n return next();\n }\n if (!admission) {\n // Admitted by another process, replayed by idempotency key, or evicted: there is nothing to\n // restore, but the loop's context still belongs to an unrelated request.\n return withCleanScopes(getDefaultIsolationScope().clone(), () => startNewTrace(next));\n }\n return withCleanScopes(admission.isolationScope, () =>\n admission.span ? withActiveSpan(admission.span, next) : startNewTrace(next),\n );\n}\n\n/**\n * Build the object to hand to `instrument()` from `@flue/runtime`.\n *\n * The two callbacks own different halves of the result:\n *\n * - `interceptor` wraps agent execution, so the agent span is *active* for its duration and every\n * span opened underneath parents correctly.\n * - `observe` opens and closes the tool spans, and names the agent span.\n *\n * Model calls get no span here: Flue sends them through pi-ai, whose integration reports each one\n * as a `gen_ai.chat` span under the agent span.\n *\n * Tool arguments and results are gated on `recordInputs`/`recordOutputs`, which fall back to the\n * current client's `dataCollection.genAI` settings and are decided when each tool span starts. The\n * same options apply to the message content of the `gen_ai.chat` spans.\n */\nexport function createFlueInstrumentation(options: FlueOptions = {}): FlueInstrumentation {\n // Keyed by the agent operation's own id, which is what the observations carry. That keeps\n // concurrent runs apart and gives a delegated subagent its own span: Flue nests a second `agent`\n // operation inside the parent's for `task` delegation, and the nesting is not bounded at two.\n // A plain map: the entry is removed in a `finally`, so it is bounded by concurrent agent runs.\n const agentSpans = new Map<string, Span>();\n // Capped, unlike the above: these are keyed off ids that only a matching end observation removes.\n const toolSpans: SpanTracker = new LRUMap(MAX_TRACKED_FLUE_SPANS);\n // Capped: a submission admitted here but run by another process never settles here.\n const admissions = new LRUMap<string, Admission>(MAX_TRACKED_FLUE_SPANS);\n\n return {\n key: FLUE_INSTRUMENTATION_KEY,\n\n interceptor: async (operation, ctx, next) => {\n // `observe` has already opened the tool span; make it active for the duration so whatever the\n // tool does lands inside it rather than beside it.\n if (operation?.type === FLUE_OPERATION.TOOL) {\n const toolSpan = operation.toolCallId ? toolSpans.get(operation.toolCallId) : undefined;\n return toolSpan ? withActiveSpan(toolSpan, next) : next();\n }\n // The `gen_ai.chat` span of the model call comes from the pi-ai integration, which reads the\n // conversation and the recording options from the scope.\n if (operation?.type === FLUE_OPERATION.MODEL) {\n warnIfPiAiNotInstrumented();\n const { conversationId } = ctx;\n return withScope(scope => {\n if (conversationId) {\n scope.setConversationId(conversationId);\n }\n setPiAiDriverOptions(scope, options, { operation: 'chat', execution: operation, context: ctx });\n return next();\n });\n }\n\n if (operation?.type !== FLUE_OPERATION.AGENT) {\n return next();\n }\n\n // A submission opens with a wrapper operation whose id *is* the submission id; the run it\n // wraps gets its own operation id, and that is the one the observations reference. Spanning\n // the wrapper too would double-count every agent invocation, but it is the outermost point of\n // every attempt, so it is where the admitting context goes back in.\n const operationId = operation.operationId;\n if (operationId && operationId === ctx.submissionId) {\n return runInAdmissionContext(admissions.get(operationId), next);\n }\n if (!operationId || agentSpans.has(operationId)) {\n return next();\n }\n\n const openAgentSpan = () =>\n startSpan(\n {\n name: `invoke_agent ${ctx.agentName ?? 'agent'}`,\n op: getGenAiSpanOp('invoke_agent'),\n attributes: {\n [SENTRY_ORIGIN]: FLUE_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'invoke_agent',\n [GEN_AI_AGENT_NAME]: ctx.agentName,\n [GEN_AI_CONVERSATION_ID]: ctx.conversationId,\n },\n },\n async (span: Span) => {\n agentSpans.set(operationId, span);\n try {\n return await next();\n } finally {\n agentSpans.delete(operationId);\n }\n },\n );\n\n // A durable or dispatched submission is run later by the coordinator, possibly in another\n // isolate or process, where nothing links it back to the request that enqueued it. Flue\n // replays that request's `traceparent` here, so continue from it — but only when no trace is\n // already active, so an in-process dispatch keeps the trace it is genuinely part of.\n const sentryTrace = ctx.traceCarrier?.traceparent\n ? sentryTraceFromTraceparent(ctx.traceCarrier.traceparent)\n : undefined;\n\n return sentryTrace && !getActiveSpan()\n ? continueTrace({ sentryTrace, baggage: undefined }, openAgentSpan)\n : openAgentSpan();\n },\n\n observe: (observation, ctx) => {\n // Observations are emitted synchronously from inside the agent operation, so the active span\n // here is the agent span the interceptor opened — tool spans parent off it without any\n // bookkeeping.\n //\n // The agent operation that gets the span is the one the observations reference, and it knows\n // neither the agent's name nor the conversation: the submission wrapper carries the name, the\n // re-entry carries the conversation, and neither opens a span. Both arrive here instead.\n const agentSpan = observation.operationId ? agentSpans.get(observation.operationId) : undefined;\n if (agentSpan) {\n if (observation.conversationId) {\n agentSpan.setAttribute(GEN_AI_CONVERSATION_ID, observation.conversationId);\n }\n if (observation.agentName) {\n agentSpan.setAttribute(GEN_AI_AGENT_NAME, observation.agentName);\n agentSpan.updateName(`invoke_agent ${observation.agentName}`);\n }\n }\n\n switch (observation.type) {\n // Emitted synchronously from inside the admitting call, so the active context is its own.\n case 'submission_queued':\n if (observation.submissionId && !isCloudflareWorkers()) {\n admissions.set(observation.submissionId, {\n isolationScope: getIsolationScope(),\n span: getActiveSpan(),\n });\n }\n return;\n case 'submission_settled':\n if (observation.submissionId) {\n admissions.remove(observation.submissionId);\n }\n return;\n case 'tool_start':\n startToolSpan(observation, ctx, toolSpans, options);\n return;\n case 'tool':\n endToolSpan(observation, toolSpans);\n return;\n default:\n return;\n }\n },\n\n // Only the tool spans are ended here. They come from `startInactiveSpan`, so nothing else will.\n // The agent spans come from `startSpan`, which ends them when its callback settles — ending them\n // here would stamp an early end time on work that is still running, and the later `end()` would\n // be ignored.\n dispose: () => {\n for (const span of toolSpans.values()) {\n span.end();\n }\n agentSpans.clear();\n admissions.clear();\n toolSpans.clear();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;AAgDA,IAAI,6BAA6B;;;;;AAMjC,SAAS,4BAAkC;CACzC,IAAI,4BACF;CAEF,6BAA6B;CAE7B,MAAM,WAAW,8BAA8B;CAC/C,IAAI,gBAAgB,MAAK,SAAQ,SAAS,SAAS,IAAI,CAAC,GACtD;CAGF,qBAAqB;EAEnB,QAAQ,KACN,4KAC2E,2BAA2B,GACxG;CACF,CAAC;AACH;AAEA,SAAS,6BAAqC;CAC5C,IAAI,MAAM,GACR,OAAO;CAET,IAAI,OAAO,GACT,OAAO;CAET,IAAI,oBAAoB,GACtB,OAAO;CAET,OAAO;AACT;;;;;;;AAQA,SAAS,sBAAyB,WAAkC,MAAkB;CAGpF,IAAI,oBAAoB,GACtB,OAAO,KAAK;CAEd,IAAI,CAAC,WAGH,OAAO,gBAAgB,yBAAyB,CAAC,CAAC,MAAM,SAAS,cAAc,IAAI,CAAC;CAEtF,OAAO,gBAAgB,UAAU,sBAC/B,UAAU,OAAO,eAAe,UAAU,MAAM,IAAI,IAAI,cAAc,IAAI,CAC5E;AACF;;;;;;;;;;;;;;;;;AAkBA,SAAgB,0BAA0B,UAAuB,CAAC,GAAwB;CAKxF,MAAM,6BAAa,IAAI,IAAkB;CAEzC,MAAM,YAAyB,IAAI,OAAO,sBAAsB;CAEhE,MAAM,aAAa,IAAI,OAA0B,sBAAsB;CAEvE,OAAO;EACL,KAAK;EAEL,aAAa,OAAO,WAAW,KAAK,SAAS;GAG3C,IAAI,WAAW,SAAS,eAAe,MAAM;IAC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