@sentry/server-utils 11.19.0 → 11.21.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 (59) hide show
  1. package/build/cjs/chunks/config.js +28 -0
  2. package/build/cjs/chunks/config.js.map +1 -1
  3. package/build/cjs/chunks/exports.js +6 -0
  4. package/build/cjs/index.js +424 -73
  5. package/build/cjs/index.js.map +1 -1
  6. package/build/esm/ai/tanstack-ai/constants.js +11 -0
  7. package/build/esm/ai/tanstack-ai/constants.js.map +1 -0
  8. package/build/esm/ai/tanstack-ai/index.js +206 -0
  9. package/build/esm/ai/tanstack-ai/index.js.map +1 -0
  10. package/build/esm/ai/tanstack-ai/utils.js +81 -0
  11. package/build/esm/ai/tanstack-ai/utils.js.map +1 -0
  12. package/build/esm/ai/vercel-ai/index.js +1 -12
  13. package/build/esm/ai/vercel-ai/index.js.map +1 -1
  14. package/build/esm/index.js +2 -1
  15. package/build/esm/index.js.map +1 -1
  16. package/build/esm/integrations/nitro/captureTracingEvents.js +4 -3
  17. package/build/esm/integrations/nitro/captureTracingEvents.js.map +1 -1
  18. package/build/esm/integrations/nitro/index.js +2 -2
  19. package/build/esm/integrations/nitro/index.js.map +1 -1
  20. package/build/esm/integrations/openai-compatible.js.map +1 -1
  21. package/build/esm/integrations/tanstack-ai.js +59 -0
  22. package/build/esm/integrations/tanstack-ai.js.map +1 -0
  23. package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js +70 -42
  24. package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -1
  25. package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js +21 -16
  26. package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js.map +1 -1
  27. package/build/esm/orchestrion/channels.js +2 -0
  28. package/build/esm/orchestrion/channels.js.map +1 -1
  29. package/build/esm/orchestrion/config/index.js +2 -0
  30. package/build/esm/orchestrion/config/index.js.map +1 -1
  31. package/build/esm/orchestrion/config/tanstack-ai.js +19 -0
  32. package/build/esm/orchestrion/config/tanstack-ai.js.map +1 -0
  33. package/build/esm/package.json +1 -1
  34. package/build/types/ai/tanstack-ai/constants.d.ts +8 -0
  35. package/build/types/ai/tanstack-ai/constants.d.ts.map +1 -0
  36. package/build/types/ai/tanstack-ai/index.d.ts +18 -0
  37. package/build/types/ai/tanstack-ai/index.d.ts.map +1 -0
  38. package/build/types/ai/tanstack-ai/types.d.ts +127 -0
  39. package/build/types/ai/tanstack-ai/types.d.ts.map +1 -0
  40. package/build/types/ai/tanstack-ai/utils.d.ts +21 -0
  41. package/build/types/ai/tanstack-ai/utils.d.ts.map +1 -0
  42. package/build/types/ai/vercel-ai/index.d.ts +0 -6
  43. package/build/types/ai/vercel-ai/index.d.ts.map +1 -1
  44. package/build/types/index.d.ts +2 -0
  45. package/build/types/index.d.ts.map +1 -1
  46. package/build/types/integrations/nitro/captureTracingEvents.d.ts +3 -1
  47. package/build/types/integrations/nitro/captureTracingEvents.d.ts.map +1 -1
  48. package/build/types/integrations/nitro/index.d.ts +6 -0
  49. package/build/types/integrations/nitro/index.d.ts.map +1 -1
  50. package/build/types/integrations/openai-compatible.d.ts.map +1 -1
  51. package/build/types/integrations/tanstack-ai.d.ts +18 -0
  52. package/build/types/integrations/tanstack-ai.d.ts.map +1 -0
  53. package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts.map +1 -1
  54. package/build/types/orchestrion/channels.d.ts +1 -0
  55. package/build/types/orchestrion/channels.d.ts.map +1 -1
  56. package/build/types/orchestrion/config/index.d.ts.map +1 -1
  57. package/build/types/orchestrion/config/tanstack-ai.d.ts +17 -0
  58. package/build/types/orchestrion/config/tanstack-ai.d.ts.map +1 -0
  59. package/package.json +3 -3
@@ -7550,6 +7550,12 @@ Object.defineProperty(exports, "setHttpServerSpanRouteAttribute", {
7550
7550
  return setHttpServerSpanRouteAttribute;
7551
7551
  }
7552
7552
  });
