@sentry/server-utils 11.18.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.
Files changed (25) hide show
  1. package/build/cjs/index.js +96 -73
  2. package/build/cjs/index.js.map +1 -1
  3. package/build/esm/ai/vercel-ai/index.js +1 -12
  4. package/build/esm/ai/vercel-ai/index.js.map +1 -1
  5. package/build/esm/integrations/nitro/captureTracingEvents.js +4 -3
  6. package/build/esm/integrations/nitro/captureTracingEvents.js.map +1 -1
  7. package/build/esm/integrations/nitro/index.js +2 -2
  8. package/build/esm/integrations/nitro/index.js.map +1 -1
  9. package/build/esm/integrations/openai-compatible.js.map +1 -1
  10. package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js +70 -42
  11. package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -1
  12. package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js +21 -16
  13. package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js.map +1 -1
  14. package/build/esm/package.json +1 -1
  15. package/build/types/ai/flue/types.d.ts +4 -8
  16. package/build/types/ai/flue/types.d.ts.map +1 -1
  17. package/build/types/ai/vercel-ai/index.d.ts +0 -6
  18. package/build/types/ai/vercel-ai/index.d.ts.map +1 -1
  19. package/build/types/integrations/nitro/captureTracingEvents.d.ts +3 -1
  20. package/build/types/integrations/nitro/captureTracingEvents.d.ts.map +1 -1
  21. package/build/types/integrations/nitro/index.d.ts +6 -0
  22. package/build/types/integrations/nitro/index.d.ts.map +1 -1
  23. package/build/types/integrations/openai-compatible.d.ts.map +1 -1
  24. package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts.map +1 -1
  25. package/package.json +3 -3
@@ -9243,17 +9243,6 @@ function getProviderMetadataAttributes(providerMetadata) {
9243
9243
  return attributes;
9244
9244
  }
9245
9245
  /**
9246
- * Usage attributes derived from `providerMetadata`, which describes only the last step of a call.
9247
- * They must not be written onto a span that reports usage aggregated across steps
9248
- * (`gen_ai.invoke_agent`), where they would replace the aggregate with one step's figures.
9249
- */
9250
- const LAST_STEP_ONLY_USAGE_KEYS = /* @__PURE__ */ new Set([
9251
- _sentry_conventions_attributes.GEN_AI_USAGE_OUTPUT_TOKENS,
9252
- _sentry_conventions_attributes.GEN_AI_USAGE_TOTAL_TOKENS,
9253
- _sentry_conventions_attributes.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,
9254
- _sentry_conventions_attributes.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS
9255
- ]);
9256
- /**
9257
9246
  * Sets an attribute only if the value is not null or undefined.
9258
9247
  */
