@sentry/server-utils 11.19.0 → 11.20.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/index.js +96 -73
- package/build/cjs/index.js.map +1 -1
- package/build/esm/ai/vercel-ai/index.js +1 -12
- package/build/esm/ai/vercel-ai/index.js.map +1 -1
- package/build/esm/integrations/nitro/captureTracingEvents.js +4 -3
- package/build/esm/integrations/nitro/captureTracingEvents.js.map +1 -1
- package/build/esm/integrations/nitro/index.js +2 -2
- package/build/esm/integrations/nitro/index.js.map +1 -1
- package/build/esm/integrations/openai-compatible.js.map +1 -1
- package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js +70 -42
- 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 +21 -16
- package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/types/ai/vercel-ai/index.d.ts +0 -6
- package/build/types/ai/vercel-ai/index.d.ts.map +1 -1
- package/build/types/integrations/nitro/captureTracingEvents.d.ts +3 -1
- package/build/types/integrations/nitro/captureTracingEvents.d.ts.map +1 -1
- package/build/types/integrations/nitro/index.d.ts +6 -0
- package/build/types/integrations/nitro/index.d.ts.map +1 -1
- package/build/types/integrations/openai-compatible.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts.map +1 -1
- package/package.json +3 -3
|
@@ -43,22 +43,11 @@ function getProviderMetadataAttributes(providerMetadata) {
|
|
|
43
43
|
return attributes;
|
|
44
44
|
}
|
|
45
45
|
/**
|
|
46
|
-
* Usage attributes derived from `providerMetadata`, which describes only the last step of a call.
|
|
47
|
-
* They must not be written onto a span that reports usage aggregated across steps
|
|
48
|
-
* (`gen_ai.invoke_agent`), where they would replace the aggregate with one step's figures.
|
|
49
|
-
*/
|
|
50
|
-
const LAST_STEP_ONLY_USAGE_KEYS = /* @__PURE__ */ new Set([
|
|
51
|
-
GEN_AI_USAGE_OUTPUT_TOKENS,
|
|
52
|
-
GEN_AI_USAGE_TOTAL_TOKENS,
|
|
53
|
-
GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,
|
|
54
|
-
GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS
|
|
55
|
-
]);
|
|
56
|
-
/**
|
|
57
46
|
* Sets an attribute only if the value is not null or undefined.
|
|
58
47
|
*/
|
|
59
48
|
function setAttributeIfDefined(attributes, key, value) {
|
|
60
49
|
if (value != null) attributes[key] = value;
|
|
61
50
|
}
|
|
62
|
-
export {
|
|
51
|
+
export { getProviderMetadataAttributes };
|
|
63
52
|
|
|
64
53
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/ai/vercel-ai/index.ts"],"sourcesContent":["import type { SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_COST_TOTAL_TOKENS,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_READ_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 type { OpenAiProviderMetadata, ProviderMetadata } from './vercel-ai-attributes';\n\n/**\n * Derive the `gen_ai.usage.*` cache/reasoning/prediction token attributes from an AI SDK\n * `providerMetadata` object.\n *\n * Used by the `ai` >= 7 tracing-channel subscriber, which receives `providerMetadata` as an object on\n * the channel result. Pass the already-parsed object; unknown/empty input yields `{}`.\n */\nexport function getProviderMetadataAttributes(providerMetadata: unknown): Record<string, number | string> {\n const attributes: Record<string, number | string> = {};\n\n if (!providerMetadata || typeof providerMetadata !== 'object') {\n return attributes;\n }\n const metadata = providerMetadata as ProviderMetadata;\n\n // OpenAI (v5 uses 'openai', v6 Azure Responses API uses 'azure')\n const openaiMetadata: OpenAiProviderMetadata | undefined = metadata.openai ?? metadata.azure;\n if (openaiMetadata) {\n setAttributeIfDefined(attributes, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, openaiMetadata.cachedPromptTokens);\n setAttributeIfDefined(attributes, GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, openaiMetadata.reasoningTokens);\n setAttributeIfDefined(\n attributes,\n 'gen_ai.usage.output_tokens.prediction_accepted',\n openaiMetadata.acceptedPredictionTokens,\n );\n setAttributeIfDefined(\n attributes,\n 'gen_ai.usage.output_tokens.prediction_rejected',\n openaiMetadata.rejectedPredictionTokens,\n );\n }\n\n if (metadata.anthropic) {\n const cachedInputTokens =\n metadata.anthropic.usage?.cache_read_input_tokens ?? metadata.anthropic.cacheReadInputTokens;\n setAttributeIfDefined(attributes, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cachedInputTokens);\n\n const cacheWriteInputTokens =\n metadata.anthropic.usage?.cache_creation_input_tokens ?? metadata.anthropic.cacheCreationInputTokens;\n setAttributeIfDefined(attributes, GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cacheWriteInputTokens);\n }\n\n if (metadata.bedrock?.usage) {\n setAttributeIfDefined(\n attributes,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n metadata.bedrock.usage.cacheReadInputTokens,\n );\n setAttributeIfDefined(\n attributes,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n metadata.bedrock.usage.cacheWriteInputTokens,\n );\n }\n\n if (metadata.deepseek) {\n setAttributeIfDefined(attributes, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, metadata.deepseek.promptCacheHitTokens);\n setAttributeIfDefined(attributes, 'gen_ai.usage.input_tokens.cache_miss', metadata.deepseek.promptCacheMissTokens);\n }\n\n // Google (v5 uses 'google', v6 Vertex AI uses 'vertex'). Gemini reports its reasoning (\"thoughts\")\n // tokens separately from the candidate output count, so the SDK's `outputTokens` covers only the\n // visible answer. Recompute output from `candidatesTokenCount + thoughtsTokenCount` rather than\n // adding onto the existing value, which stays correct on `ai` v6+ where `outputTokens` already\n // folds reasoning in. `candidatesTokenCount` is omitted when the response is truncated during\n // thinking, which means no candidate tokens, so it counts as zero. Reasoning is a subset of\n // output per the conventions, so it is only written alongside the output it belongs to.\n const googleUsage = (metadata.google ?? metadata.vertex)?.usageMetadata;\n if (googleUsage && typeof googleUsage.thoughtsTokenCount === 'number' && googleUsage.thoughtsTokenCount > 0) {\n attributes[GEN_AI_USAGE_OUTPUT_TOKENS] = (googleUsage.candidatesTokenCount ?? 0) + googleUsage.thoughtsTokenCount;\n setAttributeIfDefined(attributes, GEN_AI_USAGE_TOTAL_TOKENS, googleUsage.totalTokenCount);\n setAttributeIfDefined(attributes, GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, googleUsage.thoughtsTokenCount);\n }\n\n // Vercel AI Gateway reports the billed USD cost of the call, as a decimal string.\n const gatewayCost = Number(metadata.gateway?.cost);\n if (metadata.gateway?.cost != null && Number.isFinite(gatewayCost)) {\n attributes[GEN_AI_COST_TOTAL_TOKENS] = gatewayCost;\n }\n\n return attributes;\n}\n\n/**\n *
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/ai/vercel-ai/index.ts"],"sourcesContent":["import type { SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_COST_TOTAL_TOKENS,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_READ_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 type { OpenAiProviderMetadata, ProviderMetadata } from './vercel-ai-attributes';\n\n/**\n * Derive the `gen_ai.usage.*` cache/reasoning/prediction token attributes from an AI SDK\n * `providerMetadata` object.\n *\n * Used by the `ai` >= 7 tracing-channel subscriber, which receives `providerMetadata` as an object on\n * the channel result. Pass the already-parsed object; unknown/empty input yields `{}`.\n */\nexport function getProviderMetadataAttributes(providerMetadata: unknown): Record<string, number | string> {\n const attributes: Record<string, number | string> = {};\n\n if (!providerMetadata || typeof providerMetadata !== 'object') {\n return attributes;\n }\n const metadata = providerMetadata as ProviderMetadata;\n\n // OpenAI (v5 uses 'openai', v6 Azure Responses API uses 'azure')\n const openaiMetadata: OpenAiProviderMetadata | undefined = metadata.openai ?? metadata.azure;\n if (openaiMetadata) {\n setAttributeIfDefined(attributes, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, openaiMetadata.cachedPromptTokens);\n setAttributeIfDefined(attributes, GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, openaiMetadata.reasoningTokens);\n setAttributeIfDefined(\n attributes,\n 'gen_ai.usage.output_tokens.prediction_accepted',\n openaiMetadata.acceptedPredictionTokens,\n );\n setAttributeIfDefined(\n attributes,\n 'gen_ai.usage.output_tokens.prediction_rejected',\n openaiMetadata.rejectedPredictionTokens,\n );\n }\n\n if (metadata.anthropic) {\n const cachedInputTokens =\n metadata.anthropic.usage?.cache_read_input_tokens ?? metadata.anthropic.cacheReadInputTokens;\n setAttributeIfDefined(attributes, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cachedInputTokens);\n\n const cacheWriteInputTokens =\n metadata.anthropic.usage?.cache_creation_input_tokens ?? metadata.anthropic.cacheCreationInputTokens;\n setAttributeIfDefined(attributes, GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cacheWriteInputTokens);\n }\n\n if (metadata.bedrock?.usage) {\n setAttributeIfDefined(\n attributes,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n metadata.bedrock.usage.cacheReadInputTokens,\n );\n setAttributeIfDefined(\n attributes,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n metadata.bedrock.usage.cacheWriteInputTokens,\n );\n }\n\n if (metadata.deepseek) {\n setAttributeIfDefined(attributes, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, metadata.deepseek.promptCacheHitTokens);\n setAttributeIfDefined(attributes, 'gen_ai.usage.input_tokens.cache_miss', metadata.deepseek.promptCacheMissTokens);\n }\n\n // Google (v5 uses 'google', v6 Vertex AI uses 'vertex'). Gemini reports its reasoning (\"thoughts\")\n // tokens separately from the candidate output count, so the SDK's `outputTokens` covers only the\n // visible answer. Recompute output from `candidatesTokenCount + thoughtsTokenCount` rather than\n // adding onto the existing value, which stays correct on `ai` v6+ where `outputTokens` already\n // folds reasoning in. `candidatesTokenCount` is omitted when the response is truncated during\n // thinking, which means no candidate tokens, so it counts as zero. Reasoning is a subset of\n // output per the conventions, so it is only written alongside the output it belongs to.\n const googleUsage = (metadata.google ?? metadata.vertex)?.usageMetadata;\n if (googleUsage && typeof googleUsage.thoughtsTokenCount === 'number' && googleUsage.thoughtsTokenCount > 0) {\n attributes[GEN_AI_USAGE_OUTPUT_TOKENS] = (googleUsage.candidatesTokenCount ?? 0) + googleUsage.thoughtsTokenCount;\n setAttributeIfDefined(attributes, GEN_AI_USAGE_TOTAL_TOKENS, googleUsage.totalTokenCount);\n setAttributeIfDefined(attributes, GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, googleUsage.thoughtsTokenCount);\n }\n\n // Vercel AI Gateway reports the billed USD cost of the call, as a decimal string.\n const gatewayCost = Number(metadata.gateway?.cost);\n if (metadata.gateway?.cost != null && Number.isFinite(gatewayCost)) {\n attributes[GEN_AI_COST_TOTAL_TOKENS] = gatewayCost;\n }\n\n return attributes;\n}\n\n/**\n * Sets an attribute only if the value is not null or undefined.\n */\nfunction setAttributeIfDefined(\n attributes: Record<string, unknown>,\n key: string,\n value: SpanAttributeValue | undefined,\n): void {\n if (value != null) {\n attributes[key] = value;\n }\n}\n"],"mappings":";;;;;;;;;AAkBA,SAAgB,8BAA8B,kBAA4D;CACxG,MAAM,aAA8C,CAAC;CAErD,IAAI,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"}
|
|
@@ -8,10 +8,10 @@ import { HANDLER, HTTP_SERVER, MIDDLEWARE } from "@sentry/conventions/op";
|
|
|
8
8
|
/**
|
|
9
9
|
* Captures tracing events emitted by Nitro tracing channels.
|
|
10
10
|
*/
|
|
11
|
-
function captureTracingEvents() {
|
|
11
|
+
function captureTracingEvents(options) {
|
|
12
12
|
const globalWithTraceChannels = GLOBAL_OBJ;
|
|
13
13
|
if (globalWithTraceChannels.__SENTRY_NITRO_HTTP_CHANNELS_INSTRUMENTED__) return;
|
|
14
|
-
setupH3TracingChannels();
|
|
14
|
+
setupH3TracingChannels(options);
|
|
15
15
|
setupSrvxTracingChannels();
|
|
16
16
|
globalWithTraceChannels.__SENTRY_NITRO_HTTP_CHANNELS_INSTRUMENTED__ = true;
|
|
17
17
|
}
|
|
@@ -54,9 +54,10 @@ function getParameterizedRoute(event) {
|
|
|
54
54
|
if (!routePath || routePath === "/**") return;
|
|
55
55
|
return routePath;
|
|
56
56
|
}
|
|
57
|
-
function setupH3TracingChannels() {
|
|
57
|
+
function setupH3TracingChannels(options) {
|
|
58
58
|
if (!tracingChannel) return;
|
|
59
59
|
bindTracingChannelToSpan(tracingChannel("h3.request"), (data) => {
|
|
60
|
+
if (data.type === "middleware" && !options.middleware) return;
|
|
60
61
|
const method = data.event.req.method?.toUpperCase() || HTTP_SPAN_NAME_FALLBACK;
|
|
61
62
|
if (data.type === "route" && hasHttpServerRootSpan()) {
|
|
62
63
|
const matchedRoute = data.event.context?.matchedRoute?.route;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"captureTracingEvents.js","names":["diagnosticsChannel.tracingChannel"],"sources":["../../../../src/integrations/nitro/captureTracingEvents.ts"],"sourcesContent":["import { SENTRY_OP, SENTRY_SEGMENT_NAME_SOURCE, SENTRY_ORIGIN, SERVER_PORT } from '@sentry/conventions/attributes';\nimport { HANDLER, HTTP_SERVER, MIDDLEWARE } from '@sentry/conventions/op';\nimport {\n isObjectLike,\n getActiveSpan,\n getClient,\n getHttpSpanDetailsFromUrlObject,\n getRootSpan,\n GLOBAL_OBJ,\n hasSpanStreamingEnabled,\n httpHeadersToSpanAttributes,\n HTTP_SPAN_NAME_FALLBACK,\n parseStringToURLObject,\n setHttpStatus,\n type Span,\n spanToJSON,\n startInactiveSpan,\n} from '@sentry/core';\nimport { bindTracingChannelToSpan, type TracingChannelPayloadWithSpan } from '../../tracing-channel';\nimport * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport { setHttpServerSpanRouteAttribute } from '../../utils/setHttpServerSpanRouteAttribute';\nimport type { H3TracingRequestEvent, NitroH3Event, SrvxRequestEvent } from './nitroTypes';\n\ntype GlobalWithTraceChannels = typeof GLOBAL_OBJ & {\n __SENTRY_NITRO_HTTP_CHANNELS_INSTRUMENTED__?: boolean;\n};\n\n/**\n * Captures tracing events emitted by Nitro tracing channels.\n */\nexport function captureTracingEvents(): void {\n // Resolved at call time: bundlers may evaluate this module before `GLOBAL_OBJ` is initialized.\n const globalWithTraceChannels = GLOBAL_OBJ as GlobalWithTraceChannels;\n if (globalWithTraceChannels.__SENTRY_NITRO_HTTP_CHANNELS_INSTRUMENTED__) {\n return;\n }\n\n setupH3TracingChannels();\n setupSrvxTracingChannels();\n globalWithTraceChannels.__SENTRY_NITRO_HTTP_CHANNELS_INSTRUMENTED__ = true;\n}\n\n/**\n * Extracts the HTTP status code from a tracing channel result.\n * The result is the return value of the traced handler, which is a Response for srvx\n * and may or may not be a Response for h3.\n */\nfunction getResponseStatusCode(result: unknown): number | undefined {\n if (isObjectLike(result) && 'status' in result && typeof result.status === 'number') {\n return result.status;\n }\n return undefined;\n}\n\n/** Applies the HTTP status from the traced handler's result to the span, when present. */\nfunction applyResponseStatus(span: Span, data: TracingChannelPayloadWithSpan<{ result?: unknown }>): void {\n const statusCode = getResponseStatusCode(data.result);\n if (statusCode !== undefined) {\n setHttpStatus(span, statusCode);\n }\n}\n\n/**\n * Whether the request already has an `http.server` root span, created by the runtime's own HTTP\n * server instrumentation (Node `http`, `Bun.serve`, `Deno.serve`, Cloudflare's request wrapper).\n */\nfunction hasHttpServerRootSpan(): boolean {\n const activeSpan = getActiveSpan();\n return !!activeSpan && spanToJSON(getRootSpan(activeSpan)).attributes[SENTRY_OP] === HTTP_SERVER;\n}\n\n/**\n * The port the srvx server listens on. `options.port` is only the configured one, which is `0` for a\n * random port.\n */\nfunction getServerPort(server: SrvxRequestEvent['server']): number | undefined {\n const url = server.url ? parseStringToURLObject(server.url) : undefined;\n const port = url && 'port' in url ? Number(url.port) : undefined;\n return port || server.options.port || undefined;\n}\n\n/**\n * Extracts the parameterized route pattern from the h3 event context.\n */\nfunction getParameterizedRoute(event: NitroH3Event): string | undefined {\n const matchedRoute = event.context?.matchedRoute;\n if (!matchedRoute) {\n return undefined;\n }\n\n const routePath = matchedRoute.route;\n\n // Skip catch-all routes as they're not useful for transaction grouping\n if (!routePath || routePath === '/**') {\n return undefined;\n }\n\n return routePath;\n}\n\nfunction setupH3TracingChannels(): void {\n // Bail if this is not available\n if (!diagnosticsChannel.tracingChannel) {\n return;\n }\n\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<H3TracingRequestEvent>('h3.request'),\n data => {\n const method = data.event.req.method?.toUpperCase() || HTTP_SPAN_NAME_FALLBACK;\n\n // The route lives on the request's `http.server` root span, so the route handler only gets a\n // span that times the handler itself instead of yet another nested `http.server` span.\n if (data.type === 'route' && hasHttpServerRootSpan()) {\n const matchedRoute = data.event.context?.matchedRoute?.route;\n const span = startInactiveSpan({\n name: matchedRoute ? `${method} ${matchedRoute}` : method,\n attributes: {\n [SENTRY_ORIGIN]: 'auto.http.nitro.h3',\n [SENTRY_OP]: HANDLER,\n },\n });\n\n setParameterizedRouteAttributes(span, data.event);\n\n return span;\n }\n\n const parsedUrl = parseStringToURLObject(data.event.url.href);\n const routePattern = getParameterizedRoute(data.event);\n\n const [spanName, urlAttributes] = getHttpSpanDetailsFromUrlObject(\n parsedUrl,\n 'server',\n 'auto.http.nitro.h3',\n { method: data.event.req.method },\n routePattern,\n );\n\n const client = getClient();\n // With span streaming, span names have to be low cardinality, so we can't fall back to the URL.\n // Only applies to the http.server span; middleware spans keep their own naming.\n const isUnparameterizedStreamedServerSpan =\n data.type !== 'middleware' &&\n urlAttributes[SENTRY_SEGMENT_NAME_SOURCE] !== 'route' &&\n !!client &&\n hasSpanStreamingEnabled(client);\n\n const span = startInactiveSpan({\n name: isUnparameterizedStreamedServerSpan ? method : spanName,\n attributes: {\n ...urlAttributes,\n [SENTRY_ORIGIN]: 'auto.http.nitro.h3',\n [SENTRY_OP]: data.type === 'middleware' ? MIDDLEWARE : HTTP_SERVER,\n },\n });\n\n setParameterizedRouteAttributes(span, data.event);\n\n return span;\n },\n {\n beforeSpanEnd(span, data) {\n applyResponseStatus(span, data);\n\n // Update the root span with the parameterized route name. The root span is created before h3\n // resolves the route, so it initially has the raw URL.\n // Note: data.type is always 'middleware' here regardless of handler type, so we rely on\n // getParameterizedRoute() to filter out catch-all routes instead.\n const routePattern = getParameterizedRoute(data.event);\n if (routePattern) {\n setHttpServerSpanRouteAttribute(routePattern);\n }\n },\n },\n );\n}\n\nfunction setupSrvxTracingChannels(): void {\n if (!diagnosticsChannel.tracingChannel) {\n return;\n }\n\n // Store the parent span per-request so middleware and fetch share the same parent.\n // WeakMap ensures per-request isolation in concurrent environments and automatic cleanup.\n const requestParentSpans = new WeakMap<SrvxRequestEvent['request'], Span>();\n\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<SrvxRequestEvent>('srvx.request'),\n data => {\n // srvx only opens the request's `http.server` span when the runtime has not already created one.\n if (hasHttpServerRootSpan()) {\n return undefined;\n }\n\n const parsedUrl = data.request._url ? parseStringToURLObject(data.request._url.href) : undefined;\n const client = getClient();\n const [spanName, urlAttributes] = getHttpSpanDetailsFromUrlObject(\n parsedUrl,\n 'server',\n 'auto.http.nitro.srvx',\n { method: data.request.method },\n undefined,\n client,\n );\n\n const headerAttributes = client\n ? httpHeadersToSpanAttributes(\n Object.fromEntries(data.request.headers.entries()),\n client.getDataCollectionOptions(),\n )\n : {};\n\n // With span streaming, span names have to be low cardinality, so we can't fall back to the URL.\n // Only applies to the http.server span; middleware spans keep their own naming.\n // h3 renames this span via `setHttpServerSpanRouteAttribute` once it resolves the route.\n const isUnparameterizedStreamedServerSpan =\n !data.middleware &&\n urlAttributes[SENTRY_SEGMENT_NAME_SOURCE] !== 'route' &&\n !!client &&\n hasSpanStreamingEnabled(client);\n\n return startInactiveSpan({\n name: isUnparameterizedStreamedServerSpan\n ? data.request.method?.toUpperCase() || HTTP_SPAN_NAME_FALLBACK\n : spanName,\n attributes: {\n ...urlAttributes,\n ...headerAttributes,\n [SENTRY_ORIGIN]: 'auto.http.nitro.srvx',\n [SENTRY_OP]: data.middleware ? MIDDLEWARE : HTTP_SERVER,\n [SERVER_PORT]: getServerPort(data.server),\n },\n // Use the same parent span as middleware to make them siblings\n parentSpan: requestParentSpans.get(data.request) || undefined,\n });\n },\n {\n beforeSpanEnd(span, data) {\n applyResponseStatus(span, data);\n\n // Clean up parent span reference after the fetch handler completes (success or error).\n requestParentSpans.delete(data.request);\n },\n },\n );\n\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<SrvxRequestEvent>('srvx.middleware'),\n data => {\n // For the first middleware, capture the current parent span per-request\n if (data.middleware?.index === 0) {\n const activeSpan = getActiveSpan();\n if (activeSpan) {\n requestParentSpans.set(data.request, activeSpan);\n }\n }\n\n const parsedUrl = data.request._url ? parseStringToURLObject(data.request._url.href) : undefined;\n const [, urlAttributes] = getHttpSpanDetailsFromUrlObject(parsedUrl, 'server', 'auto.http.nitro.srvx', {\n method: data.request.method,\n });\n\n // Create span as a child of the original parent, not the previous middleware\n return startInactiveSpan({\n name: `${data.middleware?.handler.name ?? 'unknown'} - ${data.request.method} ${data.request._url?.pathname}`,\n attributes: {\n ...urlAttributes,\n [SENTRY_ORIGIN]: 'auto.http.nitro.srvx',\n [SENTRY_OP]: MIDDLEWARE,\n },\n parentSpan: requestParentSpans.get(data.request) || undefined,\n });\n },\n {\n beforeSpanEnd(span, data) {\n applyResponseStatus(span, data);\n },\n },\n );\n}\n\n/**\n * Sets the parameterized route attributes on the span.\n */\nfunction setParameterizedRouteAttributes(span: Span, event: NitroH3Event): void {\n const matchedRoutePath = getParameterizedRoute(event);\n if (!matchedRoutePath) {\n return;\n }\n\n setHttpServerSpanRouteAttribute(matchedRoutePath);\n\n const rootSpan = getRootSpan(span);\n if (!rootSpan) {\n return;\n }\n\n const params = event.context?.params;\n\n if (isObjectLike(params)) {\n Object.entries(params).forEach(([key, value]) => {\n // Based on this convention: https://conventions.sentry.dev/attributes/url/#url-path-parameter-key\n rootSpan.setAttributes({\n [`url.path.parameter.${key}`]: String(value),\n [`params.${key}`]: String(value),\n });\n });\n }\n}\n"],"mappings":";;;;;;;;;;AA8BA,SAAgB,uBAA6B;CAE3C,MAAM,0BAA0B;CAChC,IAAI,wBAAwB,6CAC1B;CAGF,uBAAuB;CACvB,yBAAyB;CACzB,wBAAwB,8CAA8C;AACxE;;;;;;AAOA,SAAS,sBAAsB,QAAqC;CAClE,IAAI,aAAa,MAAM,KAAK,YAAY,UAAU,OAAO,OAAO,WAAW,UACzE,OAAO,OAAO;AAGlB;;AAGA,SAAS,oBAAoB,MAAY,MAAiE;CACxG,MAAM,aAAa,sBAAsB,KAAK,MAAM;CACpD,IAAI,eAAe,KAAA,GACjB,cAAc,MAAM,UAAU;AAElC;;;;;AAMA,SAAS,wBAAiC;CACxC,MAAM,aAAa,cAAc;CACjC,OAAO,CAAC,CAAC,cAAc,WAAW,YAAY,UAAU,CAAC,CAAC,CAAC,WAAW,eAAe;AACvF;;;;;AAMA,SAAS,cAAc,QAAwD;CAC7E,MAAM,MAAM,OAAO,MAAM,uBAAuB,OAAO,GAAG,IAAI,KAAA;CAE9D,QADa,OAAO,UAAU,MAAM,OAAO,IAAI,IAAI,IAAI,KAAA,MACxC,OAAO,QAAQ,QAAQ,KAAA;AACxC;;;;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AQ,OACvB,CAAC;EAGD,OAAO,kBAAkB;GACvB,MAAM,GAAG,KAAK,YAAY,QAAQ,QAAQ,UAAU,KAAK,KAAK,QAAQ,OAAO,GAAG,KAAK,QAAQ,MAAM;GACnG,YAAY;IACV,GAAG;KACF,gBAAgB;KAChB,YAAY;GACf;GACA,YAAY,mBAAmB,IAAI,KAAK,OAAO,KAAK,KAAA;EACtD,CAAC;CACH,GACA,EACE,cAAc,MAAM,MAAM;EACxB,oBAAoB,MAAM,IAAI;CAChC,EACF,CACF;AACF;;;;AAKA,SAAS,gCAAgC,MAAY,OAA2B;CAC9E,MAAM,mBAAmB,sBAAsB,KAAK;CACpD,IAAI,CAAC,kBACH;CAGF,gCAAgC,gBAAgB;CAEhD,MAAM,WAAW,YAAY,IAAI;CACjC,IAAI,CAAC,UACH;CAGF,MAAM,SAAS,MAAM,SAAS;CAE9B,IAAI,aAAa,MAAM,GACrB,OAAO,QAAQ,MAAM,CAAC,CAAC,SAAS,CAAC,KAAK,WAAW;EAE/C,SAAS,cAAc;IACpB,sBAAsB,QAAQ,OAAO,KAAK;IAC1C,UAAU,QAAQ,OAAO,KAAK;EACjC,CAAC;CACH,CAAC;AAEL"}
|
|
1
|
+
{"version":3,"file":"captureTracingEvents.js","names":["diagnosticsChannel.tracingChannel"],"sources":["../../../../src/integrations/nitro/captureTracingEvents.ts"],"sourcesContent":["import { SENTRY_OP, SENTRY_SEGMENT_NAME_SOURCE, SENTRY_ORIGIN, SERVER_PORT } from '@sentry/conventions/attributes';\nimport { HANDLER, HTTP_SERVER, MIDDLEWARE } from '@sentry/conventions/op';\nimport {\n isObjectLike,\n getActiveSpan,\n getClient,\n getHttpSpanDetailsFromUrlObject,\n getRootSpan,\n GLOBAL_OBJ,\n hasSpanStreamingEnabled,\n httpHeadersToSpanAttributes,\n HTTP_SPAN_NAME_FALLBACK,\n parseStringToURLObject,\n setHttpStatus,\n type Span,\n spanToJSON,\n startInactiveSpan,\n} from '@sentry/core';\nimport { bindTracingChannelToSpan, type TracingChannelPayloadWithSpan } from '../../tracing-channel';\nimport * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport { setHttpServerSpanRouteAttribute } from '../../utils/setHttpServerSpanRouteAttribute';\nimport type { H3TracingRequestEvent, NitroH3Event, SrvxRequestEvent } from './nitroTypes';\n\ntype GlobalWithTraceChannels = typeof GLOBAL_OBJ & {\n __SENTRY_NITRO_HTTP_CHANNELS_INSTRUMENTED__?: boolean;\n};\n\n/**\n * Captures tracing events emitted by Nitro tracing channels.\n */\nexport function captureTracingEvents(options: { middleware: boolean }): void {\n // Resolved at call time: bundlers may evaluate this module before `GLOBAL_OBJ` is initialized.\n const globalWithTraceChannels = GLOBAL_OBJ as GlobalWithTraceChannels;\n if (globalWithTraceChannels.__SENTRY_NITRO_HTTP_CHANNELS_INSTRUMENTED__) {\n return;\n }\n\n setupH3TracingChannels(options);\n setupSrvxTracingChannels();\n globalWithTraceChannels.__SENTRY_NITRO_HTTP_CHANNELS_INSTRUMENTED__ = true;\n}\n\n/**\n * Extracts the HTTP status code from a tracing channel result.\n * The result is the return value of the traced handler, which is a Response for srvx\n * and may or may not be a Response for h3.\n */\nfunction getResponseStatusCode(result: unknown): number | undefined {\n if (isObjectLike(result) && 'status' in result && typeof result.status === 'number') {\n return result.status;\n }\n return undefined;\n}\n\n/** Applies the HTTP status from the traced handler's result to the span, when present. */\nfunction applyResponseStatus(span: Span, data: TracingChannelPayloadWithSpan<{ result?: unknown }>): void {\n const statusCode = getResponseStatusCode(data.result);\n if (statusCode !== undefined) {\n setHttpStatus(span, statusCode);\n }\n}\n\n/**\n * Whether the request already has an `http.server` root span, created by the runtime's own HTTP\n * server instrumentation (Node `http`, `Bun.serve`, `Deno.serve`, Cloudflare's request wrapper).\n */\nfunction hasHttpServerRootSpan(): boolean {\n const activeSpan = getActiveSpan();\n return !!activeSpan && spanToJSON(getRootSpan(activeSpan)).attributes[SENTRY_OP] === HTTP_SERVER;\n}\n\n/**\n * The port the srvx server listens on. `options.port` is only the configured one, which is `0` for a\n * random port.\n */\nfunction getServerPort(server: SrvxRequestEvent['server']): number | undefined {\n const url = server.url ? parseStringToURLObject(server.url) : undefined;\n const port = url && 'port' in url ? Number(url.port) : undefined;\n return port || server.options.port || undefined;\n}\n\n/**\n * Extracts the parameterized route pattern from the h3 event context.\n */\nfunction getParameterizedRoute(event: NitroH3Event): string | undefined {\n const matchedRoute = event.context?.matchedRoute;\n if (!matchedRoute) {\n return undefined;\n }\n\n const routePath = matchedRoute.route;\n\n // Skip catch-all routes as they're not useful for transaction grouping\n if (!routePath || routePath === '/**') {\n return undefined;\n }\n\n return routePath;\n}\n\nfunction setupH3TracingChannels(options: { middleware: boolean }): void {\n // Bail if this is not available\n if (!diagnosticsChannel.tracingChannel) {\n return;\n }\n\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<H3TracingRequestEvent>('h3.request'),\n data => {\n if (data.type === 'middleware' && !options.middleware) {\n return undefined;\n }\n\n const method = data.event.req.method?.toUpperCase() || HTTP_SPAN_NAME_FALLBACK;\n\n // The route lives on the request's `http.server` root span, so the route handler only gets a\n // span that times the handler itself instead of yet another nested `http.server` span.\n if (data.type === 'route' && hasHttpServerRootSpan()) {\n const matchedRoute = data.event.context?.matchedRoute?.route;\n const span = startInactiveSpan({\n name: matchedRoute ? `${method} ${matchedRoute}` : method,\n attributes: {\n [SENTRY_ORIGIN]: 'auto.http.nitro.h3',\n [SENTRY_OP]: HANDLER,\n },\n });\n\n setParameterizedRouteAttributes(span, data.event);\n\n return span;\n }\n\n const parsedUrl = parseStringToURLObject(data.event.url.href);\n const routePattern = getParameterizedRoute(data.event);\n\n const [spanName, urlAttributes] = getHttpSpanDetailsFromUrlObject(\n parsedUrl,\n 'server',\n 'auto.http.nitro.h3',\n { method: data.event.req.method },\n routePattern,\n );\n\n const client = getClient();\n // With span streaming, span names have to be low cardinality, so we can't fall back to the URL.\n // Only applies to the http.server span; middleware spans keep their own naming.\n const isUnparameterizedStreamedServerSpan =\n data.type !== 'middleware' &&\n urlAttributes[SENTRY_SEGMENT_NAME_SOURCE] !== 'route' &&\n !!client &&\n hasSpanStreamingEnabled(client);\n\n const span = startInactiveSpan({\n name: isUnparameterizedStreamedServerSpan ? method : spanName,\n attributes: {\n ...urlAttributes,\n [SENTRY_ORIGIN]: 'auto.http.nitro.h3',\n [SENTRY_OP]: data.type === 'middleware' ? MIDDLEWARE : HTTP_SERVER,\n },\n });\n\n setParameterizedRouteAttributes(span, data.event);\n\n return span;\n },\n {\n beforeSpanEnd(span, data) {\n applyResponseStatus(span, data);\n\n // Update the root span with the parameterized route name. The root span is created before h3\n // resolves the route, so it initially has the raw URL.\n // Note: data.type is always 'middleware' here regardless of handler type, so we rely on\n // getParameterizedRoute() to filter out catch-all routes instead.\n const routePattern = getParameterizedRoute(data.event);\n if (routePattern) {\n setHttpServerSpanRouteAttribute(routePattern);\n }\n },\n },\n );\n}\n\nfunction setupSrvxTracingChannels(): void {\n if (!diagnosticsChannel.tracingChannel) {\n return;\n }\n\n // Store the parent span per-request so middleware and fetch share the same parent.\n // WeakMap ensures per-request isolation in concurrent environments and automatic cleanup.\n const requestParentSpans = new WeakMap<SrvxRequestEvent['request'], Span>();\n\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<SrvxRequestEvent>('srvx.request'),\n data => {\n // srvx only opens the request's `http.server` span when the runtime has not already created one.\n if (hasHttpServerRootSpan()) {\n return undefined;\n }\n\n const parsedUrl = data.request._url ? parseStringToURLObject(data.request._url.href) : undefined;\n const client = getClient();\n const [spanName, urlAttributes] = getHttpSpanDetailsFromUrlObject(\n parsedUrl,\n 'server',\n 'auto.http.nitro.srvx',\n { method: data.request.method },\n undefined,\n client,\n );\n\n const headerAttributes = client\n ? httpHeadersToSpanAttributes(\n Object.fromEntries(data.request.headers.entries()),\n client.getDataCollectionOptions(),\n )\n : {};\n\n // With span streaming, span names have to be low cardinality, so we can't fall back to the URL.\n // Only applies to the http.server span; middleware spans keep their own naming.\n // h3 renames this span via `setHttpServerSpanRouteAttribute` once it resolves the route.\n const isUnparameterizedStreamedServerSpan =\n !data.middleware &&\n urlAttributes[SENTRY_SEGMENT_NAME_SOURCE] !== 'route' &&\n !!client &&\n hasSpanStreamingEnabled(client);\n\n return startInactiveSpan({\n name: isUnparameterizedStreamedServerSpan\n ? data.request.method?.toUpperCase() || HTTP_SPAN_NAME_FALLBACK\n : spanName,\n attributes: {\n ...urlAttributes,\n ...headerAttributes,\n [SENTRY_ORIGIN]: 'auto.http.nitro.srvx',\n [SENTRY_OP]: data.middleware ? MIDDLEWARE : HTTP_SERVER,\n [SERVER_PORT]: getServerPort(data.server),\n },\n // Use the same parent span as middleware to make them siblings\n parentSpan: requestParentSpans.get(data.request) || undefined,\n });\n },\n {\n beforeSpanEnd(span, data) {\n applyResponseStatus(span, data);\n\n // Clean up parent span reference after the fetch handler completes (success or error).\n requestParentSpans.delete(data.request);\n },\n },\n );\n\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<SrvxRequestEvent>('srvx.middleware'),\n data => {\n // For the first middleware, capture the current parent span per-request\n if (data.middleware?.index === 0) {\n const activeSpan = getActiveSpan();\n if (activeSpan) {\n requestParentSpans.set(data.request, activeSpan);\n }\n }\n\n const parsedUrl = data.request._url ? parseStringToURLObject(data.request._url.href) : undefined;\n const [, urlAttributes] = getHttpSpanDetailsFromUrlObject(parsedUrl, 'server', 'auto.http.nitro.srvx', {\n method: data.request.method,\n });\n\n // Create span as a child of the original parent, not the previous middleware\n return startInactiveSpan({\n name: `${data.middleware?.handler.name ?? 'unknown'} - ${data.request.method} ${data.request._url?.pathname}`,\n attributes: {\n ...urlAttributes,\n [SENTRY_ORIGIN]: 'auto.http.nitro.srvx',\n [SENTRY_OP]: MIDDLEWARE,\n },\n parentSpan: requestParentSpans.get(data.request) || undefined,\n });\n },\n {\n beforeSpanEnd(span, data) {\n applyResponseStatus(span, data);\n },\n },\n );\n}\n\n/**\n * Sets the parameterized route attributes on the span.\n */\nfunction setParameterizedRouteAttributes(span: Span, event: NitroH3Event): void {\n const matchedRoutePath = getParameterizedRoute(event);\n if (!matchedRoutePath) {\n return;\n }\n\n setHttpServerSpanRouteAttribute(matchedRoutePath);\n\n const rootSpan = getRootSpan(span);\n if (!rootSpan) {\n return;\n }\n\n const params = event.context?.params;\n\n if (isObjectLike(params)) {\n Object.entries(params).forEach(([key, value]) => {\n // Based on this convention: https://conventions.sentry.dev/attributes/url/#url-path-parameter-key\n rootSpan.setAttributes({\n [`url.path.parameter.${key}`]: String(value),\n [`params.${key}`]: String(value),\n });\n });\n }\n}\n"],"mappings":";;;;;;;;;;AA8BA,SAAgB,qBAAqB,SAAwC;CAE3E,MAAM,0BAA0B;CAChC,IAAI,wBAAwB,6CAC1B;CAGF,uBAAuB,OAAO;CAC9B,yBAAyB;CACzB,wBAAwB,8CAA8C;AACxE;;;;;;AAOA,SAAS,sBAAsB,QAAqC;CAClE,IAAI,aAAa,MAAM,KAAK,YAAY,UAAU,OAAO,OAAO,WAAW,UACzE,OAAO,OAAO;AAGlB;;AAGA,SAAS,oBAAoB,MAAY,MAAiE;CACxG,MAAM,aAAa,sBAAsB,KAAK,MAAM;CACpD,IAAI,eAAe,KAAA,GACjB,cAAc,MAAM,UAAU;AAElC;;;;;AAMA,SAAS,wBAAiC;CACxC,MAAM,aAAa,cAAc;CACjC,OAAO,CAAC,CAAC,cAAc,WAAW,YAAY,UAAU,CAAC,CAAC,CAAC,WAAW,eAAe;AACvF;;;;;AAMA,SAAS,cAAc,QAAwD;CAC7E,MAAM,MAAM,OAAO,MAAM,uBAAuB,OAAO,GAAG,IAAI,KAAA;CAE9D,QADa,OAAO,UAAU,MAAM,OAAO,IAAI,IAAI,IAAI,KAAA,MACxC,OAAO,QAAQ,QAAQ,KAAA;AACxC;;;;AAKA,SAAS,sBAAsB,OAAyC;CACtE,MAAM,eAAe,MAAM,SAAS;CACpC,IAAI,CAAC,cACH;CAGF,MAAM,YAAY,aAAa;CAG/B,IAAI,CAAC,aAA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AAQ,QAAQ,UAAU,KAAK,KAAK,QAAQ,OAAO,GAAG,KAAK,QAAQ,MAAM;GACnG,YAAY;IACV,GAAG;KACF,gBAAgB;KAChB,YAAY;GACf;GACA,YAAY,mBAAmB,IAAI,KAAK,OAAO,KAAK,KAAA;EACtD,CAAC;CACH,GACA,EACE,cAAc,MAAM,MAAM;EACxB,oBAAoB,MAAM,IAAI;CAChC,EACF,CACF;AACF;;;;AAKA,SAAS,gCAAgC,MAAY,OAA2B;CAC9E,MAAM,mBAAmB,sBAAsB,KAAK;CACpD,IAAI,CAAC,kBACH;CAGF,gCAAgC,gBAAgB;CAEhD,MAAM,WAAW,YAAY,IAAI;CACjC,IAAI,CAAC,UACH;CAGF,MAAM,SAAS,MAAM,SAAS;CAE9B,IAAI,aAAa,MAAM,GACrB,OAAO,QAAQ,MAAM,CAAC,CAAC,SAAS,CAAC,KAAK,WAAW;EAE/C,SAAS,cAAc;IACpB,sBAAsB,QAAQ,OAAO,KAAK;IAC1C,UAAU,QAAQ,OAAO,KAAK;EACjC,CAAC;CACH,CAAC;AAEL"}
|
|
@@ -5,11 +5,11 @@ import { defineIntegration } from "@sentry/core";
|
|
|
5
5
|
// src/integrations/nitro/index.ts
|
|
6
6
|
const INTEGRATION_NAME = "Nitro";
|
|
7
7
|
const _nitroIntegration = ((options = {}) => {
|
|
8
|
-
const { serverTiming = true, storage = true } = options;
|
|
8
|
+
const { middleware = true, serverTiming = true, storage = true } = options;
|
|
9
9
|
return {
|
|
10
10
|
name: INTEGRATION_NAME,
|
|
11
11
|
setupOnce() {
|
|
12
|
-
captureTracingEvents();
|
|
12
|
+
captureTracingEvents({ middleware });
|
|
13
13
|
if (storage) captureStorageEvents();
|
|
14
14
|
if (serverTiming) captureServerTimingHeaders();
|
|
15
15
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/integrations/nitro/index.ts"],"sourcesContent":["import type { IntegrationFn } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport { captureStorageEvents } from './captureStorageEvents';\nimport { captureTracingEvents } from './captureTracingEvents';\nimport { captureServerTimingHeaders } from './setServerTimingHeaders';\n\nconst INTEGRATION_NAME = 'Nitro' as const;\n\nexport interface NitroIntegrationOptions {\n /**\n * Set `Server-Timing` response headers carrying the current `sentry-trace`/`baggage`, so the browser\n * SDK can connect a pageload trace to the backend trace.\n *\n * @default true\n */\n serverTiming?: boolean;\n\n /**\n * Create cache spans for unstorage operations.\n *\n * @default true\n */\n storage?: boolean;\n}\n\nconst _nitroIntegration = ((options: NitroIntegrationOptions = {}) => {\n const { serverTiming = true, storage = true } = options;\n\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n captureTracingEvents();\n\n if (storage) {\n captureStorageEvents();\n }\n\n if (serverTiming) {\n captureServerTimingHeaders();\n }\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Instruments a Nitro server via its `node:diagnostics_channel` tracing channels: HTTP server and\n * middleware spans (h3/srvx), cache spans (unstorage) and `Server-Timing` trace-propagation headers.\n * It subscribes to those channels, so it is inert unless a Nitro app (or a framework that enables the\n * same tracing channels) is running.\n *\n * Registered regardless of whether tracing is enabled, because trace propagation must work in\n * tracing-without-performance mode too; without tracing, the spans it starts are non-recording.\n * Error capture is handled by the `@sentry/nitro` runtime plugin's Nitro `error` hook.\n */\nexport const nitroIntegration = defineIntegration(_nitroIntegration);\n"],"mappings":";;;;;AAMA,MAAM,mBAAmB;
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/integrations/nitro/index.ts"],"sourcesContent":["import type { IntegrationFn } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport { captureStorageEvents } from './captureStorageEvents';\nimport { captureTracingEvents } from './captureTracingEvents';\nimport { captureServerTimingHeaders } from './setServerTimingHeaders';\n\nconst INTEGRATION_NAME = 'Nitro' as const;\n\nexport interface NitroIntegrationOptions {\n /**\n * Create `middleware` spans for h3 middleware.\n *\n * @default true\n */\n middleware?: boolean;\n\n /**\n * Set `Server-Timing` response headers carrying the current `sentry-trace`/`baggage`, so the browser\n * SDK can connect a pageload trace to the backend trace.\n *\n * @default true\n */\n serverTiming?: boolean;\n\n /**\n * Create cache spans for unstorage operations.\n *\n * @default true\n */\n storage?: boolean;\n}\n\nconst _nitroIntegration = ((options: NitroIntegrationOptions = {}) => {\n const { middleware = true, serverTiming = true, storage = true } = options;\n\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n captureTracingEvents({ middleware });\n\n if (storage) {\n captureStorageEvents();\n }\n\n if (serverTiming) {\n captureServerTimingHeaders();\n }\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Instruments a Nitro server via its `node:diagnostics_channel` tracing channels: HTTP server and\n * middleware spans (h3/srvx), cache spans (unstorage) and `Server-Timing` trace-propagation headers.\n * It subscribes to those channels, so it is inert unless a Nitro app (or a framework that enables the\n * same tracing channels) is running.\n *\n * Registered regardless of whether tracing is enabled, because trace propagation must work in\n * tracing-without-performance mode too; without tracing, the spans it starts are non-recording.\n * Error capture is handled by the `@sentry/nitro` runtime plugin's Nitro `error` hook.\n */\nexport const nitroIntegration = defineIntegration(_nitroIntegration);\n"],"mappings":";;;;;AAMA,MAAM,mBAAmB;AA0BzB,MAAM,sBAAsB,UAAmC,CAAC,MAAM;CACpE,MAAM,EAAE,aAAa,MAAM,eAAe,MAAM,UAAU,SAAS;CAEnE,OAAO;EACL,MAAM;EACN,YAAY;GACV,qBAAqB,EAAE,WAAW,CAAC;GAEnC,IAAI,SACF,qBAAqB;GAGvB,IAAI,cACF,2BAA2B;EAE/B;CACF;AACF;;;;;;;;;;;AAYA,MAAa,mBAAmB,kBAAkB,iBAAiB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai-compatible.js","names":["diagnosticsChannel.tracingChannel"],"sources":["../../../src/integrations/openai-compatible.ts"],"sourcesContent":["import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { Integration, IntegrationFn, Span, SpanAttributeValue } from '@sentry/core';\nimport {\n _INTERNAL_shouldSkipAiProviderWrapping,\n getClient,\n hasSpanStreamingEnabled,\n startInactiveSpan,\n} from '@sentry/core';\nimport { GEN_AI_PROVIDER_NAME, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { getGenAiSpanOp, getRequestSignal, markCancelledIfAborted, resolveGenAiCallRecording } from '../ai/core/utils';\nimport { wrapApiPromiseResponse } from '../ai/core/apiPromise';\nimport { type GenAiSpanResult, runGenAiSpanEnd, runGenAiSpanStart } from '../ai/core/span-hooks';\nimport { addRequestAttributes, extractRequestAttributes } from '../ai/openai';\nimport { instrumentStream } from '../ai/openai/streaming';\nimport type { OpenAiCallInfo, OpenAiOptions } from '../ai/openai/types';\nimport { addResponseAttributes } from '../ai/openai/utils';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\n\n// The recording decision is made once, when the span starts, in the caller's async context.\ntype OpenAiChannelContext = OrchestrionChannelContext & {\n _sentryRecordOutputs?: boolean;\n _sentryOnSpanEnd?: (result: GenAiSpanResult<unknown>) => void;\n};\n\n/**\n * Describes an OpenAI-compatible provider whose SDK mirrors the openai wire format (Groq, Together, ...),\n * so the span building, streaming and response parsing can all be reused from `ai/openai`.\n */\nexport interface OpenAiCompatibleProvider {\n /** Integration name; also the key used to skip double-wrapping when another provider drives the SDK. */\n integrationName: string;\n /** Value reported on `gen_ai.provider.name`. */\n providerName: string;\n /** Span origin, `auto.ai.<provider>`. */\n origin: string;\n /** The instrumented `module.name`s (from the orchestrion config's `getModuleNames`). */\n moduleNames: string[];\n /** The fully-qualified orchestrion channels this provider publishes to. */\n channels: { chat: string; embeddings: string };\n}\n\n/**\n * Builds a diagnostics-channel integration for an OpenAI-compatible provider SDK. It subscribes to the\n * `orchestrion:<module>:{chat,embeddings}` channels injected into the SDK's `create` methods, so it\n * requires the Sentry runtime hook or bundler plugin. Everything below the channel — request/response\n * attributes and streaming — is shared with the openai integration; only the provider name and origin\n * differ.\n */\nexport function createOpenAiCompatibleIntegration<T extends OpenAiCompatibleProvider>(\n provider: T,\n): (options?: OpenAiOptions) => Integration & { name: T['integrationName'] } {\n const instrumentedChannels = [\n { channel: provider.channels.chat, operation: 'chat' },\n { channel: provider.channels.embeddings, operation: 'embeddings' },\n ] as const;\n\n function instrument(options: OpenAiOptions): void {\n for (const { channel, operation } of instrumentedChannels) {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<OpenAiChannelContext>(channel),\n data => createGenAiSpan(data, operation, provider, options),\n {\n beforeSpanEnd: (span, data) => {\n if ('error' in data) {\n markCancelledIfAborted(span, getRequestSignal(data.arguments?.[1]));\n }\n addResponseAttributes(span, data.result, !!data._sentryRecordOutputs);\n data._sentryOnSpanEnd?.('error' in data ? { error: data.error } : { response: data.result });\n },\n deferSpanEnd: ({ span, data, end }) =>\n wrapApiPromiseResponse(\n data.result,\n response => {\n data.result = response;\n if (!wrapStreamResult(span, data)) {\n end();\n }\n },\n end,\n ) || wrapStreamResult(span, data),\n },\n );\n }\n }\n\n return ((options: OpenAiOptions = {}) => {\n return {\n name: provider.integrationName,\n setup(client) {\n invokeOrchestrionInstrumentation(client, provider.moduleNames, instrument, [options]);\n },\n };\n }) satisfies IntegrationFn;\n}\n\n/**\n * Build the span for an instrumented `create` call.\n * Returning `undefined` opts the payload out so no span is opened.\n */\nfunction createGenAiSpan(\n data: OpenAiChannelContext,\n operation: string,\n provider: OpenAiCompatibleProvider,\n options: OpenAiOptions,\n): Span | undefined {\n // When another provider (e.g. LangChain) is driving the SDK, it records the spans itself and marks this\n // provider as skipped; skip here to avoid double spans.\n if (_INTERNAL_shouldSkipAiProviderWrapping(provider.integrationName)) {\n return undefined;\n }\n\n const args = data.arguments ?? [];\n const params = args[0] as Record<string, unknown> | undefined;\n\n const call: OpenAiCallInfo = { operation, request: params };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n data._sentryRecordOutputs = recordOutputs;\n\n // `extractRequestAttributes` defaults the provider to openai; override it for the concrete provider.\n const attributes = extractRequestAttributes(args, operation, recordInputs);\n attributes[GEN_AI_PROVIDER_NAME] = provider.providerName;\n attributes[SENTRY_ORIGIN] = provider.origin;\n const model = (params?.model as string) || 'unknown';\n const client = getClient();\n\n const span = startInactiveSpan({\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name: model !== 'unknown' || !(client && hasSpanStreamingEnabled(client)) ? `${operation} ${model}` : operation,\n op: getGenAiSpanOp(operation),\n attributes: attributes as Record<string, SpanAttributeValue>,\n });\n\n if (recordInputs && params) {\n addRequestAttributes(span, params, operation);\n }\n\n runGenAiSpanStart(options, span, call);\n data._sentryOnSpanEnd = result => runGenAiSpanEnd(options, span, call, result);\n\n return span;\n}\n\ntype AsyncIterableStream = { [Symbol.asyncIterator]: () => AsyncIterator<unknown> };\n\nfunction isAsyncIterable(value: unknown): value is AsyncIterableStream {\n return !!value && typeof (value as AsyncIterableStream)[Symbol.asyncIterator] === 'function';\n}\n\n/**\n * For a streaming `create({ stream: true })` the result is a `Stream` the caller consumes later. We can't\n * swap what `create` returns, but the `Stream` in `data.result` is the same instance the caller holds and\n * we observe it before the caller iterates — so we patch its async iterator in place to run through\n * `instrumentStream`, which accumulates the streamed attributes and ends the span when iteration finishes.\n * Only a streaming call resolves to an async-iterable, so that check alone distinguishes it. Returns `true`\n * to hand span-ending ownership to `instrumentStream`; `false` for non-streaming/errored results, which end\n * via the normal `beforeSpanEnd` path.\n */\nfunction wrapStreamResult(span: Span, data: OpenAiChannelContext): boolean {\n const result = data.result;\n if (!isAsyncIterable(result)) {\n return false;\n }\n\n const iterate = result[Symbol.asyncIterator].bind(result);\n const instrumented = instrumentStream(\n { [Symbol.asyncIterator]: iterate },\n span,\n !!data._sentryRecordOutputs,\n data._sentryOnSpanEnd,\n );\n result[Symbol.asyncIterator] = () => instrumented;\n\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAkDA,SAAgB,kCACd,UAC2E;CAC3E,MAAM,uBAAuB,CAC3B;EAAE,SAAS,SAAS,SAAS;EAAM,WAAW;CAAO,GACrD;EAAE,SAAS,SAAS,SAAS;EAAY,WAAW;CAAa,CACnE;CAEA,SAAS,WAAW,SAA8B;EAChD,KAAK,MAAM,EAAE,SAAS,eAAe,sBACnC,yBACEA,eAAwD,OAAO,IAC/D,SAAQ,gBAAgB,MAAM,WAAW,UAAU,OAAO,GAC1D;GACE,gBAAgB,MAAM,SAAS;IAC7B,IAAI,WAAW,MACb,uBAAuB,MAAM,iBAAiB,KAAK,YAAY,EAAE,CAAC;IAEpE,sBAAsB,MAAM,KAAK,QAAQ,CAAC,CAAC,KAAK,oBAAoB;IACpE,KAAK,mBAAmB,WAAW,OAAO,EAAE,OAAO,KAAK,MAAM,IAAI,EAAE,UAAU,KAAK,OAAO,CAAC;GAC7F;GACA,eAAe,EAAE,MAAM,MAAM,UAC3B,uBACE,KAAK,SACL,aAAY;IACV,KAAK,SAAS;IACd,IAAI,CAAC,iBAAiB,MAAM,IAAI,GAC9B,IAAI;GAER,GACA,GACF,KAAK,iBAAiB,MAAM,IAAI;EACpC,CACF;CAEJ;CAEA,SAAS,UAAyB,CAAC,MAAM;
|
|
1
|
+
{"version":3,"file":"openai-compatible.js","names":["diagnosticsChannel.tracingChannel"],"sources":["../../../src/integrations/openai-compatible.ts"],"sourcesContent":["import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { Integration, IntegrationFn, Span, SpanAttributeValue } from '@sentry/core';\nimport {\n _INTERNAL_shouldSkipAiProviderWrapping,\n getClient,\n hasSpanStreamingEnabled,\n startInactiveSpan,\n} from '@sentry/core';\nimport { GEN_AI_PROVIDER_NAME, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { getGenAiSpanOp, getRequestSignal, markCancelledIfAborted, resolveGenAiCallRecording } from '../ai/core/utils';\nimport { wrapApiPromiseResponse } from '../ai/core/apiPromise';\nimport { type GenAiSpanResult, runGenAiSpanEnd, runGenAiSpanStart } from '../ai/core/span-hooks';\nimport { addRequestAttributes, extractRequestAttributes } from '../ai/openai';\nimport { instrumentStream } from '../ai/openai/streaming';\nimport type { OpenAiCallInfo, OpenAiOptions } from '../ai/openai/types';\nimport { addResponseAttributes } from '../ai/openai/utils';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\n\n// The recording decision is made once, when the span starts, in the caller's async context.\ntype OpenAiChannelContext = OrchestrionChannelContext & {\n _sentryRecordOutputs?: boolean;\n _sentryOnSpanEnd?: (result: GenAiSpanResult<unknown>) => void;\n};\n\n/**\n * Describes an OpenAI-compatible provider whose SDK mirrors the openai wire format (Groq, Together, ...),\n * so the span building, streaming and response parsing can all be reused from `ai/openai`.\n */\nexport interface OpenAiCompatibleProvider {\n /** Integration name; also the key used to skip double-wrapping when another provider drives the SDK. */\n integrationName: string;\n /** Value reported on `gen_ai.provider.name`. */\n providerName: string;\n /** Span origin, `auto.ai.<provider>`. */\n origin: string;\n /** The instrumented `module.name`s (from the orchestrion config's `getModuleNames`). */\n moduleNames: string[];\n /** The fully-qualified orchestrion channels this provider publishes to. */\n channels: { chat: string; embeddings: string };\n}\n\n/**\n * Builds a diagnostics-channel integration for an OpenAI-compatible provider SDK. It subscribes to the\n * `orchestrion:<module>:{chat,embeddings}` channels injected into the SDK's `create` methods, so it\n * requires the Sentry runtime hook or bundler plugin. Everything below the channel — request/response\n * attributes and streaming — is shared with the openai integration; only the provider name and origin\n * differ.\n */\nexport function createOpenAiCompatibleIntegration<T extends OpenAiCompatibleProvider>(\n provider: T,\n): (options?: OpenAiOptions) => Integration & { name: T['integrationName'] } {\n const instrumentedChannels = [\n { channel: provider.channels.chat, operation: 'chat' },\n { channel: provider.channels.embeddings, operation: 'embeddings' },\n ] as const;\n\n function instrument(options: OpenAiOptions): void {\n for (const { channel, operation } of instrumentedChannels) {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<OpenAiChannelContext>(channel),\n data => createGenAiSpan(data, operation, provider, options),\n {\n beforeSpanEnd: (span, data) => {\n if ('error' in data) {\n markCancelledIfAborted(span, getRequestSignal(data.arguments?.[1]));\n }\n addResponseAttributes(span, data.result, !!data._sentryRecordOutputs);\n data._sentryOnSpanEnd?.('error' in data ? { error: data.error } : { response: data.result });\n },\n deferSpanEnd: ({ span, data, end }) =>\n wrapApiPromiseResponse(\n data.result,\n response => {\n data.result = response;\n if (!wrapStreamResult(span, data)) {\n end();\n }\n },\n end,\n ) || wrapStreamResult(span, data),\n },\n );\n }\n }\n\n return ((options: OpenAiOptions = {}) => {\n // oxlint-disable-next-line sdk/require-define-integration -- callers pass the returned function to `defineIntegration`\n return {\n name: provider.integrationName,\n setup(client) {\n invokeOrchestrionInstrumentation(client, provider.moduleNames, instrument, [options]);\n },\n };\n }) satisfies IntegrationFn;\n}\n\n/**\n * Build the span for an instrumented `create` call.\n * Returning `undefined` opts the payload out so no span is opened.\n */\nfunction createGenAiSpan(\n data: OpenAiChannelContext,\n operation: string,\n provider: OpenAiCompatibleProvider,\n options: OpenAiOptions,\n): Span | undefined {\n // When another provider (e.g. LangChain) is driving the SDK, it records the spans itself and marks this\n // provider as skipped; skip here to avoid double spans.\n if (_INTERNAL_shouldSkipAiProviderWrapping(provider.integrationName)) {\n return undefined;\n }\n\n const args = data.arguments ?? [];\n const params = args[0] as Record<string, unknown> | undefined;\n\n const call: OpenAiCallInfo = { operation, request: params };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n data._sentryRecordOutputs = recordOutputs;\n\n // `extractRequestAttributes` defaults the provider to openai; override it for the concrete provider.\n const attributes = extractRequestAttributes(args, operation, recordInputs);\n attributes[GEN_AI_PROVIDER_NAME] = provider.providerName;\n attributes[SENTRY_ORIGIN] = provider.origin;\n const model = (params?.model as string) || 'unknown';\n const client = getClient();\n\n const span = startInactiveSpan({\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name: model !== 'unknown' || !(client && hasSpanStreamingEnabled(client)) ? `${operation} ${model}` : operation,\n op: getGenAiSpanOp(operation),\n attributes: attributes as Record<string, SpanAttributeValue>,\n });\n\n if (recordInputs && params) {\n addRequestAttributes(span, params, operation);\n }\n\n runGenAiSpanStart(options, span, call);\n data._sentryOnSpanEnd = result => runGenAiSpanEnd(options, span, call, result);\n\n return span;\n}\n\ntype AsyncIterableStream = { [Symbol.asyncIterator]: () => AsyncIterator<unknown> };\n\nfunction isAsyncIterable(value: unknown): value is AsyncIterableStream {\n return !!value && typeof (value as AsyncIterableStream)[Symbol.asyncIterator] === 'function';\n}\n\n/**\n * For a streaming `create({ stream: true })` the result is a `Stream` the caller consumes later. We can't\n * swap what `create` returns, but the `Stream` in `data.result` is the same instance the caller holds and\n * we observe it before the caller iterates — so we patch its async iterator in place to run through\n * `instrumentStream`, which accumulates the streamed attributes and ends the span when iteration finishes.\n * Only a streaming call resolves to an async-iterable, so that check alone distinguishes it. Returns `true`\n * to hand span-ending ownership to `instrumentStream`; `false` for non-streaming/errored results, which end\n * via the normal `beforeSpanEnd` path.\n */\nfunction wrapStreamResult(span: Span, data: OpenAiChannelContext): boolean {\n const result = data.result;\n if (!isAsyncIterable(result)) {\n return false;\n }\n\n const iterate = result[Symbol.asyncIterator].bind(result);\n const instrumented = instrumentStream(\n { [Symbol.asyncIterator]: iterate },\n span,\n !!data._sentryRecordOutputs,\n data._sentryOnSpanEnd,\n );\n result[Symbol.asyncIterator] = () => instrumented;\n\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAkDA,SAAgB,kCACd,UAC2E;CAC3E,MAAM,uBAAuB,CAC3B;EAAE,SAAS,SAAS,SAAS;EAAM,WAAW;CAAO,GACrD;EAAE,SAAS,SAAS,SAAS;EAAY,WAAW;CAAa,CACnE;CAEA,SAAS,WAAW,SAA8B;EAChD,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AAG,UAAU;EACtG,IAAI,eAAe,SAAS;EAChB;CACd,CAAC;CAED,IAAI,gBAAgB,QAClB,qBAAqB,MAAM,QAAQ,SAAS;CAG9C,kBAAkB,SAAS,MAAM,IAAI;CACrC,KAAK,oBAAmB,WAAU,gBAAgB,SAAS,MAAM,MAAM,MAAM;CAE7E,OAAO;AACT;AAIA,SAAS,gBAAgB,OAA8C;CACrE,OAAO,CAAC,CAAC,SAAS,OAAQ,MAA8B,OAAO,mBAAmB;AACpF;;;;;;;;;;AAWA,SAAS,iBAAiB,MAAY,MAAqC;CACzE,MAAM,SAAS,KAAK;CACpB,IAAI,CAAC,gBAAgB,MAAM,GACzB,OAAO;CAGT,MAAM,UAAU,OAAO,OAAO,cAAc,CAAC,KAAK,MAAM;CACxD,MAAM,eAAe,iBACnB,GAAG,OAAO,gBAAgB,QAAQ,GAClC,MACA,CAAC,CAAC,KAAK,sBACP,KAAK,gBACP;CACA,OAAO,OAAO,uBAAuB;CAErC,OAAO;AACT"}
|
|
@@ -2,7 +2,7 @@ import { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from "../../ai/core/gen-ai-attributes.j
|
|
|
2
2
|
import { runGenAiSpanEnd, runGenAiSpanStart } from "../../ai/core/span-hooks.js";
|
|
3
3
|
import { isEveGenAiRecordingDefault } from "./gen-ai-recording-mode.js";
|
|
4
4
|
import { getEvaluationOutputMessages, isReadableStream, resolveRecordingOption } from "../../ai/core/utils.js";
|
|
5
|
-
import {
|
|
5
|
+
import { getProviderMetadataAttributes } from "../../ai/vercel-ai/index.js";
|
|
6
6
|
import { WORKERS_AI_INTEGRATION_NAME } from "../../ai/workers-ai/constants.js";
|
|
7
7
|
import { bindTracingChannelToSpan } from "../../tracing-channel.js";
|
|
8
8
|
import { toExtractAnswers, toExtractFields, toExtractState } from "./extract.js";
|
|
@@ -89,19 +89,14 @@ function getActiveSpanConversationId() {
|
|
|
89
89
|
return active ? asString(spanToJSON(active).attributes[GEN_AI_CONVERSATION_ID]) : void 0;
|
|
90
90
|
}
|
|
91
91
|
/**
|
|
92
|
-
* `providerMetadata`
|
|
93
|
-
*
|
|
94
|
-
* Reasoning goes only when it accompanies a recomputed output (Google), because dropping that
|
|
95
|
-
* output leaves the span's own count reasoning-exclusive and the documented subset relationship
|
|
96
|
-
* would not hold. A provider that reports reasoning against an already-inclusive output (OpenAI)
|
|
97
|
-
* keeps it.
|
|
92
|
+
* The `providerMetadata` attributes other than token counts. A partial-cost operation's cost covers
|
|
93
|
+
* only its last provider call, so it stays on the `generate_content` spans.
|
|
98
94
|
*/
|
|
99
|
-
function
|
|
100
|
-
|
|
101
|
-
const
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
if (PARTIAL_COST_OPERATION_TYPES.has(type)) delete providerAttributes[GEN_AI_COST_TOTAL_TOKENS];
|
|
95
|
+
function getProviderOnlyAttributes(providerMetadata, type) {
|
|
96
|
+
const attributes = getProviderMetadataAttributes(providerMetadata);
|
|
97
|
+
for (const key of Object.values(TOKEN_ATTRIBUTES)) delete attributes[key];
|
|
98
|
+
if (PARTIAL_COST_OPERATION_TYPES.has(type)) delete attributes[GEN_AI_COST_TOTAL_TOKENS];
|
|
99
|
+
return attributes;
|
|
105
100
|
}
|
|
106
101
|
/** Record tool name → description from an event's `tools`, so tool spans can backfill the description. */
|
|
107
102
|
function recordToolDescriptions(callId, tools) {
|
|
@@ -216,17 +211,8 @@ function streamedResultToChannelResult(final) {
|
|
|
216
211
|
* because the operation's completion promise settles only after every model-call stream has drained.
|
|
217
212
|
*/
|
|
218
213
|
function enrichInvokeAgentFromStream(span, final, recordOutputs) {
|
|
219
|
-
const usage =
|
|
220
|
-
|
|
221
|
-
const input = tokenCount(usage.inputTokens) ?? tokenCount(usage.promptTokens) ?? tokenCount(usage.tokens);
|
|
222
|
-
const output = tokenCount(usage.outputTokens) ?? tokenCount(usage.completionTokens);
|
|
223
|
-
addTokensToSpan(span, GEN_AI_USAGE_INPUT_TOKENS, input);
|
|
224
|
-
addTokensToSpan(span, GEN_AI_USAGE_OUTPUT_TOKENS, output);
|
|
225
|
-
addTokensToSpan(span, GEN_AI_USAGE_TOTAL_TOKENS, tokenCount(usage.totalTokens) ?? sum(input, output));
|
|
226
|
-
const { cacheRead, cacheWrite } = cacheTokens(usage);
|
|
227
|
-
addTokensToSpan(span, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cacheRead);
|
|
228
|
-
addTokensToSpan(span, GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cacheWrite);
|
|
229
|
-
}
|
|
214
|
+
const usage = modelCallUsage(final.usage, final.providerMetadata);
|
|
215
|
+
for (const key of TOKEN_KEYS) addTokensToSpan(span, TOKEN_ATTRIBUTES[key], usage[key]);
|
|
230
216
|
if (recordOutputs) {
|
|
231
217
|
const outputMessages = buildOutputMessages(partsFromTextAndToolCalls(final.text, final.toolCalls), getFinishReason({ finishReason: final.finishReason }));
|
|
232
218
|
if (outputMessages) span.setAttribute(GEN_AI_OUTPUT_MESSAGES, outputMessages);
|
|
@@ -419,15 +405,11 @@ function enrichSpanOnEnd(span, data) {
|
|
|
419
405
|
else if (recordOutputs) span.setAttribute(GEN_AI_TOOL_CALL_RESULT, stringify(result.output ?? result));
|
|
420
406
|
return;
|
|
421
407
|
}
|
|
422
|
-
const
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
const
|
|
426
|
-
|
|
427
|
-
if (inputTokens !== void 0) span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, inputTokens);
|
|
428
|
-
if (outputTokens !== void 0) span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, outputTokens);
|
|
429
|
-
if (totalTokens !== void 0) span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, totalTokens);
|
|
430
|
-
setCacheTokens(span, usage);
|
|
408
|
+
const providerMetadata = result.providerMetadata;
|
|
409
|
+
const usage = ROOT_OPERATION_TYPES.has(type) ? operationUsage(result, providerMetadata) : modelCallUsage(result.usage, providerMetadata);
|
|
410
|
+
for (const key of TOKEN_KEYS) {
|
|
411
|
+
const value = usage[key];
|
|
412
|
+
if (value !== void 0) span.setAttribute(TOKEN_ATTRIBUTES[key], value);
|
|
431
413
|
}
|
|
432
414
|
const finishReason = getFinishReason(result);
|
|
433
415
|
if (finishReason && type === "languageModelCall") span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, stringify([finishReason]));
|
|
@@ -436,10 +418,7 @@ function enrichSpanOnEnd(span, data) {
|
|
|
436
418
|
if (responseId) span.setAttribute(GEN_AI_RESPONSE_ID, responseId);
|
|
437
419
|
const responseModel = asString(response?.modelId) ?? asString(data.event.modelId);
|
|
438
420
|
if (responseModel) span.setAttribute(GEN_AI_RESPONSE_MODEL, responseModel);
|
|
439
|
-
|
|
440
|
-
const providerAttributes = getProviderMetadataAttributes(providerMetadata);
|
|
441
|
-
dropLastStepOnlyUsage(providerAttributes, type);
|
|
442
|
-
span.setAttributes(providerAttributes);
|
|
421
|
+
span.setAttributes(getProviderOnlyAttributes(providerMetadata, type));
|
|
443
422
|
if (recordOutputs) {
|
|
444
423
|
const outputMessages = getOutputMessages(type, result, finishReason, data.event);
|
|
445
424
|
if (outputMessages) span.setAttribute(GEN_AI_OUTPUT_MESSAGES, outputMessages);
|
|
@@ -487,14 +466,63 @@ function tokenCount(value) {
|
|
|
487
466
|
return asNumber(value) ?? (isObjectLike(value) ? asNumber(value.total) : void 0);
|
|
488
467
|
}
|
|
489
468
|
/**
|
|
469
|
+
* Reasoning from the SDK's usage: v6+ for every provider, v5 only for OpenAI, whose output includes it.
|
|
470
|
+
* Other v5 providers don't say whether their output does, and Google's comes from `providerMetadata`.
|
|
471
|
+
*/
|
|
472
|
+
function reasoningTokens(usage, providerMetadata) {
|
|
473
|
+
const outputTokens = isObjectLike(usage.outputTokens) ? usage.outputTokens : void 0;
|
|
474
|
+
const outputTokenDetails = isObjectLike(usage.outputTokenDetails) ? usage.outputTokenDetails : void 0;
|
|
475
|
+
const reasoning = asNumber(outputTokens?.reasoning) ?? asNumber(outputTokenDetails?.reasoningTokens);
|
|
476
|
+
if (reasoning !== void 0) return reasoning;
|
|
477
|
+
const metadata = isObjectLike(providerMetadata) ? providerMetadata : void 0;
|
|
478
|
+
return metadata?.openai || metadata?.azure ? asNumber(usage.reasoningTokens) : void 0;
|
|
479
|
+
}
|
|
480
|
+
const TOKEN_ATTRIBUTES = {
|
|
481
|
+
input: GEN_AI_USAGE_INPUT_TOKENS,
|
|
482
|
+
output: GEN_AI_USAGE_OUTPUT_TOKENS,
|
|
483
|
+
total: GEN_AI_USAGE_TOTAL_TOKENS,
|
|
484
|
+
cacheRead: GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,
|
|
485
|
+
cacheWrite: GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,
|
|
486
|
+
reasoning: GEN_AI_USAGE_REASONING_OUTPUT_TOKENS
|
|
487
|
+
};
|
|
488
|
+
const TOKEN_KEYS = Object.keys(TOKEN_ATTRIBUTES);
|
|
489
|
+
/**
|
|
490
|
+
* One model call's final token counts: its usage (flat or `{ total }`, v4 `promptTokens`/`completionTokens`)
|
|
491
|
+
* corrected by its own `providerMetadata`.
|
|
492
|
+
*/
|
|
493
|
+
function modelCallUsage(usage, providerMetadata) {
|
|
494
|
+
const derived = getProviderMetadataAttributes(providerMetadata);
|
|
495
|
+
const counts = isObjectLike(usage) ? usage : {};
|
|
496
|
+
const input = tokenCount(counts.inputTokens) ?? tokenCount(counts.promptTokens) ?? tokenCount(counts.tokens);
|
|
497
|
+
const output = asNumber(derived[GEN_AI_USAGE_OUTPUT_TOKENS]) ?? tokenCount(counts.outputTokens) ?? tokenCount(counts.completionTokens);
|
|
498
|
+
const { cacheRead, cacheWrite } = cacheTokens(counts);
|
|
499
|
+
return {
|
|
500
|
+
input,
|
|
501
|
+
output,
|
|
502
|
+
total: asNumber(derived[GEN_AI_USAGE_TOTAL_TOKENS]) ?? tokenCount(counts.totalTokens) ?? sum(input, output),
|
|
503
|
+
cacheRead: asNumber(derived[GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]) ?? cacheRead,
|
|
504
|
+
cacheWrite: asNumber(derived[GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]) ?? cacheWrite,
|
|
505
|
+
reasoning: reasoningTokens(counts, providerMetadata) ?? asNumber(derived[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS])
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
/**
|
|
509
|
+
* An operation's token counts, summed over its steps, which can use different providers. Every text
|
|
510
|
+
* operation from v4 on has `steps`; the others are a single model call.
|
|
511
|
+
*/
|
|
512
|
+
function operationUsage(result, providerMetadata) {
|
|
513
|
+
const steps = Array.isArray(result.steps) ? result.steps.filter(isObjectLike) : [];
|
|
514
|
+
if (!steps.length) return modelCallUsage(result.usage, providerMetadata);
|
|
515
|
+
const total = {};
|
|
516
|
+
for (const step of steps) {
|
|
517
|
+
const stepUsage = modelCallUsage(step.usage, step.providerMetadata);
|
|
518
|
+
for (const key of TOKEN_KEYS) total[key] = sum(total[key], stepUsage[key]);
|
|
519
|
+
}
|
|
520
|
+
return total;
|
|
521
|
+
}
|
|
522
|
+
/**
|
|
490
523
|
* Cache token counts as the AI SDK normalizes them: v5 `cachedInputTokens`, v6 `inputTokenDetails`,
|
|
491
524
|
* v7 `inputTokens.{cacheRead,cacheWrite}`.
|
|
492
525
|
*/
|
|
493
|
-
function setCacheTokens(span, usage) {
|
|
494
|
-
const { cacheRead, cacheWrite } = cacheTokens(usage);
|
|
495
|
-
if (cacheRead !== void 0) span.setAttribute(GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cacheRead);
|
|
496
|
-
if (cacheWrite !== void 0) span.setAttribute(GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cacheWrite);
|
|
497
|
-
}
|
|
498
526
|
function cacheTokens(usage) {
|
|
499
527
|
const inputTokens = isObjectLike(usage.inputTokens) ? usage.inputTokens : void 0;
|
|
500
528
|
const inputTokenDetails = isObjectLike(usage.inputTokenDetails) ? usage.inputTokenDetails : void 0;
|