@sentry/server-utils 11.14.0 → 11.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/cjs/chunks/exports.js +526 -217
- package/build/cjs/chunks/exports.js.map +1 -1
- package/build/cjs/index.js +1028 -120
- package/build/cjs/index.js.map +1 -1
- package/build/esm/ai/anthropic-ai/index.js +32 -56
- package/build/esm/ai/anthropic-ai/index.js.map +1 -1
- package/build/esm/ai/anthropic-ai/streaming.js +10 -6
- package/build/esm/ai/anthropic-ai/streaming.js.map +1 -1
- package/build/esm/ai/anthropic-ai/tool-runner.js +18 -3
- package/build/esm/ai/anthropic-ai/tool-runner.js.map +1 -1
- package/build/esm/ai/anthropic-ai/utils.js +41 -3
- package/build/esm/ai/anthropic-ai/utils.js.map +1 -1
- package/build/esm/ai/core/span-hooks.js +23 -0
- package/build/esm/ai/core/span-hooks.js.map +1 -0
- package/build/esm/ai/core/time-to-first-chunk.js +14 -0
- package/build/esm/ai/core/time-to-first-chunk.js.map +1 -0
- package/build/esm/ai/core/utils.js +29 -3
- package/build/esm/ai/core/utils.js.map +1 -1
- package/build/esm/ai/flue/index.js +15 -12
- package/build/esm/ai/flue/index.js.map +1 -1
- package/build/esm/ai/flue/utils.js +24 -17
- package/build/esm/ai/flue/utils.js.map +1 -1
- package/build/esm/ai/google-genai/index.js +21 -8
- package/build/esm/ai/google-genai/index.js.map +1 -1
- package/build/esm/ai/google-genai/streaming.js +6 -2
- package/build/esm/ai/google-genai/streaming.js.map +1 -1
- package/build/esm/ai/langchain/embeddings.js +5 -2
- package/build/esm/ai/langchain/embeddings.js.map +1 -1
- package/build/esm/ai/langchain/index.js +82 -24
- package/build/esm/ai/langchain/index.js.map +1 -1
- package/build/esm/ai/langchain/utils.js +9 -1
- package/build/esm/ai/langchain/utils.js.map +1 -1
- package/build/esm/ai/langgraph/agent-span.js +13 -5
- package/build/esm/ai/langgraph/agent-span.js.map +1 -1
- package/build/esm/ai/langgraph/index.js +13 -15
- package/build/esm/ai/langgraph/index.js.map +1 -1
- package/build/esm/ai/langgraph/stream.js +4 -3
- package/build/esm/ai/langgraph/stream.js.map +1 -1
- package/build/esm/ai/langgraph/utils.js +17 -8
- package/build/esm/ai/langgraph/utils.js.map +1 -1
- package/build/esm/ai/mastra/classifier-evaluation.js.map +1 -1
- package/build/esm/ai/mastra/index.js +33 -16
- package/build/esm/ai/mastra/index.js.map +1 -1
- package/build/esm/ai/mastra/utils.js +3 -5
- package/build/esm/ai/mastra/utils.js.map +1 -1
- package/build/esm/ai/mistral/index.js +21 -7
- package/build/esm/ai/mistral/index.js.map +1 -1
- package/build/esm/ai/mistral/streaming.js +4 -2
- package/build/esm/ai/mistral/streaming.js.map +1 -1
- package/build/esm/ai/openai/index.js +19 -8
- package/build/esm/ai/openai/index.js.map +1 -1
- package/build/esm/ai/openai/streaming.js +7 -2
- package/build/esm/ai/openai/streaming.js.map +1 -1
- package/build/esm/ai/pi-ai/chat.js +18 -1
- package/build/esm/ai/pi-ai/chat.js.map +1 -1
- package/build/esm/ai/pi-ai/recording.js +34 -15
- package/build/esm/ai/pi-ai/recording.js.map +1 -1
- package/build/esm/ai/pi-durable/index.js +7 -2
- package/build/esm/ai/pi-durable/index.js.map +1 -1
- package/build/esm/ai/pi-durable/runs.js.map +1 -1
- package/build/esm/ai/pi-durable/tools.js +18 -3
- package/build/esm/ai/pi-durable/tools.js.map +1 -1
- package/build/esm/ai/typesafe/index.js +14 -6
- package/build/esm/ai/typesafe/index.js.map +1 -1
- package/build/esm/ai/workers-ai/index.js +26 -9
- package/build/esm/ai/workers-ai/index.js.map +1 -1
- package/build/esm/ai/workers-ai/streaming.js +6 -4
- package/build/esm/ai/workers-ai/streaming.js.map +1 -1
- package/build/esm/cron/common.js +16 -0
- package/build/esm/cron/common.js.map +1 -0
- package/build/esm/cron/cron.js +82 -0
- package/build/esm/cron/cron.js.map +1 -0
- package/build/esm/cron/index.js +13 -0
- package/build/esm/cron/index.js.map +1 -0
- package/build/esm/cron/node-cron.js +66 -0
- package/build/esm/cron/node-cron.js.map +1 -0
- package/build/esm/cron/node-schedule.js +43 -0
- package/build/esm/cron/node-schedule.js.map +1 -0
- package/build/esm/index.js +6 -2
- package/build/esm/index.js.map +1 -1
- package/build/esm/integrations/anthropic.js +25 -16
- package/build/esm/integrations/anthropic.js.map +1 -1
- package/build/esm/integrations/aws-sdk/index.js +1 -0
- package/build/esm/integrations/aws-sdk/index.js.map +1 -1
- package/build/esm/integrations/aws-sdk/services/ServicesExtensions.js +3 -0
- package/build/esm/integrations/aws-sdk/services/ServicesExtensions.js.map +1 -1
- package/build/esm/integrations/aws-sdk/services/bedrock-runtime.js +45 -12
- package/build/esm/integrations/aws-sdk/services/bedrock-runtime.js.map +1 -1
- package/build/esm/integrations/bullmq/contextManager.js +45 -0
- package/build/esm/integrations/bullmq/contextManager.js.map +1 -0
- package/build/esm/integrations/bullmq/index.js +44 -0
- package/build/esm/integrations/bullmq/index.js.map +1 -0
- package/build/esm/integrations/bullmq/meter.js +86 -0
- package/build/esm/integrations/bullmq/meter.js.map +1 -0
- package/build/esm/integrations/bullmq/span.js +114 -0
- package/build/esm/integrations/bullmq/span.js.map +1 -0
- package/build/esm/integrations/bullmq/tracer.js +62 -0
- package/build/esm/integrations/bullmq/tracer.js.map +1 -0
- package/build/esm/integrations/express/instrumentation.js +10 -1
- package/build/esm/integrations/express/instrumentation.js.map +1 -1
- package/build/esm/integrations/google-genai.js +17 -9
- package/build/esm/integrations/google-genai.js.map +1 -1
- package/build/esm/integrations/langgraph.js +5 -7
- package/build/esm/integrations/langgraph.js.map +1 -1
- package/build/esm/integrations/mastra-classifier.js +1 -1
- package/build/esm/integrations/mastra-classifier.js.map +1 -1
- package/build/esm/integrations/mistral.js +13 -4
- package/build/esm/integrations/mistral.js.map +1 -1
- package/build/esm/integrations/openai-compatible.js +16 -8
- package/build/esm/integrations/openai-compatible.js.map +1 -1
- package/build/esm/integrations/openai.js +16 -8
- package/build/esm/integrations/openai.js.map +1 -1
- package/build/esm/integrations/pi-ai.js +39 -18
- package/build/esm/integrations/pi-ai.js.map +1 -1
- package/build/esm/integrations/pino.js +131 -0
- package/build/esm/integrations/pino.js.map +1 -0
- package/build/esm/integrations/typesafe.js +17 -3
- package/build/esm/integrations/typesafe.js.map +1 -1
- package/build/esm/integrations/vercel-ai/index.js.map +1 -1
- package/build/esm/integrations/vercel-ai/util.js +3 -2
- package/build/esm/integrations/vercel-ai/util.js.map +1 -1
- package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js +44 -17
- package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -1
- package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js +22 -16
- package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js.map +1 -1
- package/build/esm/integrations/winston.js +90 -0
- package/build/esm/integrations/winston.js.map +1 -0
- package/build/esm/orchestrion/detect.js +1 -1
- package/build/esm/orchestrion/detect.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/types/ai/anthropic-ai/index.d.ts +1 -5
- package/build/types/ai/anthropic-ai/index.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/streaming.d.ts +3 -2
- package/build/types/ai/anthropic-ai/streaming.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/tool-runner.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/types.d.ts +24 -3
- package/build/types/ai/anthropic-ai/types.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/utils.d.ts +2 -3
- package/build/types/ai/anthropic-ai/utils.d.ts.map +1 -1
- package/build/types/ai/core/span-hooks.d.ts +31 -0
- package/build/types/ai/core/span-hooks.d.ts.map +1 -0
- package/build/types/ai/core/time-to-first-chunk.d.ts +7 -0
- package/build/types/ai/core/time-to-first-chunk.d.ts.map +1 -0
- package/build/types/ai/core/utils.d.ts +30 -1
- package/build/types/ai/core/utils.d.ts.map +1 -1
- package/build/types/ai/flue/index.d.ts +13 -5
- package/build/types/ai/flue/index.d.ts.map +1 -1
- package/build/types/ai/flue/types.d.ts +20 -2
- package/build/types/ai/flue/types.d.ts.map +1 -1
- package/build/types/ai/flue/utils.d.ts +5 -9
- package/build/types/ai/flue/utils.d.ts.map +1 -1
- package/build/types/ai/google-genai/index.d.ts.map +1 -1
- package/build/types/ai/google-genai/streaming.d.ts +2 -1
- package/build/types/ai/google-genai/streaming.d.ts.map +1 -1
- package/build/types/ai/google-genai/types.d.ts +17 -3
- package/build/types/ai/google-genai/types.d.ts.map +1 -1
- package/build/types/ai/langchain/index.d.ts.map +1 -1
- package/build/types/ai/langchain/types.d.ts +49 -3
- package/build/types/ai/langchain/types.d.ts.map +1 -1
- package/build/types/ai/langchain/utils.d.ts +6 -0
- package/build/types/ai/langchain/utils.d.ts.map +1 -1
- package/build/types/ai/langgraph/agent-span.d.ts +4 -1
- package/build/types/ai/langgraph/agent-span.d.ts.map +1 -1
- package/build/types/ai/langgraph/index.d.ts +1 -1
- package/build/types/ai/langgraph/index.d.ts.map +1 -1
- package/build/types/ai/langgraph/stream.d.ts.map +1 -1
- package/build/types/ai/langgraph/types.d.ts +14 -3
- package/build/types/ai/langgraph/types.d.ts.map +1 -1
- package/build/types/ai/langgraph/utils.d.ts +3 -0
- package/build/types/ai/langgraph/utils.d.ts.map +1 -1
- package/build/types/ai/mastra/classifier-evaluation.d.ts +3 -3
- package/build/types/ai/mastra/classifier-evaluation.d.ts.map +1 -1
- package/build/types/ai/mastra/index.d.ts +17 -3
- package/build/types/ai/mastra/index.d.ts.map +1 -1
- package/build/types/ai/mastra/types.d.ts +2 -0
- package/build/types/ai/mastra/types.d.ts.map +1 -1
- package/build/types/ai/mastra/utils.d.ts.map +1 -1
- package/build/types/ai/mistral/index.d.ts.map +1 -1
- package/build/types/ai/mistral/streaming.d.ts +2 -1
- package/build/types/ai/mistral/streaming.d.ts.map +1 -1
- package/build/types/ai/mistral/types.d.ts +14 -3
- package/build/types/ai/mistral/types.d.ts.map +1 -1
- package/build/types/ai/openai/index.d.ts.map +1 -1
- package/build/types/ai/openai/streaming.d.ts +3 -1
- package/build/types/ai/openai/streaming.d.ts.map +1 -1
- package/build/types/ai/openai/types.d.ts +14 -3
- package/build/types/ai/openai/types.d.ts.map +1 -1
- package/build/types/ai/pi-ai/chat.d.ts +7 -1
- package/build/types/ai/pi-ai/chat.d.ts.map +1 -1
- package/build/types/ai/pi-ai/recording.d.ts +21 -9
- package/build/types/ai/pi-ai/recording.d.ts.map +1 -1
- package/build/types/ai/pi-ai/types.d.ts +16 -0
- package/build/types/ai/pi-ai/types.d.ts.map +1 -1
- package/build/types/ai/pi-durable/index.d.ts +12 -3
- package/build/types/ai/pi-durable/index.d.ts.map +1 -1
- package/build/types/ai/pi-durable/runs.d.ts +2 -0
- package/build/types/ai/pi-durable/runs.d.ts.map +1 -1
- package/build/types/ai/pi-durable/tools.d.ts +4 -3
- package/build/types/ai/pi-durable/tools.d.ts.map +1 -1
- package/build/types/ai/pi-durable/types.d.ts +15 -0
- package/build/types/ai/pi-durable/types.d.ts.map +1 -1
- package/build/types/ai/typesafe/index.d.ts +10 -2
- package/build/types/ai/typesafe/index.d.ts.map +1 -1
- package/build/types/ai/workers-ai/index.d.ts.map +1 -1
- package/build/types/ai/workers-ai/streaming.d.ts +2 -1
- package/build/types/ai/workers-ai/streaming.d.ts.map +1 -1
- package/build/types/ai/workers-ai/types.d.ts +18 -3
- package/build/types/ai/workers-ai/types.d.ts.map +1 -1
- package/build/types/cron/common.d.ts +8 -0
- package/build/types/cron/common.d.ts.map +1 -0
- package/build/types/cron/cron.d.ts +45 -0
- package/build/types/cron/cron.d.ts.map +1 -0
- package/build/types/cron/index.d.ts +10 -0
- package/build/types/cron/index.d.ts.map +1 -0
- package/build/types/cron/node-cron.d.ts +33 -0
- package/build/types/cron/node-cron.d.ts.map +1 -0
- package/build/types/cron/node-schedule.d.ts +19 -0
- package/build/types/cron/node-schedule.d.ts.map +1 -0
- package/build/types/index.d.ts +5 -2
- package/build/types/index.d.ts.map +1 -1
- package/build/types/integrations/anthropic.d.ts +2 -1
- package/build/types/integrations/anthropic.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/index.d.ts +3 -3
- package/build/types/integrations/aws-sdk/index.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/services/ServiceExtension.d.ts +1 -0
- package/build/types/integrations/aws-sdk/services/ServiceExtension.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/services/ServicesExtensions.d.ts +3 -2
- package/build/types/integrations/aws-sdk/services/ServicesExtensions.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/services/bedrock-runtime.d.ts +25 -4
- package/build/types/integrations/aws-sdk/services/bedrock-runtime.d.ts.map +1 -1
- package/build/types/integrations/bullmq/contextManager.d.ts +13 -0
- package/build/types/integrations/bullmq/contextManager.d.ts.map +1 -0
- package/build/types/integrations/bullmq/index.d.ts +43 -0
- package/build/types/integrations/bullmq/index.d.ts.map +1 -0
- package/build/types/integrations/bullmq/meter.d.ts +7 -0
- package/build/types/integrations/bullmq/meter.d.ts.map +1 -0
- package/build/types/integrations/bullmq/span.d.ts +35 -0
- package/build/types/integrations/bullmq/span.d.ts.map +1 -0
- package/build/types/integrations/bullmq/tracer.d.ts +5 -0
- package/build/types/integrations/bullmq/tracer.d.ts.map +1 -0
- package/build/types/integrations/bullmq/types.d.ts +72 -0
- package/build/types/integrations/bullmq/types.d.ts.map +1 -0
- package/build/types/integrations/express/types.d.ts +1 -0
- package/build/types/integrations/express/types.d.ts.map +1 -1
- package/build/types/integrations/flue.d.ts +2 -1
- package/build/types/integrations/flue.d.ts.map +1 -1
- package/build/types/integrations/google-genai.d.ts +2 -1
- package/build/types/integrations/google-genai.d.ts.map +1 -1
- package/build/types/integrations/groq.d.ts +1 -1
- package/build/types/integrations/langchain.d.ts +2 -1
- package/build/types/integrations/langchain.d.ts.map +1 -1
- package/build/types/integrations/langgraph.d.ts +2 -1
- package/build/types/integrations/langgraph.d.ts.map +1 -1
- package/build/types/integrations/mistral.d.ts +2 -1
- package/build/types/integrations/mistral.d.ts.map +1 -1
- package/build/types/integrations/openai-compatible.d.ts.map +1 -1
- package/build/types/integrations/openai.d.ts +2 -1
- package/build/types/integrations/openai.d.ts.map +1 -1
- package/build/types/integrations/pi-ai.d.ts +6 -3
- package/build/types/integrations/pi-ai.d.ts.map +1 -1
- package/build/types/integrations/pi-durable.d.ts +2 -1
- package/build/types/integrations/pi-durable.d.ts.map +1 -1
- package/build/types/integrations/pino.d.ts +61 -0
- package/build/types/integrations/pino.d.ts.map +1 -0
- package/build/types/integrations/together-ai.d.ts +1 -1
- package/build/types/integrations/typesafe.d.ts +2 -2
- package/build/types/integrations/typesafe.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/index.d.ts +3 -3
- package/build/types/integrations/vercel-ai/index.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/util.d.ts +2 -1
- package/build/types/integrations/vercel-ai/util.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts +20 -4
- package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.d.ts.map +1 -1
- package/build/types/integrations/winston.d.ts +55 -0
- package/build/types/integrations/winston.d.ts.map +1 -0
- package/package.json +3 -3
|
@@ -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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AS;CAC/B,MAAM,gBACJ,OAAO,cAAc,YAAY,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,0B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,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,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,cAA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O,eAAe,CAAC,cAAc,IACjC,cAAc;IAAE;IAAa,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;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,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,KAAK,WAAW,OAAO;KAClD;IACF,KAAK;KACH,YAAY,aAAa,SAAS;KAClC;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,19 +1,12 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { runGenAiSpanEnd, runGenAiSpanStart } from "../core/span-hooks.js";
|
|
2
|
+
import { getGenAiSpanOp, resolveGenAiCallRecording } from "../core/utils.js";
|
|
2
3
|
import { piAiContentToString } from "../pi-ai/messages.js";
|
|
3
4
|
import { FLUE_ORIGIN } from "./constants.js";
|
|
4
5
|
import { GEN_AI_CONVERSATION_ID, GEN_AI_OPERATION_NAME, GEN_AI_TOOL_CALL_ARGUMENTS, GEN_AI_TOOL_CALL_RESULT, GEN_AI_TOOL_NAME, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
|
|
5
6
|
import { SPAN_STATUS_ERROR, captureException, isObjectLike, startInactiveSpan, stringify, withActiveSpan } from "@sentry/core";
|
|
6
7
|
// src/ai/flue/utils.ts
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
* Sentry's own propagation uses `sentry-trace`, so the carrier has to be converted before it can
|
|
10
|
-
* continue the trace. Kept local until something else needs a W3C parser.
|
|
11
|
-
*/
|
|
12
|
-
function sentryTraceFromTraceparent(traceparent) {
|
|
13
|
-
const [version, traceId, spanId, flags] = traceparent.split("-");
|
|
14
|
-
if (version !== "00" || !traceId || !spanId || !flags) return;
|
|
15
|
-
return `${traceId}-${spanId}-${parseInt(flags, 16) % 2 === 1 ? "1" : "0"}`;
|
|
16
|
-
}
|
|
8
|
+
const TOOL_SPANS_RECORDING_OUTPUTS = /* @__PURE__ */ new WeakSet();
|
|
9
|
+
const TOOL_SPAN_END_HOOKS = /* @__PURE__ */ new WeakMap();
|
|
17
10
|
/**
|
|
18
11
|
* Store a span under `key`. Callers only reach this with a key the tracker does not hold, so the
|
|
19
12
|
* one span at risk of being dropped without `end()` is the oldest entry, which `LRUMap.set` silently
|
|
@@ -54,10 +47,16 @@ function captureToolError(span, errorInfo) {
|
|
|
54
47
|
* OpenTelemetry adapter projects them: siblings of `chat`, correlated to model output by tool call
|
|
55
48
|
* id. Keyed by `toolCallId` so concurrent tool calls in one turn cannot cross-attribute.
|
|
56
49
|
*/
|
|
57
|
-
function startToolSpan(observation, toolSpans,
|
|
50
|
+
function startToolSpan(observation, context, toolSpans, options) {
|
|
58
51
|
const { toolCallId, toolName } = observation;
|
|
59
52
|
if (!toolCallId || toolSpans.get(toolCallId)) return;
|
|
60
|
-
|
|
53
|
+
const call = {
|
|
54
|
+
operation: "execute_tool",
|
|
55
|
+
observation,
|
|
56
|
+
context
|
|
57
|
+
};
|
|
58
|
+
const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);
|
|
59
|
+
const span = startInactiveSpan({
|
|
61
60
|
name: `execute_tool ${toolName ?? "unknown"}`,
|
|
62
61
|
op: getGenAiSpanOp("execute_tool"),
|
|
63
62
|
attributes: {
|
|
@@ -67,14 +66,21 @@ function startToolSpan(observation, toolSpans, recordInputs) {
|
|
|
67
66
|
[GEN_AI_CONVERSATION_ID]: observation.conversationId,
|
|
68
67
|
...recordInputs && observation.args !== void 0 ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(observation.args) } : {}
|
|
69
68
|
}
|
|
70
|
-
})
|
|
69
|
+
});
|
|
70
|
+
if (recordOutputs) TOOL_SPANS_RECORDING_OUTPUTS.add(span);
|
|
71
|
+
runGenAiSpanStart(options, span, call);
|
|
72
|
+
TOOL_SPAN_END_HOOKS.set(span, (end) => runGenAiSpanEnd(options, span, call, end.isError ? {
|
|
73
|
+
response: end,
|
|
74
|
+
error: end.errorInfo
|
|
75
|
+
} : { response: end }));
|
|
76
|
+
trackSpan(toolSpans, toolCallId, span);
|
|
71
77
|
}
|
|
72
|
-
function endToolSpan(observation, toolSpans
|
|
78
|
+
function endToolSpan(observation, toolSpans) {
|
|
73
79
|
const { toolCallId } = observation;
|
|
74
80
|
const span = toolCallId ? toolSpans.get(toolCallId) : void 0;
|
|
75
81
|
if (!span || !toolCallId) return;
|
|
76
82
|
toolSpans.remove(toolCallId);
|
|
77
|
-
if (
|
|
83
|
+
if (TOOL_SPANS_RECORDING_OUTPUTS.has(span)) {
|
|
78
84
|
const result = toolResultForModel(observation);
|
|
79
85
|
if (result !== void 0) span.setAttribute(GEN_AI_TOOL_CALL_RESULT, result);
|
|
80
86
|
}
|
|
@@ -85,6 +91,7 @@ function endToolSpan(observation, toolSpans, recordOutputs) {
|
|
|
85
91
|
});
|
|
86
92
|
captureToolError(span, observation.errorInfo);
|
|
87
93
|
}
|
|
94
|
+
TOOL_SPAN_END_HOOKS.get(span)?.(observation);
|
|
88
95
|
span.end();
|
|
89
96
|
}
|
|
90
97
|
/**
|
|
@@ -101,6 +108,6 @@ function toolResultForModel(observation) {
|
|
|
101
108
|
if (isObjectLike(result) && Array.isArray(result.content)) return piAiContentToString(result.content);
|
|
102
109
|
return result === void 0 ? void 0 : stringify(result);
|
|
103
110
|
}
|
|
104
|
-
export { endToolSpan,
|
|
111
|
+
export { endToolSpan, startToolSpan };
|
|
105
112
|
|
|
106
113
|
//# sourceMappingURL=utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":[],"sources":["../../../../src/ai/flue/utils.ts"],"sourcesContent":["import type { LRUMap, Span } from '@sentry/core';\nimport {\n captureException,\n isObjectLike,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n stringify,\n withActiveSpan,\n} from '@sentry/core';\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_OPERATION_NAME,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_NAME,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport {
|
|
1
|
+
{"version":3,"file":"utils.js","names":[],"sources":["../../../../src/ai/flue/utils.ts"],"sourcesContent":["import type { LRUMap, Span } from '@sentry/core';\nimport {\n captureException,\n isObjectLike,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n stringify,\n withActiveSpan,\n} from '@sentry/core';\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_OPERATION_NAME,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_NAME,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport type { GenAiSpanHooks } from '../core/span-hooks';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { GenAiCallOptions } from '../core/utils';\nimport { getGenAiSpanOp, resolveGenAiCallRecording } from '../core/utils';\nimport { piAiContentToString } from '../pi-ai/messages';\nimport { FLUE_ORIGIN, MAX_TRACKED_FLUE_SPANS } from './constants';\nimport type { FlueCallInfo, FlueErrorInfo, FlueEventContext, FlueObservation } from './types';\n\n/**\n * Turn and tool spans, keyed by the id of the work they cover. Bounded, because the key is only\n * removed when the matching end observation arrives and an abandoned stream never emits one.\n */\nexport type SpanTracker = LRUMap<string, Span>;\n\nconst TOOL_SPANS_RECORDING_OUTPUTS = new WeakSet<Span>();\nconst TOOL_SPAN_END_HOOKS = new WeakMap<Span, (observation: FlueObservation) => void>();\n\n/**\n * Store a span under `key`. Callers only reach this with a key the tracker does not hold, so the\n * one span at risk of being dropped without `end()` is the oldest entry, which `LRUMap.set` silently\n * evicts once the tracker is full.\n */\nfunction trackSpan(tracker: SpanTracker, key: string, span: Span): void {\n if (tracker.size >= MAX_TRACKED_FLUE_SPANS) {\n const oldestKey = tracker.keys()[0];\n if (oldestKey !== undefined) {\n tracker.remove(oldestKey)?.end();\n }\n }\n\n tracker.set(key, span);\n}\n\n/**\n * Report a failed tool as an error event.\n *\n * Flue catches whatever the tool threw and hands it back to the model as a tool result, so nothing\n * propagates for the SDK's global handlers to see: without this a throwing tool produces an errored\n * span and no issue at all. `errorInfo` carries the original name, message and stack, so rebuild an\n * `Error` from it rather than capturing the serialized shape.\n *\n * Tools only. A failed turn carries no `errorInfo` — a provider auth failure produces an errored\n * `chat` span and nothing to rebuild from — so there is no turn equivalent to capture.\n */\nfunction captureToolError(span: Span, errorInfo: FlueErrorInfo | undefined): void {\n if (!errorInfo) {\n return;\n }\n\n const error = new Error(errorInfo.message ?? 'Flue tool failed');\n error.name = errorInfo.name ?? errorInfo.type ?? 'Error';\n if (errorInfo.stack) {\n error.stack = errorInfo.stack;\n }\n\n // Captured under the operation's own span so the issue lands on the right trace, matching how the\n // Mastra integration attaches its captures.\n withActiveSpan(span, () => {\n // Handled: this is not a rejection observed on a tracing channel, where the handled state is\n // unknowable. Flue caught the throw and returned it to the model as a tool result, so it is\n // definitively handled and no global hook will ever see it.\n captureException(error, { mechanism: { handled: true, type: FLUE_ORIGIN } });\n });\n}\n\n/**\n * Tool spans hang off the agent invocation rather than the turn, matching how Flue's own\n * OpenTelemetry adapter projects them: siblings of `chat`, correlated to model output by tool call\n * id. Keyed by `toolCallId` so concurrent tool calls in one turn cannot cross-attribute.\n */\nexport function startToolSpan(\n observation: FlueObservation,\n context: FlueEventContext,\n toolSpans: SpanTracker,\n options: GenAiCallOptions<FlueCallInfo> & GenAiSpanHooks<FlueCallInfo, FlueObservation>,\n): void {\n const { toolCallId, toolName } = observation;\n if (!toolCallId || toolSpans.get(toolCallId)) {\n return;\n }\n\n const call: FlueCallInfo = { operation: 'execute_tool', observation, context };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n const span = startInactiveSpan({\n name: `execute_tool ${toolName ?? 'unknown'}`,\n op: getGenAiSpanOp('execute_tool'),\n attributes: {\n [SENTRY_ORIGIN]: FLUE_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'execute_tool',\n [GEN_AI_TOOL_NAME]: toolName,\n [GEN_AI_CONVERSATION_ID]: observation.conversationId,\n ...(recordInputs && observation.args !== undefined\n ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(observation.args) }\n : {}),\n },\n });\n if (recordOutputs) {\n TOOL_SPANS_RECORDING_OUTPUTS.add(span);\n }\n runGenAiSpanStart(options, span, call);\n TOOL_SPAN_END_HOOKS.set(span, end =>\n runGenAiSpanEnd(options, span, call, end.isError ? { response: end, error: end.errorInfo } : { response: end }),\n );\n trackSpan(toolSpans, toolCallId, span);\n}\n\nexport function endToolSpan(observation: FlueObservation, toolSpans: SpanTracker): void {\n const { toolCallId } = observation;\n const span = toolCallId ? toolSpans.get(toolCallId) : undefined;\n if (!span || !toolCallId) {\n return;\n }\n toolSpans.remove(toolCallId);\n\n if (TOOL_SPANS_RECORDING_OUTPUTS.has(span)) {\n const result = toolResultForModel(observation);\n if (result !== undefined) {\n span.setAttribute(GEN_AI_TOOL_CALL_RESULT, result);\n }\n }\n\n if (observation.isError) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n captureToolError(span, observation.errorInfo);\n }\n TOOL_SPAN_END_HOOKS.get(span)?.(observation);\n span.end();\n}\n\n/**\n * The result the model receives: Flue's `effectiveResult` when it has one, else the content blocks\n * of its harness-level `result` (`{ content, details }`, whose `details` payload is tool-specific).\n */\nfunction toolResultForModel(observation: FlueObservation): string | undefined {\n const { effectiveResult } = observation;\n if (effectiveResult !== undefined) {\n if (typeof effectiveResult === 'string') {\n return effectiveResult;\n }\n return Array.isArray(effectiveResult) ? piAiContentToString(effectiveResult) : stringify(effectiveResult);\n }\n const { result } = observation;\n if (isObjectLike(result) && Array.isArray(result.content)) {\n return piAiContentToString(result.content);\n }\n return result === undefined ? undefined : stringify(result);\n}\n"],"mappings":";;;;;;;AA+BA,MAAM,+CAA+B,IAAI,QAAc;AACvD,MAAM,sCAAsB,IAAI,QAAsD;;;;;;AAOtF,SAAS,UAAU,SAAsB,KAAa,MAAkB;CACtE,IAAI,QAAQ,QAAA,KAAgC;EAC1C,MAAM,YAAY,QAAQ,KAAK,CAAC,CAAC;EACjC,IAAI,cAAc,KAAA,GAChB,QAAQ,OAAO,SAAS,CAAC,EAAE,IAAI;CAEnC;CAEA,QAAQ,IAAI,KAAK,IAAI;AACvB;;;;;;;;;;;;AAaA,SAAS,iBAAiB,MAAY,WAA4C;CAChF,IAAI,CAAC,WACH;CAGF,MAAM,QAAQ,IAAI,MAAM,UAAU,WAAW,kBAAkB;CAC/D,MAAM,OAAO,UAAU,QAAQ,UAAU,QAAQ;CACjD,IAAI,UAAU,OACZ,MAAM,QAAQ,UAAU;CAK1B,eAAe,YAAY;EAIzB,iBAAiB,OAAO,EAAE,WAAW;GAAE,SAAS;GAAM,MAAM;EAAY,EAAE,CAAC;CAC7E,CAAC;AACH;;;;;;AAOA,SAAgB,cACd,aACA,SACA,WACA,SACM;CACN,MAAM,EAAE,YAAY,aAAa;CACjC,IAAI,CAAC,cAAc,UAAU,IAAI,UAAU,GACzC;CAGF,MAAM,OAAqB;EAAE,WAAW;EAAgB;EAAa;CAAQ;CAC7E,MAAM,EAAE,cAAc,kBAAkB,0BAA0B,SAAS,IAAI;CAC/E,MAAM,OAAO,kBAAkB;EAC7B,MAAM,gBAAgB,YAAY;EAClC,IAAI,eAAe,cAAc;EACjC,YAAY;IACT,gBAAgB;IAChB,wBA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AAW,KAAA,IAAY,KAAA,IAAY,UAAU,MAAM;AAC5D"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { runGenAiSpanEnd, runGenAiSpanStart } from "../core/span-hooks.js";
|
|
2
|
+
import { buildMethodPath, getErrorStatus, getGenAiSpanOp, getRequestSignal, getTokenUsageAttributes, resolveGenAiCallRecording } from "../core/utils.js";
|
|
2
3
|
import { GOOGLE_GENAI_METHOD_REGISTRY, GOOGLE_GENAI_SYSTEM_NAME } from "./constants.js";
|
|
3
4
|
import { addDecisionResponseAttributes, getDecisionInputMessages } from "./decisions.js";
|
|
4
5
|
import { instrumentStream } from "./streaming.js";
|
|
@@ -153,9 +154,14 @@ function instrumentMethod(originalMethod, methodPath, instrumentedMethod, contex
|
|
|
153
154
|
return new Proxy(originalMethod, { apply(target, _, args) {
|
|
154
155
|
const operationName = instrumentedMethod.operation || "unknown";
|
|
155
156
|
const params = args[0];
|
|
157
|
+
const call = {
|
|
158
|
+
operation: operationName,
|
|
159
|
+
request: params
|
|
160
|
+
};
|
|
161
|
+
const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);
|
|
156
162
|
const attributeParams = resolveChatParams(operationName, params, context);
|
|
157
163
|
const abortSignal = getCallAbortSignal(operationName, attributeParams, args[1]);
|
|
158
|
-
const requestAttributes = extractRequestAttributes(operationName, attributeParams, context,
|
|
164
|
+
const requestAttributes = extractRequestAttributes(operationName, attributeParams, context, recordInputs);
|
|
159
165
|
const model = requestAttributes[GEN_AI_REQUEST_MODEL] || "unknown";
|
|
160
166
|
const client = getClient();
|
|
161
167
|
const spanName = typeof model === "string" && model !== "unknown" || !(client && hasSpanStreamingEnabled(client)) ? `${operationName} ${model}` : operationName;
|
|
@@ -165,11 +171,13 @@ function instrumentMethod(originalMethod, methodPath, instrumentedMethod, contex
|
|
|
165
171
|
attributes: requestAttributes
|
|
166
172
|
}, async (span) => {
|
|
167
173
|
try {
|
|
168
|
-
if (
|
|
174
|
+
if (recordInputs && attributeParams) addPrivateRequestAttributes(span, attributeParams, operationName);
|
|
175
|
+
runGenAiSpanStart(options, span, call);
|
|
169
176
|
const stream = await target.apply(context, args);
|
|
170
|
-
return instrumentStream(stream, span,
|
|
177
|
+
return instrumentStream(stream, span, recordOutputs, abortSignal, (result) => runGenAiSpanEnd(options, span, call, result));
|
|
171
178
|
} catch (error) {
|
|
172
179
|
span.setStatus(getErrorStatus(abortSignal));
|
|
180
|
+
runGenAiSpanEnd(options, span, call, { error });
|
|
173
181
|
span.end();
|
|
174
182
|
throw error;
|
|
175
183
|
}
|
|
@@ -179,9 +187,14 @@ function instrumentMethod(originalMethod, methodPath, instrumentedMethod, contex
|
|
|
179
187
|
op: getGenAiSpanOp(operationName),
|
|
180
188
|
attributes: requestAttributes
|
|
181
189
|
}, (span) => {
|
|
182
|
-
if (
|
|
183
|
-
|
|
184
|
-
|
|
190
|
+
if (recordInputs && attributeParams) addPrivateRequestAttributes(span, attributeParams, operationName);
|
|
191
|
+
runGenAiSpanStart(options, span, call);
|
|
192
|
+
return handleCallbackErrors(() => target.apply(context, args), (error) => {
|
|
193
|
+
span.setStatus(getErrorStatus(abortSignal));
|
|
194
|
+
runGenAiSpanEnd(options, span, call, { error });
|
|
195
|
+
}, () => {}, (result) => {
|
|
196
|
+
if (!isEmbeddings) addResponseAttributes(span, result, recordOutputs, operationName);
|
|
197
|
+
runGenAiSpanEnd(options, span, call, { response: result });
|
|
185
198
|
});
|
|
186
199
|
});
|
|
187
200
|
} });
|
|
@@ -263,7 +276,7 @@ function createDeepProxy(target, currentPath = "", options) {
|
|
|
263
276
|
* ```
|
|
264
277
|
*/
|
|
265
278
|
function instrumentGoogleGenAIClient(client, options) {
|
|
266
|
-
return createDeepProxy(client, "",
|
|
279
|
+
return createDeepProxy(client, "", options ?? {});
|
|
267
280
|
}
|
|
268
281
|
export { addPrivateRequestAttributes, addResponseAttributes, extractModel, extractRequestAttributes, getAbortSignal, getCallAbortSignal, instrumentGoogleGenAIClient, resolveChatParams };
|
|
269
282
|
|