9259
9248
  function setAttributeIfDefined(attributes, key, value) {
@@ -9517,19 +9506,14 @@ function getActiveSpanConversationId() {
9517
9506
  return active ? asString((0, _sentry_core.spanToJSON)(active).attributes[_sentry_conventions_attributes.GEN_AI_CONVERSATION_ID]) : void 0;
9518
9507
  }
9519
9508
  /**
9520
- * `providerMetadata` is last-step only; drop derived usage on spans that report an aggregate.
9521
- *
9522
- * Reasoning goes only when it accompanies a recomputed output (Google), because dropping that
9523
- * output leaves the span's own count reasoning-exclusive and the documented subset relationship
9524
- * would not hold. A provider that reports reasoning against an already-inclusive output (OpenAI)
9525
- * keeps it.
9509
+ * The `providerMetadata` attributes other than token counts. A partial-cost operation's cost covers
9510
+ * only its last provider call, so it stays on the `generate_content` spans.
9526
9511
  */
9527
- function dropLastStepOnlyUsage(providerAttributes, type) {
9528
- if (!ROOT_OPERATION_TYPES.has(type)) return;
9529
- const hasRecomputedOutput = _sentry_conventions_attributes.GEN_AI_USAGE_OUTPUT_TOKENS in providerAttributes;
9530
- for (const key of LAST_STEP_ONLY_USAGE_KEYS) delete providerAttributes[key];
9531
- if (hasRecomputedOutput) delete providerAttributes[_sentry_conventions_attributes.GEN_AI_USAGE_REASONING_OUTPUT_TOKENS];
9532
- if (PARTIAL_COST_OPERATION_TYPES.has(type)) delete providerAttributes[_sentry_conventions_attributes.GEN_AI_COST_TOTAL_TOKENS];
9512
+ function getProviderOnlyAttributes(providerMetadata, type) {
9513
+ const attributes = getProviderMetadataAttributes(providerMetadata);
9514
+ for (const key of Object.values(TOKEN_ATTRIBUTES)) delete attributes[key];
9515
+ if (PARTIAL_COST_OPERATION_TYPES.has(type)) delete attributes[_sentry_conventions_attributes.GEN_AI_COST_TOTAL_TOKENS];
9516
+ return attributes;
9533
9517
  }
9534
9518
  /** Record tool name → description from an event's `tools`, so tool spans can backfill the description. */
9535
9519
  function recordToolDescriptions(callId, tools) {
@@ -9644,17 +9628,8 @@ function streamedResultToChannelResult(final) {
9644
9628
  * because the operation's completion promise settles only after every model-call stream has drained.
9645
9629
  */
9646
9630
  function enrichInvokeAgentFromStream(span, final, recordOutputs) {
9647
- const usage = (0, _sentry_core.isObjectLike)(final.usage) ? final.usage : void 0;
9648
- if (usage) {
9649
- const input = tokenCount(usage.inputTokens) ?? tokenCount(usage.promptTokens) ?? tokenCount(usage.tokens);
9650
- const output = tokenCount(usage.outputTokens) ?? tokenCount(usage.completionTokens);
9651
- addTokensToSpan(span, _sentry_conventions_attributes.GEN_AI_USAGE_INPUT_TOKENS, input);
9652
- addTokensToSpan(span, _sentry_conventions_attributes.GEN_AI_USAGE_OUTPUT_TOKENS, output);
9653
- addTokensToSpan(span, _sentry_conventions_attributes.GEN_AI_USAGE_TOTAL_TOKENS, tokenCount(usage.totalTokens) ?? sum(input, output));
9654
- const { cacheRead, cacheWrite } = cacheTokens(usage);
9655
- addTokensToSpan(span, _sentry_conventions_attributes.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cacheRead);
9656
- addTokensToSpan(span, _sentry_conventions_attributes.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cacheWrite);
9657
- }
9631
+ const usage = modelCallUsage(final.usage, final.providerMetadata);
9632
+ for (const key of TOKEN_KEYS) addTokensToSpan(span, TOKEN_ATTRIBUTES[key], usage[key]);
9658
9633
  if (recordOutputs) {
9659
9634
  const outputMessages = buildOutputMessages(partsFromTextAndToolCalls(final.text, final.toolCalls), getFinishReason({ finishReason: final.finishReason }));
9660
9635
  if (outputMessages) span.setAttribute(_sentry_conventions_attributes.GEN_AI_OUTPUT_MESSAGES, outputMessages);
@@ -9847,15 +9822,11 @@ function enrichSpanOnEnd(span, data) {
9847
9822
  else if (recordOutputs) span.setAttribute(_sentry_conventions_attributes.GEN_AI_TOOL_CALL_RESULT, (0, _sentry_core.stringify)(result.output ?? result));
9848
9823
  return;
9849
9824
  }
9850
- const usage = (0, _sentry_core.isObjectLike)(result.usage) ? result.usage : void 0;
9851
- if (usage) {
9852
- const inputTokens = tokenCount(usage.inputTokens) ?? tokenCount(usage.promptTokens) ?? tokenCount(usage.tokens);
9853
- const outputTokens = tokenCount(usage.outputTokens) ?? tokenCount(usage.completionTokens);
9854
- const totalTokens = tokenCount(usage.totalTokens) ?? sum(inputTokens, outputTokens);
9855
- if (inputTokens !== void 0) span.setAttribute(_sentry_conventions_attributes.GEN_AI_USAGE_INPUT_TOKENS, inputTokens);
9856
- if (outputTokens !== void 0) span.setAttribute(_sentry_conventions_attributes.GEN_AI_USAGE_OUTPUT_TOKENS, outputTokens);
9857
- if (totalTokens !== void 0) span.setAttribute(_sentry_conventions_attributes.GEN_AI_USAGE_TOTAL_TOKENS, totalTokens);
9858
- setCacheTokens(span, usage);
9825
+ const providerMetadata = result.providerMetadata;
9826
+ const usage = ROOT_OPERATION_TYPES.has(type) ? operationUsage(result, providerMetadata) : modelCallUsage(result.usage, providerMetadata);
9827
+ for (const key of TOKEN_KEYS) {
9828
+ const value = usage[key];
9829
+ if (value !== void 0) span.setAttribute(TOKEN_ATTRIBUTES[key], value);
9859
9830
  }
9860
9831
  const finishReason = getFinishReason(result);
9861
9832
  if (finishReason && type === "languageModelCall") span.setAttribute(_sentry_conventions_attributes.GEN_AI_RESPONSE_FINISH_REASONS, (0, _sentry_core.stringify)([finishReason]));
@@ -9864,10 +9835,7 @@ function enrichSpanOnEnd(span, data) {
9864
9835
  if (responseId) span.setAttribute(_sentry_conventions_attributes.GEN_AI_RESPONSE_ID, responseId);
9865
9836
  const responseModel = asString(response?.modelId) ?? asString(data.event.modelId);
9866
9837
  if (responseModel) span.setAttribute(_sentry_conventions_attributes.GEN_AI_RESPONSE_MODEL, responseModel);
9867
- const providerMetadata = result.providerMetadata;
9868
- const providerAttributes = getProviderMetadataAttributes(providerMetadata);
9869
- dropLastStepOnlyUsage(providerAttributes, type);
9870
- span.setAttributes(providerAttributes);
9838
+ span.setAttributes(getProviderOnlyAttributes(providerMetadata, type));
9871
9839
  if (recordOutputs) {
9872
9840
  const outputMessages = getOutputMessages(type, result, finishReason, data.event);
9873
9841
  if (outputMessages) span.setAttribute(_sentry_conventions_attributes.GEN_AI_OUTPUT_MESSAGES, outputMessages);
@@ -9915,14 +9883,63 @@ function tokenCount(value) {
9915
9883
  return asNumber(value) ?? ((0, _sentry_core.isObjectLike)(value) ? asNumber(value.total) : void 0);
9916
9884
  }
9917
9885
  /**
9886
+ * Reasoning from the SDK's usage: v6+ for every provider, v5 only for OpenAI, whose output includes it.
9887
+ * Other v5 providers don't say whether their output does, and Google's comes from `providerMetadata`.
9888
+ */
9889
+ function reasoningTokens(usage, providerMetadata) {
9890
+ const outputTokens = (0, _sentry_core.isObjectLike)(usage.outputTokens) ? usage.outputTokens : void 0;
9891
+ const outputTokenDetails = (0, _sentry_core.isObjectLike)(usage.outputTokenDetails) ? usage.outputTokenDetails : void 0;
9892
+ const reasoning = asNumber(outputTokens?.reasoning) ?? asNumber(outputTokenDetails?.reasoningTokens);
9893
+ if (reasoning !== void 0) return reasoning;
9894
+ const metadata = (0, _sentry_core.isObjectLike)(providerMetadata) ? providerMetadata : void 0;
9895
+ return metadata?.openai || metadata?.azure ? asNumber(usage.reasoningTokens) : void 0;
9896
+ }
9897
+ const TOKEN_ATTRIBUTES = {
9898
+ input: _sentry_conventions_attributes.GEN_AI_USAGE_INPUT_TOKENS,
9899
+ output: _sentry_conventions_attributes.GEN_AI_USAGE_OUTPUT_TOKENS,
9900
+ total: _sentry_conventions_attributes.GEN_AI_USAGE_TOTAL_TOKENS,
9901
+ cacheRead: _sentry_conventions_attributes.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,
9902
+ cacheWrite: _sentry_conventions_attributes.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,
9903
+ reasoning: _sentry_conventions_attributes.GEN_AI_USAGE_REASONING_OUTPUT_TOKENS
9904
+ };
9905
+ const TOKEN_KEYS = Object.keys(TOKEN_ATTRIBUTES);
9906
+ /**
9907
+ * One model call's final token counts: its usage (flat or `{ total }`, v4 `promptTokens`/`completionTokens`)
9908
+ * corrected by its own `providerMetadata`.
9909
+ */
9910
+ function modelCallUsage(usage, providerMetadata) {
9911
+ const derived = getProviderMetadataAttributes(providerMetadata);
9912
+ const counts = (0, _sentry_core.isObjectLike)(usage) ? usage : {};
9913
+ const input = tokenCount(counts.inputTokens) ?? tokenCount(counts.promptTokens) ?? tokenCount(counts.tokens);
9914
+ const output = asNumber(derived[_sentry_conventions_attributes.GEN_AI_USAGE_OUTPUT_TOKENS]) ?? tokenCount(counts.outputTokens) ?? tokenCount(counts.completionTokens);
9915
+ const { cacheRead, cacheWrite } = cacheTokens(counts);
9916
+ return {
9917
+ input,
9918
+ output,
9919
+ total: asNumber(derived[_sentry_conventions_attributes.GEN_AI_USAGE_TOTAL_TOKENS]) ?? tokenCount(counts.totalTokens) ?? sum(input, output),
9920
+ cacheRead: asNumber(derived[_sentry_conventions_attributes.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]) ?? cacheRead,
9921
+ cacheWrite: asNumber(derived[_sentry_conventions_attributes.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]) ?? cacheWrite,
9922
+ reasoning: reasoningTokens(counts, providerMetadata) ?? asNumber(derived[_sentry_conventions_attributes.GEN_AI_USAGE_REASONING_OUTPUT_TOKENS])
9923
+ };
9924
+ }
9925
+ /**
9926
+ * An operation's token counts, summed over its steps, which can use different providers. Every text
9927
+ * operation from v4 on has `steps`; the others are a single model call.
9928
+ */
9929
+ function operationUsage(result, providerMetadata) {
9930
+ const steps = Array.isArray(result.steps) ? result.steps.filter(_sentry_core.isObjectLike) : [];
9931
+ if (!steps.length) return modelCallUsage(result.usage, providerMetadata);
9932
+ const total = {};
9933
+ for (const step of steps) {
9934
+ const stepUsage = modelCallUsage(step.usage, step.providerMetadata);
9935
+ for (const key of TOKEN_KEYS) total[key] = sum(total[key], stepUsage[key]);
9936
+ }
9937
+ return total;
9938
+ }
9939
+ /**
9918
9940
  * Cache token counts as the AI SDK normalizes them: v5 `cachedInputTokens`, v6 `inputTokenDetails`,
9919
9941
  * v7 `inputTokens.{cacheRead,cacheWrite}`.
9920
9942
  */
9921
- function setCacheTokens(span, usage) {
9922
- const { cacheRead, cacheWrite } = cacheTokens(usage);
9923
- if (cacheRead !== void 0) span.setAttribute(_sentry_conventions_attributes.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cacheRead);
9924
- if (cacheWrite !== void 0) span.setAttribute(_sentry_conventions_attributes.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cacheWrite);
9925
- }
9926
9943
  function cacheTokens(usage) {
9927
9944
  const inputTokens = (0, _sentry_core.isObjectLike)(usage.inputTokens) ? usage.inputTokens : void 0;
9928
9945
  const inputTokenDetails = (0, _sentry_core.isObjectLike)(usage.inputTokenDetails) ? usage.inputTokenDetails : void 0;
@@ -10239,8 +10256,8 @@ function deferStreamTextOperationEnd(span, data, end) {
10239
10256
  const streamResult = data.result;
10240
10257
  (async () => {
10241
10258
  try {
10242
- const [usage, text, objectOutcome, toolCalls, finishReason, response] = await Promise.all([
10243
- streamResult.totalUsage ?? streamResult.usage,
10259
+ const [usage, text, objectOutcome, toolCalls, finishReason, response, steps, providerMetadata] = await Promise.all([
10260
+ streamResult.usage,
10244
10261
  streamResult.text,
10245
10262
  type === "streamObject" ? Promise.resolve(streamResult.object).then((value) => ({ value }), (error) => ({
10246
10263
  value: void 0,
@@ -10248,26 +10265,28 @@ function deferStreamTextOperationEnd(span, data, end) {
10248
10265
  })) : { value: void 0 },
10249
10266
  streamResult.toolCalls,
10250
10267
  streamResult.finishReason,
10251
- streamResult.response
10268
+ streamResult.response,
10269
+ streamResult.steps,
10270
+ streamResult.providerMetadata
10252
10271
  ]);
10272
+ const result = {
10273
+ usage,
10274
+ toolCalls,
10275
+ finishReason,
10276
+ response,
10277
+ steps,
10278
+ providerMetadata
10279
+ };
10253
10280
  if ("error" in objectOutcome) {
10254
- message.result = {
10255
- usage,
10256
- toolCalls,
10257
- finishReason,
10258
- response
10259
- };
10281
+ message.result = result;
10260
10282
  enrichSpanOnEnd(span, message);
10261
10283
  end(objectOutcome.error);
10262
10284
  return;
10263
10285
  }
10264
10286
  const object = objectOutcome.value;
10265
10287
  data.result = {
10266
- usage,
10267
- text: text ?? ((0, _sentry_core.isObjectLike)(object) ? JSON.stringify(object) : object),
10268
- toolCalls,
10269
- finishReason,
10270
- response
10288
+ ...result,
10289
+ text: text ?? ((0, _sentry_core.isObjectLike)(object) ? JSON.stringify(object) : object)
10271
10290
  };
10272
10291
  end();
10273
10292
  } catch (error) {
@@ -10276,9 +10295,12 @@ function deferStreamTextOperationEnd(span, data, end) {
10276
10295
  })();
10277
10296
  return true;
10278
10297
  }
10279
- /** A streamed result exposes its aggregates as promises (`totalUsage`/`usage`); a settled result does not. */
10298
+ /**
10299
+ * A streamed result exposes its aggregates as promises; a settled result does not. Reading `totalUsage`
10300
+ * would create a promise that rejects unobserved when the stream aborts.
10301
+ */
10280
10302
  function isStreamingResult(result) {
10281
- return (0, _sentry_core.isObjectLike)(result) && (isThenable(result.totalUsage) || isThenable(result.usage));
10303
+ return (0, _sentry_core.isObjectLike)(result) && (isThenable(result.steps) || isThenable(result.usage));
10282
10304
  }
10283
10305
  function isThenable(value) {
10284
10306
  return (0, _sentry_core.isObjectLike)(value) && typeof value.then === "function";
@@ -11298,10 +11320,10 @@ function isResponseCacheEntry(key, _) {
11298
11320
  /**
11299
11321
  * Captures tracing events emitted by Nitro tracing channels.
11300
11322
  */
11301
- function captureTracingEvents() {
11323
+ function captureTracingEvents(options) {
11302
11324
  const globalWithTraceChannels = _sentry_core.GLOBAL_OBJ;
11303
11325
  if (globalWithTraceChannels.__SENTRY_NITRO_HTTP_CHANNELS_INSTRUMENTED__) return;
11304
- setupH3TracingChannels();
11326
+ setupH3TracingChannels(options);
11305
11327
  setupSrvxTracingChannels();
11306
11328
  globalWithTraceChannels.__SENTRY_NITRO_HTTP_CHANNELS_INSTRUMENTED__ = true;
11307
11329
  }
@@ -11344,9 +11366,10 @@ function getParameterizedRoute(event) {
11344
11366
  if (!routePath || routePath === "/**") return;
11345
11367
  return routePath;
11346
11368
  }
11347
- function setupH3TracingChannels() {
11369
+ function setupH3TracingChannels(options) {
11348
11370
  if (!tracingChannel) return;
11349
11371
  bindTracingChannelToSpan(tracingChannel("h3.request"), (data) => {
11372
+ if (data.type === "middleware" && !options.middleware) return;
11350
11373
  const method = data.event.req.method?.toUpperCase() || _sentry_core.HTTP_SPAN_NAME_FALLBACK;
11351
11374
  if (data.type === "route" && hasHttpServerRootSpan()) {
11352
11375
  const matchedRoute = data.event.context?.matchedRoute?.route;
@@ -11477,11 +11500,11 @@ function setServerTimingHeaders(event) {
11477
11500
  // src/integrations/nitro/index.ts
11478
11501
  const INTEGRATION_NAME = "Nitro";
11479
11502
  const _nitroIntegration = ((options = {}) => {
11480
- const { serverTiming = true, storage = true } = options;
11503
+ const { middleware = true, serverTiming = true, storage = true } = options;
11481
11504
  return {
11482
11505
  name: INTEGRATION_NAME,
11483
11506
  setupOnce() {
11484
- captureTracingEvents();
11507
+ captureTracingEvents({ middleware });
11485
11508
  if (storage) captureStorageEvents();
11486
11509
  if (serverTiming) captureServerTimingHeaders();
11487
11510
  }