7553
+ Object.defineProperty(exports, "setOutputMessagesAttribute", {
7554
+ enumerable: true,
7555
+ get: function() {
7556
+ return setOutputMessagesAttribute$1;
7557
+ }
7558
+ });
7553
7559
  Object.defineProperty(exports, "setPiAiDriverOptions", {
7554
7560
  enumerable: true,
7555
7561
  get: function() {
@@ -1455,6 +1455,7 @@ const CHANNELS = {
1455
1455
  ...require_config.prismaChannels,
1456
1456
  ...require_config.redisChannels,
1457
1457
  ...require_config.remixChannels,
1458
+ ...require_config.tanstackAiChannels,
1458
1459
  ...require_config.tediousChannels,
1459
1460
  ...require_config.togetherAiChannels,
1460
1461
  ...require_config.typesafeChannels,
@@ -6984,6 +6985,332 @@ function instrumentPiDurable(options) {
6984
6985
  * pi-durable sends them through pi-ai.
6985
6986
  */
6986
6987
  const piDurableIntegration = (0, _sentry_core.defineIntegration)(_piDurableIntegration);
6988
+ // src/ai/tanstack-ai/constants.ts
6989
+ const TANSTACK_AI_INTEGRATION_NAME = "TanStackAI";
6990
+ const TANSTACK_AI_ORIGIN = "auto.ai.tanstack_ai";
6991
+ /**
6992
+ * Marks our middleware, so a `chat()` call that already has it does not get a second one.
6993
+ * `Symbol.for`, so that two copies of the SDK in one process see each other's middleware.
6994
+ */
6995
+ const TANSTACK_AI_MIDDLEWARE_BRAND = Symbol.for("sentry.tanstack-ai.middleware");
6996
+ // src/ai/tanstack-ai/utils.ts
6997
+ /**
6998
+ * `ctx.provider` is the adapter name, which for some adapters also names the API (for example
6999
+ * `openrouter-responses`). The call metadata has the provider of the adapter, but only after the
7000
+ * first model call started.
7001
+ */
7002
+ function getProviderName(ctx) {
7003
+ return ctx.callMetadata?.source?.provider ?? ctx.provider;
7004
+ }
7005
+ function getInputAttributes(messages, systemPrompts) {
7006
+ return {
7007
+ [_sentry_conventions_attributes.GEN_AI_INPUT_MESSAGES]: (0, _sentry_core.stringify)(messages.map(toGenAiMessage)),
7008
+ [_sentry_conventions_attributes.GEN_AI_SYSTEM_INSTRUCTIONS]: systemPrompts.length ? (0, _sentry_core.stringify)(systemPrompts.map((prompt) => ({
7009
+ type: "text",
7010
+ content: typeof prompt === "string" ? prompt : prompt.content
7011
+ }))) : void 0
7012
+ };
7013
+ }
7014
+ /**
7015
+ * TanStack AI has no common option for temperature, top p or max tokens. Each adapter takes them in
7016
+ * `modelOptions` and passes them to the provider with the provider's key name (snake_case or camelCase,
7017
+ * and `max_tokens` or `max_output_tokens`). So we take the first of the known keys that has a value.
7018
+ */
7019
+ function getRequestAttributes(modelOptions = {}) {
7020
+ const pick = (...keys) => {
7021
+ for (const key of keys) {
7022
+ const value = modelOptions[key];
7023
+ if (typeof value === "number") return value;
7024
+ }
7025
+ };
7026
+ return {
7027
+ [_sentry_conventions_attributes.GEN_AI_REQUEST_TEMPERATURE]: pick("temperature"),
7028
+ [_sentry_conventions_attributes.GEN_AI_REQUEST_TOP_P]: pick("top_p", "topP"),
7029
+ [_sentry_conventions_attributes.GEN_AI_REQUEST_MAX_TOKENS]: pick("max_tokens", "maxTokens", "max_output_tokens", "maxOutputTokens")
7030
+ };
7031
+ }
7032
+ function getUsageAttributes(usage) {
7033
+ const attributes = require_exports.getTokenUsageAttributes(usage.promptTokens, usage.completionTokens, usage.promptTokensDetails?.cacheWriteTokens, usage.promptTokensDetails?.cachedTokens, usage.totalTokens);
7034
+ if (typeof usage.completionTokensDetails?.reasoningTokens === "number") attributes[_sentry_conventions_attributes.GEN_AI_USAGE_REASONING_OUTPUT_TOKENS] = usage.completionTokensDetails.reasoningTokens;
7035
+ return attributes;
7036
+ }
7037
+ function toGenAiMessage(message) {
7038
+ const parts = [];
7039
+ const { content } = message;
7040
+ if (message.role === "tool") parts.push({
7041
+ type: "tool_call_response",
7042
+ id: message.toolCallId,
7043
+ result: content
7044
+ });
7045
+ else if (typeof content === "string") parts.push({
7046
+ type: "text",
7047
+ content
7048
+ });
7049
+ else if (Array.isArray(content)) for (const part of content) parts.push(part.type === "text" ? {
7050
+ type: "text",
7051
+ content: part.content
7052
+ } : { type: part.type });
7053
+ for (const toolCall of message.toolCalls ?? []) parts.push({
7054
+ type: "tool_call",
7055
+ id: toolCall.id,
7056
+ name: toolCall.function?.name,
7057
+ arguments: toolCall.function?.arguments
7058
+ });
7059
+ return {
7060
+ role: message.role,
7061
+ parts
7062
+ };
7063
+ }
7064
+ /** The error of a `RUN_ERROR` chunk. */
7065
+ function getRunError(chunk) {
7066
+ return chunk.error ?? {
7067
+ message: chunk.message,
7068
+ code: chunk.code
7069
+ };
7070
+ }
7071
+ // src/ai/tanstack-ai/index.ts
7072
+ const OUTPUT_CHUNK_TYPES = /* @__PURE__ */ new Set([
7073
+ "TEXT_MESSAGE_CONTENT",
7074
+ "TOOL_CALL_START",
7075
+ "REASONING_MESSAGE_CONTENT"
7076
+ ]);
7077
+ /**
7078
+ * Makes the chat middleware for one `chat()` call. Call it when `chat()` is called: the parent of the
7079
+ * `invoke_agent` span is the span that is active then, and the recording options are decided then.
7080
+ * The middleware cannot make its spans active, so the spans of other work in the run do not nest
7081
+ * below them.
7082
+ */
7083
+ function createTanstackAIMiddleware(options, call) {
7084
+ const parentSpan = (0, _sentry_core.getActiveSpan)() ?? null;
7085
+ const { recordInputs, recordOutputs } = require_exports.resolveGenAiCallRecording(options, call);
7086
+ const streaming = call.outputSchema ? call.stream === true : call.stream !== false;
7087
+ let agentSpan;
7088
+ let chatSpan;
7089
+ let outputText = "";
7090
+ let outputToolCalls = [];
7091
+ const toolCallNames = /* @__PURE__ */ new Map();
7092
+ const toolSpans = /* @__PURE__ */ new Map();
7093
+ const startSpan = (spanOptions) => {
7094
+ const span = (0, _sentry_core.startInactiveSpan)(spanOptions);
7095
+ require_exports.runGenAiSpanStart(options, span, call);
7096
+ return span;
7097
+ };
7098
+ const endSpan = (span, status, error) => {
7099
+ if (status) span.setStatus(status);
7100
+ require_exports.runGenAiSpanEnd(options, span, call, status ? { error } : {});
7101
+ span.end();
7102
+ };
7103
+ const endChatSpan = (status, error) => {
7104
+ if (chatSpan) {
7105
+ endSpan(chatSpan, status, error);
7106
+ chatSpan = void 0;
7107
+ }
7108
+ };
7109
+ const endRun = (status, error) => {
7110
+ if (!agentSpan) return;
7111
+ for (const span of toolSpans.values()) endSpan(span, status, error);
7112
+ toolSpans.clear();
7113
+ endChatSpan(status, error);
7114
+ endSpan(agentSpan, status, error);
7115
+ agentSpan = void 0;
7116
+ };
7117
+ const startChatSpan = (ctx, config) => {
7118
+ outputText = "";
7119
+ outputToolCalls = [];
7120
+ toolCallNames.clear();
7121
+ return startSpan({
7122
+ name: `chat ${ctx.model}`,
7123
+ op: require_exports.getGenAiSpanOp("chat"),
7124
+ parentSpan: agentSpan,
7125
+ attributes: {
7126
+ [_sentry_conventions_attributes.SENTRY_ORIGIN]: TANSTACK_AI_ORIGIN,
7127
+ [_sentry_conventions_attributes.GEN_AI_OPERATION_NAME]: "chat",
7128
+ [_sentry_conventions_attributes.GEN_AI_PROVIDER_NAME]: getProviderName(ctx),
7129
+ [_sentry_conventions_attributes.GEN_AI_REQUEST_MODEL]: ctx.model,
7130
+ [_sentry_conventions_attributes.GEN_AI_CONVERSATION_ID]: ctx.threadId,
7131
+ [_sentry_conventions_attributes.GEN_AI_RESPONSE_STREAMING]: streaming,
7132
+ ...getRequestAttributes(config.modelOptions),
7133
+ ...recordInputs && config.tools.length && ctx.phase !== "structuredOutput" ? { [_sentry_conventions_attributes.GEN_AI_TOOL_DEFINITIONS]: (0, _sentry_core.stringify)(config.tools.map(({ name, description, inputSchema }) => ({
7134
+ name,
7135
+ description,
7136
+ inputSchema
7137
+ }))) } : {},
7138
+ ...recordInputs ? getInputAttributes(config.providerMessages ?? config.messages, config.systemPrompts) : {}
7139
+ }
7140
+ });
7141
+ };
7142
+ return {
7143
+ name: "sentry",
7144
+ [TANSTACK_AI_MIDDLEWARE_BRAND]: true,
7145
+ onConfig(ctx, config) {
7146
+ if (ctx.phase === "init" && !agentSpan) {
7147
+ const agentName = ctx.subagentName;
7148
+ agentSpan = startSpan({
7149
+ name: agentName ? `invoke_agent ${agentName}` : "invoke_agent",
7150
+ op: require_exports.getGenAiSpanOp("invoke_agent"),
7151
+ parentSpan,
7152
+ attributes: {
7153
+ [_sentry_conventions_attributes.SENTRY_ORIGIN]: TANSTACK_AI_ORIGIN,
7154
+ [_sentry_conventions_attributes.GEN_AI_OPERATION_NAME]: "invoke_agent",
7155
+ [_sentry_conventions_attributes.GEN_AI_PROVIDER_NAME]: getProviderName(ctx),
7156
+ [_sentry_conventions_attributes.GEN_AI_REQUEST_MODEL]: ctx.model,
7157
+ [_sentry_conventions_attributes.GEN_AI_CONVERSATION_ID]: ctx.threadId,
7158
+ [_sentry_conventions_attributes.GEN_AI_RESPONSE_STREAMING]: streaming,
7159
+ [_sentry_conventions_attributes.GEN_AI_AGENT_NAME]: agentName,
7160
+ ...recordInputs ? getInputAttributes(config.messages, config.systemPrompts) : {}
7161
+ }
7162
+ });
7163
+ }
7164
+ if (!agentSpan || ctx.phase !== "beforeModel" && ctx.phase !== "structuredOutput") return;
7165
+ endChatSpan({
7166
+ code: _sentry_core.SPAN_STATUS_ERROR,
7167
+ message: "internal_error"
7168
+ });
7169
+ chatSpan = startChatSpan(ctx, config);
7170
+ },
7171
+ onChunk(ctx, chunk) {
7172
+ if (!agentSpan) return;
7173
+ if (chunk.type === "RUN_FINISHED" || chunk.type === "RUN_ERROR") {
7174
+ const provider = getProviderName(ctx);
7175
+ chatSpan?.setAttribute(_sentry_conventions_attributes.GEN_AI_PROVIDER_NAME, provider);
7176
+ agentSpan.setAttribute(_sentry_conventions_attributes.GEN_AI_PROVIDER_NAME, provider);
7177
+ }
7178
+ if (chunk.type === "RUN_ERROR") {
7179
+ endRun(require_exports.getErrorStatus(ctx.signal), getRunError(chunk));
7180
+ return;
7181
+ }
7182
+ if (chunk.type === "RUN_FINISHED" && chunk.outcome?.type === "interrupt") {
7183
+ endRun();
7184
+ return;
7185
+ }
7186
+ if (!chatSpan) return;
7187
+ if (streaming && OUTPUT_CHUNK_TYPES.has(chunk.type)) require_exports.recordTimeToFirstChunk(chatSpan);
7188
+ if (chunk.type === "TEXT_MESSAGE_CONTENT" && recordOutputs && chunk.delta) outputText += chunk.delta;
7189
+ else if (chunk.type === "TOOL_CALL_START" && chunk.toolCallId && chunk.toolCallName) toolCallNames.set(chunk.toolCallId, chunk.toolCallName);
7190
+ else if (chunk.type === "TOOL_CALL_END" && recordOutputs && chunk.toolCallId) outputToolCalls.push({
7191
+ id: chunk.toolCallId,
7192
+ name: toolCallNames.get(chunk.toolCallId),
7193
+ arguments: chunk.input ?? {}
7194
+ });
7195
+ else if (chunk.type === "RUN_FINISHED") {
7196
+ const responseModel = chunk.model ?? ctx.callMetadata?.model;
7197
+ const responseId = chunk.responseId ?? ctx.callMetadata?.responseId;
7198
+ const finishReason = chunk.finishReason ?? void 0;
7199
+ if (finishReason) chatSpan.setAttribute(_sentry_conventions_attributes.GEN_AI_RESPONSE_FINISH_REASONS, (0, _sentry_core.stringify)([finishReason]));
7200
+ for (const span of [chatSpan, agentSpan]) {
7201
+ if (responseModel) span.setAttribute(_sentry_conventions_attributes.GEN_AI_RESPONSE_MODEL, responseModel);
7202
+ if (responseId) span.setAttribute(_sentry_conventions_attributes.GEN_AI_RESPONSE_ID, responseId);
7203
+ if (recordOutputs) require_exports.setOutputMessagesAttribute(span, {
7204
+ responseText: outputText,
7205
+ toolCalls: outputToolCalls,
7206
+ finishReason
7207
+ });
7208
+ }
7209
+ }
7210
+ },
7211
+ onInterruptBoundary(ctx) {
7212
+ if (ctx.phase === "afterModel") endChatSpan();
7213
+ },
7214
+ onUsage(_ctx, usage) {
7215
+ chatSpan?.setAttributes(getUsageAttributes(usage));
7216
+ },
7217
+ onGuardToolCall(ctx, { toolName, toolCallId, args, tool }) {
7218
+ if (!agentSpan || tool && typeof tool.execute !== "function") return;
7219
+ toolSpans.set(toolCallId, startSpan({
7220
+ name: `execute_tool ${toolName}`,
7221
+ op: require_exports.getGenAiSpanOp("execute_tool"),
7222
+ parentSpan: agentSpan,
7223
+ attributes: {
7224
+ [_sentry_conventions_attributes.SENTRY_ORIGIN]: TANSTACK_AI_ORIGIN,
7225
+ [_sentry_conventions_attributes.GEN_AI_OPERATION_NAME]: "execute_tool",
7226
+ [_sentry_conventions_attributes.GEN_AI_TOOL_NAME]: toolName,
7227
+ [require_exports.GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: toolCallId,
7228
+ [_sentry_conventions_attributes.GEN_AI_CONVERSATION_ID]: ctx.threadId,
7229
+ [_sentry_conventions_attributes.GEN_AI_TOOL_DESCRIPTION]: tool?.description,
7230
+ ...recordInputs ? { [_sentry_conventions_attributes.GEN_AI_TOOL_CALL_ARGUMENTS]: (0, _sentry_core.stringify)(args) } : {}
7231
+ }
7232
+ }));
7233
+ },
7234
+ onAfterToolCall(ctx, { toolCallId, ok, result, error }) {
7235
+ const span = toolSpans.get(toolCallId);
7236
+ if (!span) return;
7237
+ toolSpans.delete(toolCallId);
7238
+ if (recordOutputs && ok && result !== void 0) span.setAttribute(_sentry_conventions_attributes.GEN_AI_TOOL_CALL_RESULT, typeof result === "string" ? result : (0, _sentry_core.stringify)(result));
7239
+ if (ok) {
7240
+ endSpan(span);
7241
+ return;
7242
+ }
7243
+ const status = require_exports.getErrorStatus(ctx.signal);
7244
+ if (status.message === "internal_error") (0, _sentry_core.withActiveSpan)(span, () => {
7245
+ (0, _sentry_core.captureException)(error, { mechanism: {
7246
+ type: TANSTACK_AI_ORIGIN,
7247
+ handled: false
7248
+ } });
7249
+ });
7250
+ endSpan(span, status, error);
7251
+ },
7252
+ onFinish() {
7253
+ endRun();
7254
+ },
7255
+ onAbort() {
7256
+ endRun({
7257
+ code: _sentry_core.SPAN_STATUS_ERROR,
7258
+ message: "cancelled"
7259
+ });
7260
+ },
7261
+ onError(ctx, { error }) {
7262
+ endRun(require_exports.getErrorStatus(ctx.signal), error);
7263
+ }
7264
+ };
7265
+ }
7266
+ // src/integrations/tanstack-ai.ts
7267
+ const _tanstackAIIntegration = ((options = {}) => {
7268
+ return {
7269
+ name: TANSTACK_AI_INTEGRATION_NAME,
7270
+ setup(client) {
7271
+ invokeOrchestrionInstrumentation(client, require_config.tanstackAiModuleNames, instrumentTanstackAI, [options], { requiresTracingChannelBinding: false });
7272
+ }
7273
+ };
7274
+ });
7275
+ let warnedOtelMiddleware = false;
7276
+ function instrumentTanstackAI(options) {
7277
+ tracingChannel(CHANNELS.TANSTACK_AI_CHAT).start.subscribe((message) => {
7278
+ safeChannelCallback(() => {
7279
+ const data = message;
7280
+ const call = data.arguments[0];
7281
+ if (!(0, _sentry_core.isObjectLike)(call)) return;
7282
+ const existing = call.middleware;
7283
+ if (existing !== void 0 && !Array.isArray(existing)) return;
7284
+ if (existing?.some((entry) => (0, _sentry_core.isObjectLike)(entry) && entry[TANSTACK_AI_MIDDLEWARE_BRAND])) return;
7285
+ if (existing?.some((entry) => (0, _sentry_core.isObjectLike)(entry) && entry.name === "otel")) warnOtelMiddleware();
7286
+ data.arguments[0] = {
7287
+ ...call,
7288
+ middleware: [...existing ?? [], createTanstackAIMiddleware(options, call)]
7289
+ };
7290
+ });
7291
+ });
7292
+ }
7293
+ function warnOtelMiddleware() {
7294
+ if (warnedOtelMiddleware) return;
7295
+ warnedOtelMiddleware = true;
7296
+ (0, _sentry_core.consoleSandbox)(() => {
7297
+ console.warn("[Sentry] `tanstackAIIntegration` is active and a `chat()` call also uses TanStack's otelMiddleware, so each run is recorded twice. Remove otelMiddleware to avoid duplicate spans.");
7298
+ });
7299
+ }
7300
+ /**
7301
+ * Traces the `chat()` calls of TanStack AI (`@tanstack/ai` >= 1.0.0 < 2), through the
7302
+ * `orchestrion:@tanstack/ai:chat` channel. Each call gets a `gen_ai.invoke_agent` span, with a
7303
+ * `gen_ai.chat` span for each model call and a `gen_ai.execute_tool` span for each tool run.
7304
+ * Needs the Sentry runtime hook (`--import`) or bundler plugin.
7305
+ *
7306
+ * @example
7307
+ * ```javascript
7308
+ * Sentry.init({
7309
+ * integrations: [Sentry.tanstackAIIntegration({ recordInputs: true, recordOutputs: true })],
7310
+ * });
7311
+ * ```
7312
+ */
7313
+ const tanstackAIIntegration = (0, _sentry_core.defineIntegration)(_tanstackAIIntegration);
6987
7314
  // src/integrations/mastra-classifier.ts
6988
7315
  /**
6989
7316
  * Add the evaluated state, questions and answers of a `Classifier.evaluate()` call to the exporter's
@@ -9243,17 +9570,6 @@ function getProviderMetadataAttributes(providerMetadata) {
9243
9570
  return attributes;
9244
9571
  }
9245
9572
  /**
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
9573
  * Sets an attribute only if the value is not null or undefined.
9258
9574
  */
9259
9575
  function setAttributeIfDefined(attributes, key, value) {
@@ -9517,19 +9833,14 @@ function getActiveSpanConversationId() {
9517
9833
  return active ? asString((0, _sentry_core.spanToJSON)(active).attributes[_sentry_conventions_attributes.GEN_AI_CONVERSATION_ID]) : void 0;
9518
9834
  }
9519
9835
  /**
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.
9836
+ * The `providerMetadata` attributes other than token counts. A partial-cost operation's cost covers
9837
+ * only its last provider call, so it stays on the `generate_content` spans.
9526
9838
  */
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];
9839
+ function getProviderOnlyAttributes(providerMetadata, type) {
9840
+ const attributes = getProviderMetadataAttributes(providerMetadata);
9841
+ for (const key of Object.values(TOKEN_ATTRIBUTES)) delete attributes[key];
9842
+ if (PARTIAL_COST_OPERATION_TYPES.has(type)) delete attributes[_sentry_conventions_attributes.GEN_AI_COST_TOTAL_TOKENS];
9843
+ return attributes;
9533
9844
  }
9534
9845
  /** Record tool name → description from an event's `tools`, so tool spans can backfill the description. */
9535
9846
  function recordToolDescriptions(callId, tools) {
@@ -9644,17 +9955,8 @@ function streamedResultToChannelResult(final) {
9644
9955
  * because the operation's completion promise settles only after every model-call stream has drained.
9645
9956
  */
9646
9957
  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
- }
9958
+ const usage = modelCallUsage(final.usage, final.providerMetadata);
9959
+ for (const key of TOKEN_KEYS) addTokensToSpan(span, TOKEN_ATTRIBUTES[key], usage[key]);
9658
9960
  if (recordOutputs) {
9659
9961
  const outputMessages = buildOutputMessages(partsFromTextAndToolCalls(final.text, final.toolCalls), getFinishReason({ finishReason: final.finishReason }));
9660
9962
  if (outputMessages) span.setAttribute(_sentry_conventions_attributes.GEN_AI_OUTPUT_MESSAGES, outputMessages);
@@ -9847,15 +10149,11 @@ function enrichSpanOnEnd(span, data) {
9847
10149
  else if (recordOutputs) span.setAttribute(_sentry_conventions_attributes.GEN_AI_TOOL_CALL_RESULT, (0, _sentry_core.stringify)(result.output ?? result));
9848
10150
  return;
9849
10151
  }
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);
10152
+ const providerMetadata = result.providerMetadata;
10153
+ const usage = ROOT_OPERATION_TYPES.has(type) ? operationUsage(result, providerMetadata) : modelCallUsage(result.usage, providerMetadata);
10154
+ for (const key of TOKEN_KEYS) {
10155
+ const value = usage[key];
10156
+ if (value !== void 0) span.setAttribute(TOKEN_ATTRIBUTES[key], value);
9859
10157
  }
9860
10158
  const finishReason = getFinishReason(result);
9861
10159
  if (finishReason && type === "languageModelCall") span.setAttribute(_sentry_conventions_attributes.GEN_AI_RESPONSE_FINISH_REASONS, (0, _sentry_core.stringify)([finishReason]));
@@ -9864,10 +10162,7 @@ function enrichSpanOnEnd(span, data) {
9864
10162
  if (responseId) span.setAttribute(_sentry_conventions_attributes.GEN_AI_RESPONSE_ID, responseId);
9865
10163
  const responseModel = asString(response?.modelId) ?? asString(data.event.modelId);
9866
10164
  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);
10165
+ span.setAttributes(getProviderOnlyAttributes(providerMetadata, type));
9871
10166
  if (recordOutputs) {
9872
10167
  const outputMessages = getOutputMessages(type, result, finishReason, data.event);
9873
10168
  if (outputMessages) span.setAttribute(_sentry_conventions_attributes.GEN_AI_OUTPUT_MESSAGES, outputMessages);
@@ -9915,14 +10210,63 @@ function tokenCount(value) {
9915
10210
  return asNumber(value) ?? ((0, _sentry_core.isObjectLike)(value) ? asNumber(value.total) : void 0);
9916
10211
  }
9917
10212
  /**
10213
+ * Reasoning from the SDK's usage: v6+ for every provider, v5 only for OpenAI, whose output includes it.
10214
+ * Other v5 providers don't say whether their output does, and Google's comes from `providerMetadata`.
10215
+ */
10216
+ function reasoningTokens(usage, providerMetadata) {
10217
+ const outputTokens = (0, _sentry_core.isObjectLike)(usage.outputTokens) ? usage.outputTokens : void 0;
10218
+ const outputTokenDetails = (0, _sentry_core.isObjectLike)(usage.outputTokenDetails) ? usage.outputTokenDetails : void 0;
10219
+ const reasoning = asNumber(outputTokens?.reasoning) ?? asNumber(outputTokenDetails?.reasoningTokens);
10220
+ if (reasoning !== void 0) return reasoning;
10221
+ const metadata = (0, _sentry_core.isObjectLike)(providerMetadata) ? providerMetadata : void 0;
10222
+ return metadata?.openai || metadata?.azure ? asNumber(usage.reasoningTokens) : void 0;
10223
+ }
10224
+ const TOKEN_ATTRIBUTES = {
10225
+ input: _sentry_conventions_attributes.GEN_AI_USAGE_INPUT_TOKENS,
10226
+ output: _sentry_conventions_attributes.GEN_AI_USAGE_OUTPUT_TOKENS,
10227
+ total: _sentry_conventions_attributes.GEN_AI_USAGE_TOTAL_TOKENS,
10228
+ cacheRead: _sentry_conventions_attributes.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,
10229
+ cacheWrite: _sentry_conventions_attributes.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,
10230
+ reasoning: _sentry_conventions_attributes.GEN_AI_USAGE_REASONING_OUTPUT_TOKENS
10231
+ };
10232
+ const TOKEN_KEYS = Object.keys(TOKEN_ATTRIBUTES);
10233
+ /**
10234
+ * One model call's final token counts: its usage (flat or `{ total }`, v4 `promptTokens`/`completionTokens`)
10235
+ * corrected by its own `providerMetadata`.
10236
+ */
10237
+ function modelCallUsage(usage, providerMetadata) {
10238
+ const derived = getProviderMetadataAttributes(providerMetadata);
10239
+ const counts = (0, _sentry_core.isObjectLike)(usage) ? usage : {};
10240
+ const input = tokenCount(counts.inputTokens) ?? tokenCount(counts.promptTokens) ?? tokenCount(counts.tokens);
10241
+ const output = asNumber(derived[_sentry_conventions_attributes.GEN_AI_USAGE_OUTPUT_TOKENS]) ?? tokenCount(counts.outputTokens) ?? tokenCount(counts.completionTokens);
10242
+ const { cacheRead, cacheWrite } = cacheTokens(counts);
10243
+ return {
10244
+ input,
10245
+ output,
10246
+ total: asNumber(derived[_sentry_conventions_attributes.GEN_AI_USAGE_TOTAL_TOKENS]) ?? tokenCount(counts.totalTokens) ?? sum(input, output),
10247
+ cacheRead: asNumber(derived[_sentry_conventions_attributes.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]) ?? cacheRead,
10248
+ cacheWrite: asNumber(derived[_sentry_conventions_attributes.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]) ?? cacheWrite,
10249
+ reasoning: reasoningTokens(counts, providerMetadata) ?? asNumber(derived[_sentry_conventions_attributes.GEN_AI_USAGE_REASONING_OUTPUT_TOKENS])
10250
+ };
10251
+ }
10252
+ /**
10253
+ * An operation's token counts, summed over its steps, which can use different providers. Every text
10254
+ * operation from v4 on has `steps`; the others are a single model call.
10255
+ */
10256
+ function operationUsage(result, providerMetadata) {
10257
+ const steps = Array.isArray(result.steps) ? result.steps.filter(_sentry_core.isObjectLike) : [];
10258
+ if (!steps.length) return modelCallUsage(result.usage, providerMetadata);
10259
+ const total = {};
10260
+ for (const step of steps) {
10261
+ const stepUsage = modelCallUsage(step.usage, step.providerMetadata);
10262
+ for (const key of TOKEN_KEYS) total[key] = sum(total[key], stepUsage[key]);
10263
+ }
10264
+ return total;
10265
+ }
10266
+ /**
9918
10267
  * Cache token counts as the AI SDK normalizes them: v5 `cachedInputTokens`, v6 `inputTokenDetails`,
9919
10268
  * v7 `inputTokens.{cacheRead,cacheWrite}`.
9920
10269
  */
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
10270
  function cacheTokens(usage) {
9927
10271
  const inputTokens = (0, _sentry_core.isObjectLike)(usage.inputTokens) ? usage.inputTokens : void 0;
9928
10272
  const inputTokenDetails = (0, _sentry_core.isObjectLike)(usage.inputTokenDetails) ? usage.inputTokenDetails : void 0;
@@ -10239,8 +10583,8 @@ function deferStreamTextOperationEnd(span, data, end) {
10239
10583
  const streamResult = data.result;
10240
10584
  (async () => {
10241
10585
  try {
10242
- const [usage, text, objectOutcome, toolCalls, finishReason, response] = await Promise.all([
10243
- streamResult.totalUsage ?? streamResult.usage,
10586
+ const [usage, text, objectOutcome, toolCalls, finishReason, response, steps, providerMetadata] = await Promise.all([
10587
+ streamResult.usage,
10244
10588
  streamResult.text,
10245
10589
  type === "streamObject" ? Promise.resolve(streamResult.object).then((value) => ({ value }), (error) => ({
10246
10590
  value: void 0,
@@ -10248,26 +10592,28 @@ function deferStreamTextOperationEnd(span, data, end) {
10248
10592
  })) : { value: void 0 },
10249
10593
  streamResult.toolCalls,
10250
10594
  streamResult.finishReason,
10251
- streamResult.response
10595
+ streamResult.response,
10596
+ streamResult.steps,
10597
+ streamResult.providerMetadata
10252
10598
  ]);
10599
+ const result = {
10600
+ usage,
10601
+ toolCalls,
10602
+ finishReason,
10603
+ response,
10604
+ steps,
10605
+ providerMetadata
10606
+ };
10253
10607
  if ("error" in objectOutcome) {
10254
- message.result = {
10255
- usage,
10256
- toolCalls,
10257
- finishReason,
10258
- response
10259
- };
10608
+ message.result = result;
10260
10609
  enrichSpanOnEnd(span, message);
10261
10610
  end(objectOutcome.error);
10262
10611
  return;
10263
10612
  }
10264
10613
  const object = objectOutcome.value;
10265
10614
  data.result = {
10266
- usage,
10267
- text: text ?? ((0, _sentry_core.isObjectLike)(object) ? JSON.stringify(object) : object),
10268
- toolCalls,
10269
- finishReason,
10270
- response
10615
+ ...result,
10616
+ text: text ?? ((0, _sentry_core.isObjectLike)(object) ? JSON.stringify(object) : object)
10271
10617
  };
10272
10618
  end();
10273
10619
  } catch (error) {
@@ -10276,9 +10622,12 @@ function deferStreamTextOperationEnd(span, data, end) {
10276
10622
  })();
10277
10623
  return true;
10278
10624
  }
10279
- /** A streamed result exposes its aggregates as promises (`totalUsage`/`usage`); a settled result does not. */
10625
+ /**
10626
+ * A streamed result exposes its aggregates as promises; a settled result does not. Reading `totalUsage`
10627
+ * would create a promise that rejects unobserved when the stream aborts.
10628
+ */
10280
10629
  function isStreamingResult(result) {
10281
- return (0, _sentry_core.isObjectLike)(result) && (isThenable(result.totalUsage) || isThenable(result.usage));
10630
+ return (0, _sentry_core.isObjectLike)(result) && (isThenable(result.steps) || isThenable(result.usage));
10282
10631
  }
10283
10632
  function isThenable(value) {
10284
10633
  return (0, _sentry_core.isObjectLike)(value) && typeof value.then === "function";
@@ -11298,10 +11647,10 @@ function isResponseCacheEntry(key, _) {
11298
11647
  /**
11299
11648
  * Captures tracing events emitted by Nitro tracing channels.
11300
11649
  */
11301
- function captureTracingEvents() {
11650
+ function captureTracingEvents(options) {
11302
11651
  const globalWithTraceChannels = _sentry_core.GLOBAL_OBJ;
11303
11652
  if (globalWithTraceChannels.__SENTRY_NITRO_HTTP_CHANNELS_INSTRUMENTED__) return;
11304
- setupH3TracingChannels();
11653
+ setupH3TracingChannels(options);
11305
11654
  setupSrvxTracingChannels();
11306
11655
  globalWithTraceChannels.__SENTRY_NITRO_HTTP_CHANNELS_INSTRUMENTED__ = true;
11307
11656
  }
@@ -11344,9 +11693,10 @@ function getParameterizedRoute(event) {
11344
11693
  if (!routePath || routePath === "/**") return;
11345
11694
  return routePath;
11346
11695
  }
11347
- function setupH3TracingChannels() {
11696
+ function setupH3TracingChannels(options) {
11348
11697
  if (!tracingChannel) return;
11349
11698
  bindTracingChannelToSpan(tracingChannel("h3.request"), (data) => {
11699
+ if (data.type === "middleware" && !options.middleware) return;
11350
11700
  const method = data.event.req.method?.toUpperCase() || _sentry_core.HTTP_SPAN_NAME_FALLBACK;
11351
11701
  if (data.type === "route" && hasHttpServerRootSpan()) {
11352
11702
  const matchedRoute = data.event.context?.matchedRoute?.route;
@@ -11477,11 +11827,11 @@ function setServerTimingHeaders(event) {
11477
11827
  // src/integrations/nitro/index.ts
11478
11828
  const INTEGRATION_NAME = "Nitro";
11479
11829
  const _nitroIntegration = ((options = {}) => {
11480
- const { serverTiming = true, storage = true } = options;
11830
+ const { middleware = true, serverTiming = true, storage = true } = options;
11481
11831
  return {
11482
11832
  name: INTEGRATION_NAME,
11483
11833
  setupOnce() {
11484
- captureTracingEvents();
11834
+ captureTracingEvents({ middleware });
11485
11835
  if (storage) captureStorageEvents();
11486
11836
  if (serverTiming) captureServerTimingHeaders();
11487
11837
  }
@@ -11654,6 +12004,7 @@ exports.setupExpressErrorHandler = setupExpressErrorHandler;
11654
12004
  exports.setupFastifyErrorHandler = setupFastifyErrorHandler;
11655
12005
  exports.setupHapiErrorHandler = setupHapiErrorHandler;
11656
12006
  exports.subscribeDiagnosticsChannel = subscribe;
12007
+ exports.tanstackAIIntegration = tanstackAIIntegration;
11657
12008
  exports.tediousIntegration = tediousIntegration;
11658
12009
  exports.togetherAIIntegration = togetherAIIntegration;
11659
12010
  exports.typesafeIntegration = typesafeIntegration;