@sentry/server-utils 11.20.0 → 11.22.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 (66) hide show
  1. package/build/cjs/chunks/config.js +30 -0
  2. package/build/cjs/chunks/config.js.map +1 -1
  3. package/build/cjs/chunks/exports.js +10 -1
  4. package/build/cjs/chunks/exports.js.map +1 -1
  5. package/build/cjs/index.js +381 -16
  6. package/build/cjs/index.js.map +1 -1
  7. package/build/esm/ai/tanstack-ai/constants.js +11 -0
  8. package/build/esm/ai/tanstack-ai/constants.js.map +1 -0
  9. package/build/esm/ai/tanstack-ai/index.js +206 -0
  10. package/build/esm/ai/tanstack-ai/index.js.map +1 -0
  11. package/build/esm/ai/tanstack-ai/utils.js +81 -0
  12. package/build/esm/ai/tanstack-ai/utils.js.map +1 -0
  13. package/build/esm/ai/workers-ai/utils.js +4 -1
  14. package/build/esm/ai/workers-ai/utils.js.map +1 -1
  15. package/build/esm/index.js +2 -1
  16. package/build/esm/index.js.map +1 -1
  17. package/build/esm/integrations/fastify/instrumentation.js +5 -1
  18. package/build/esm/integrations/fastify/instrumentation.js.map +1 -1
  19. package/build/esm/integrations/neon.js +10 -2
  20. package/build/esm/integrations/neon.js.map +1 -1
  21. package/build/esm/integrations/pg.js +41 -14
  22. package/build/esm/integrations/pg.js.map +1 -1
  23. package/build/esm/integrations/pino.js.map +1 -1
  24. package/build/esm/integrations/tanstack-ai.js +59 -0
  25. package/build/esm/integrations/tanstack-ai.js.map +1 -0
  26. package/build/esm/integrations/vercel-ai/extract.js +2 -3
  27. package/build/esm/integrations/vercel-ai/extract.js.map +1 -1
  28. package/build/esm/orchestrion/channels.js +2 -0
  29. package/build/esm/orchestrion/channels.js.map +1 -1
  30. package/build/esm/orchestrion/config/index.js +2 -0
  31. package/build/esm/orchestrion/config/index.js.map +1 -1
  32. package/build/esm/orchestrion/config/prisma.js +2 -0
  33. package/build/esm/orchestrion/config/prisma.js.map +1 -1
  34. package/build/esm/orchestrion/config/tanstack-ai.js +19 -0
  35. package/build/esm/orchestrion/config/tanstack-ai.js.map +1 -0
  36. package/build/esm/package.json +1 -1
  37. package/build/esm/tracing-channel.js.map +1 -1
  38. package/build/types/ai/tanstack-ai/constants.d.ts +8 -0
  39. package/build/types/ai/tanstack-ai/constants.d.ts.map +1 -0
  40. package/build/types/ai/tanstack-ai/index.d.ts +18 -0
  41. package/build/types/ai/tanstack-ai/index.d.ts.map +1 -0
  42. package/build/types/ai/tanstack-ai/types.d.ts +127 -0
  43. package/build/types/ai/tanstack-ai/types.d.ts.map +1 -0
  44. package/build/types/ai/tanstack-ai/utils.d.ts +21 -0
  45. package/build/types/ai/tanstack-ai/utils.d.ts.map +1 -0
  46. package/build/types/ai/workers-ai/utils.d.ts.map +1 -1
  47. package/build/types/index.d.ts +2 -0
  48. package/build/types/index.d.ts.map +1 -1
  49. package/build/types/integrations/fastify/instrumentation.d.ts.map +1 -1
  50. package/build/types/integrations/neon.d.ts.map +1 -1
  51. package/build/types/integrations/pg.d.ts +6 -1
  52. package/build/types/integrations/pg.d.ts.map +1 -1
  53. package/build/types/integrations/pino.d.ts.map +1 -1
  54. package/build/types/integrations/tanstack-ai.d.ts +18 -0
  55. package/build/types/integrations/tanstack-ai.d.ts.map +1 -0
  56. package/build/types/integrations/vercel-ai/extract.d.ts +2 -5
  57. package/build/types/integrations/vercel-ai/extract.d.ts.map +1 -1
  58. package/build/types/orchestrion/channels.d.ts +2 -0
  59. package/build/types/orchestrion/channels.d.ts.map +1 -1
  60. package/build/types/orchestrion/config/index.d.ts.map +1 -1
  61. package/build/types/orchestrion/config/prisma.d.ts +2 -1
  62. package/build/types/orchestrion/config/prisma.d.ts.map +1 -1
  63. package/build/types/orchestrion/config/tanstack-ai.d.ts +17 -0
  64. package/build/types/orchestrion/config/tanstack-ai.d.ts.map +1 -0
  65. package/build/types/tracing-channel.d.ts.map +1 -1
  66. package/package.json +4 -4
@@ -766,6 +766,10 @@ function onRequest(request, _reply, hookDone) {
766
766
  const routeName = getRequestRouteUrl(request);
767
767
  const method = request.method || "GET";
768
768
  (0, _sentry_core.getIsolationScope)().setTransactionName(`${method} ${routeName}`);
769
+ if (!(0, _sentry_core.getActiveSpan)()) {
770
+ hookDone();
771
+ return;
772
+ }
769
773
  const attributes = {
770
774
  [_sentry_conventions_attributes.SENTRY_ORIGIN]: ORIGIN$23,
771
775
  [_sentry_conventions_attributes.SENTRY_OP]: _sentry_conventions_op.HANDLER,
@@ -864,7 +868,7 @@ function handlerWrapper(handler, hookName, spanAttributes = {}) {
864
868
  if (!request) return handler.call(this, ...args);
865
869
  const parentSpan = request[kRequestSpan] ?? void 0;
866
870
  const effectiveParentSpan = parentSpan ?? (0, _sentry_core.getActiveSpan)();
867
- if (effectiveParentSpan && !(0, _sentry_core.spanIsSampled)(effectiveParentSpan)) return handler.call(this, ...args);
871
+ if (!effectiveParentSpan || !(0, _sentry_core.spanIsSampled)(effectiveParentSpan)) return handler.call(this, ...args);
868
872
  const handlerName = handler.name?.length > 0 ? handler.name : this.pluginName ?? ANONYMOUS_FUNCTION_NAME;
869
873
  const hookType = spanAttributes[ATTRIBUTE_FASTIFY_TYPE];
870
874
  const op = hookType === HOOK_TYPE_INSTANCE ? _sentry_conventions_op.MIDDLEWARE : hookType === HOOK_TYPE_HANDLER ? _sentry_conventions_op.HANDLER : void 0;
@@ -1455,6 +1459,7 @@ const CHANNELS = {
1455
1459
  ...require_config.prismaChannels,
1456
1460
  ...require_config.redisChannels,
1457
1461
  ...require_config.remixChannels,
1462
+ ...require_config.tanstackAiChannels,
1458
1463
  ...require_config.tediousChannels,
1459
1464
  ...require_config.togetherAiChannels,
1460
1465
  ...require_config.typesafeChannels,
@@ -6984,6 +6989,332 @@ function instrumentPiDurable(options) {
6984
6989
  * pi-durable sends them through pi-ai.
6985
6990
  */
6986
6991
  const piDurableIntegration = (0, _sentry_core.defineIntegration)(_piDurableIntegration);
6992
+ // src/ai/tanstack-ai/constants.ts
6993
+ const TANSTACK_AI_INTEGRATION_NAME = "TanStackAI";
6994
+ const TANSTACK_AI_ORIGIN = "auto.ai.tanstack_ai";
6995
+ /**
6996
+ * Marks our middleware, so a `chat()` call that already has it does not get a second one.
6997
+ * `Symbol.for`, so that two copies of the SDK in one process see each other's middleware.
6998
+ */
6999
+ const TANSTACK_AI_MIDDLEWARE_BRAND = Symbol.for("sentry.tanstack-ai.middleware");
7000
+ // src/ai/tanstack-ai/utils.ts
7001
+ /**
7002
+ * `ctx.provider` is the adapter name, which for some adapters also names the API (for example
7003
+ * `openrouter-responses`). The call metadata has the provider of the adapter, but only after the
7004
+ * first model call started.
7005
+ */
7006
+ function getProviderName(ctx) {
7007
+ return ctx.callMetadata?.source?.provider ?? ctx.provider;
7008
+ }
7009
+ function getInputAttributes(messages, systemPrompts) {
7010
+ return {
7011
+ [_sentry_conventions_attributes.GEN_AI_INPUT_MESSAGES]: (0, _sentry_core.stringify)(messages.map(toGenAiMessage)),
7012
+ [_sentry_conventions_attributes.GEN_AI_SYSTEM_INSTRUCTIONS]: systemPrompts.length ? (0, _sentry_core.stringify)(systemPrompts.map((prompt) => ({
7013
+ type: "text",
7014
+ content: typeof prompt === "string" ? prompt : prompt.content
7015
+ }))) : void 0
7016
+ };
7017
+ }
7018
+ /**
7019
+ * TanStack AI has no common option for temperature, top p or max tokens. Each adapter takes them in
7020
+ * `modelOptions` and passes them to the provider with the provider's key name (snake_case or camelCase,
7021
+ * and `max_tokens` or `max_output_tokens`). So we take the first of the known keys that has a value.
7022
+ */
7023
+ function getRequestAttributes(modelOptions = {}) {
7024
+ const pick = (...keys) => {
7025
+ for (const key of keys) {
7026
+ const value = modelOptions[key];
7027
+ if (typeof value === "number") return value;
7028
+ }
7029
+ };
7030
+ return {
7031
+ [_sentry_conventions_attributes.GEN_AI_REQUEST_TEMPERATURE]: pick("temperature"),
7032
+ [_sentry_conventions_attributes.GEN_AI_REQUEST_TOP_P]: pick("top_p", "topP"),
7033
+ [_sentry_conventions_attributes.GEN_AI_REQUEST_MAX_TOKENS]: pick("max_tokens", "maxTokens", "max_output_tokens", "maxOutputTokens")
7034
+ };
7035
+ }
7036
+ function getUsageAttributes(usage) {
7037
+ const attributes = require_exports.getTokenUsageAttributes(usage.promptTokens, usage.completionTokens, usage.promptTokensDetails?.cacheWriteTokens, usage.promptTokensDetails?.cachedTokens, usage.totalTokens);
7038
+ if (typeof usage.completionTokensDetails?.reasoningTokens === "number") attributes[_sentry_conventions_attributes.GEN_AI_USAGE_REASONING_OUTPUT_TOKENS] = usage.completionTokensDetails.reasoningTokens;
7039
+ return attributes;
7040
+ }
7041
+ function toGenAiMessage(message) {
7042
+ const parts = [];
7043
+ const { content } = message;
7044
+ if (message.role === "tool") parts.push({
7045
+ type: "tool_call_response",
7046
+ id: message.toolCallId,
7047
+ result: content
7048
+ });
7049
+ else if (typeof content === "string") parts.push({
7050
+ type: "text",
7051
+ content
7052
+ });
7053
+ else if (Array.isArray(content)) for (const part of content) parts.push(part.type === "text" ? {
7054
+ type: "text",
7055
+ content: part.content
7056
+ } : { type: part.type });
7057
+ for (const toolCall of message.toolCalls ?? []) parts.push({
7058
+ type: "tool_call",
7059
+ id: toolCall.id,
7060
+ name: toolCall.function?.name,
7061
+ arguments: toolCall.function?.arguments
7062
+ });
7063
+ return {
7064
+ role: message.role,
7065
+ parts
7066
+ };
7067
+ }
7068
+ /** The error of a `RUN_ERROR` chunk. */
7069
+ function getRunError(chunk) {
7070
+ return chunk.error ?? {
7071
+ message: chunk.message,
7072
+ code: chunk.code
7073
+ };
7074
+ }
7075
+ // src/ai/tanstack-ai/index.ts
7076
+ const OUTPUT_CHUNK_TYPES = /* @__PURE__ */ new Set([
7077
+ "TEXT_MESSAGE_CONTENT",
7078
+ "TOOL_CALL_START",
7079
+ "REASONING_MESSAGE_CONTENT"
7080
+ ]);
7081
+ /**
7082
+ * Makes the chat middleware for one `chat()` call. Call it when `chat()` is called: the parent of the
7083
+ * `invoke_agent` span is the span that is active then, and the recording options are decided then.
7084
+ * The middleware cannot make its spans active, so the spans of other work in the run do not nest
7085
+ * below them.
7086
+ */
7087
+ function createTanstackAIMiddleware(options, call) {
7088
+ const parentSpan = (0, _sentry_core.getActiveSpan)() ?? null;
7089
+ const { recordInputs, recordOutputs } = require_exports.resolveGenAiCallRecording(options, call);
7090
+ const streaming = call.outputSchema ? call.stream === true : call.stream !== false;
7091
+ let agentSpan;
7092
+ let chatSpan;
7093
+ let outputText = "";
7094
+ let outputToolCalls = [];
7095
+ const toolCallNames = /* @__PURE__ */ new Map();
7096
+ const toolSpans = /* @__PURE__ */ new Map();
7097
+ const startSpan = (spanOptions) => {
7098
+ const span = (0, _sentry_core.startInactiveSpan)(spanOptions);
7099
+ require_exports.runGenAiSpanStart(options, span, call);
7100
+ return span;
7101
+ };
7102
+ const endSpan = (span, status, error) => {
7103
+ if (status) span.setStatus(status);
7104
+ require_exports.runGenAiSpanEnd(options, span, call, status ? { error } : {});
7105
+ span.end();
7106
+ };
7107
+ const endChatSpan = (status, error) => {
7108
+ if (chatSpan) {
7109
+ endSpan(chatSpan, status, error);
7110
+ chatSpan = void 0;
7111
+ }
7112
+ };
7113
+ const endRun = (status, error) => {
7114
+ if (!agentSpan) return;
7115
+ for (const span of toolSpans.values()) endSpan(span, status, error);
7116
+ toolSpans.clear();
7117
+ endChatSpan(status, error);
7118
+ endSpan(agentSpan, status, error);
7119
+ agentSpan = void 0;
7120
+ };
7121
+ const startChatSpan = (ctx, config) => {
7122
+ outputText = "";
7123
+ outputToolCalls = [];
7124
+ toolCallNames.clear();
7125
+ return startSpan({
7126
+ name: `chat ${ctx.model}`,
7127
+ op: require_exports.getGenAiSpanOp("chat"),
7128
+ parentSpan: agentSpan,
7129
+ attributes: {
7130
+ [_sentry_conventions_attributes.SENTRY_ORIGIN]: TANSTACK_AI_ORIGIN,
7131
+ [_sentry_conventions_attributes.GEN_AI_OPERATION_NAME]: "chat",
7132
+ [_sentry_conventions_attributes.GEN_AI_PROVIDER_NAME]: getProviderName(ctx),
7133
+ [_sentry_conventions_attributes.GEN_AI_REQUEST_MODEL]: ctx.model,
7134
+ [_sentry_conventions_attributes.GEN_AI_CONVERSATION_ID]: ctx.threadId,
7135
+ [_sentry_conventions_attributes.GEN_AI_RESPONSE_STREAMING]: streaming,
7136
+ ...getRequestAttributes(config.modelOptions),
7137
+ ...recordInputs && config.tools.length && ctx.phase !== "structuredOutput" ? { [_sentry_conventions_attributes.GEN_AI_TOOL_DEFINITIONS]: (0, _sentry_core.stringify)(config.tools.map(({ name, description, inputSchema }) => ({
7138
+ name,
7139
+ description,
7140
+ inputSchema
7141
+ }))) } : {},
7142
+ ...recordInputs ? getInputAttributes(config.providerMessages ?? config.messages, config.systemPrompts) : {}
7143
+ }
7144
+ });
7145
+ };
7146
+ return {
7147
+ name: "sentry",
7148
+ [TANSTACK_AI_MIDDLEWARE_BRAND]: true,
7149
+ onConfig(ctx, config) {
7150
+ if (ctx.phase === "init" && !agentSpan) {
7151
+ const agentName = ctx.subagentName;
7152
+ agentSpan = startSpan({
7153
+ name: agentName ? `invoke_agent ${agentName}` : "invoke_agent",
7154
+ op: require_exports.getGenAiSpanOp("invoke_agent"),
7155
+ parentSpan,
7156
+ attributes: {
7157
+ [_sentry_conventions_attributes.SENTRY_ORIGIN]: TANSTACK_AI_ORIGIN,
7158
+ [_sentry_conventions_attributes.GEN_AI_OPERATION_NAME]: "invoke_agent",
7159
+ [_sentry_conventions_attributes.GEN_AI_PROVIDER_NAME]: getProviderName(ctx),
7160
+ [_sentry_conventions_attributes.GEN_AI_REQUEST_MODEL]: ctx.model,
7161
+ [_sentry_conventions_attributes.GEN_AI_CONVERSATION_ID]: ctx.threadId,
7162
+ [_sentry_conventions_attributes.GEN_AI_RESPONSE_STREAMING]: streaming,
7163
+ [_sentry_conventions_attributes.GEN_AI_AGENT_NAME]: agentName,
7164
+ ...recordInputs ? getInputAttributes(config.messages, config.systemPrompts) : {}
7165
+ }
7166
+ });
7167
+ }
7168
+ if (!agentSpan || ctx.phase !== "beforeModel" && ctx.phase !== "structuredOutput") return;
7169
+ endChatSpan({
7170
+ code: _sentry_core.SPAN_STATUS_ERROR,
7171
+ message: "internal_error"
7172
+ });
7173
+ chatSpan = startChatSpan(ctx, config);
7174
+ },
7175
+ onChunk(ctx, chunk) {
7176
+ if (!agentSpan) return;
7177
+ if (chunk.type === "RUN_FINISHED" || chunk.type === "RUN_ERROR") {
7178
+ const provider = getProviderName(ctx);
7179
+ chatSpan?.setAttribute(_sentry_conventions_attributes.GEN_AI_PROVIDER_NAME, provider);
7180
+ agentSpan.setAttribute(_sentry_conventions_attributes.GEN_AI_PROVIDER_NAME, provider);
7181
+ }
7182
+ if (chunk.type === "RUN_ERROR") {
7183
+ endRun(require_exports.getErrorStatus(ctx.signal), getRunError(chunk));
7184
+ return;
7185
+ }
7186
+ if (chunk.type === "RUN_FINISHED" && chunk.outcome?.type === "interrupt") {
7187
+ endRun();
7188
+ return;
7189
+ }
7190
+ if (!chatSpan) return;
7191
+ if (streaming && OUTPUT_CHUNK_TYPES.has(chunk.type)) require_exports.recordTimeToFirstChunk(chatSpan);
7192
+ if (chunk.type === "TEXT_MESSAGE_CONTENT" && recordOutputs && chunk.delta) outputText += chunk.delta;
7193
+ else if (chunk.type === "TOOL_CALL_START" && chunk.toolCallId && chunk.toolCallName) toolCallNames.set(chunk.toolCallId, chunk.toolCallName);
7194
+ else if (chunk.type === "TOOL_CALL_END" && recordOutputs && chunk.toolCallId) outputToolCalls.push({
7195
+ id: chunk.toolCallId,
7196
+ name: toolCallNames.get(chunk.toolCallId),
7197
+ arguments: chunk.input ?? {}
7198
+ });
7199
+ else if (chunk.type === "RUN_FINISHED") {
7200
+ const responseModel = chunk.model ?? ctx.callMetadata?.model;
7201
+ const responseId = chunk.responseId ?? ctx.callMetadata?.responseId;
7202
+ const finishReason = chunk.finishReason ?? void 0;
7203
+ if (finishReason) chatSpan.setAttribute(_sentry_conventions_attributes.GEN_AI_RESPONSE_FINISH_REASONS, (0, _sentry_core.stringify)([finishReason]));
7204
+ for (const span of [chatSpan, agentSpan]) {
7205
+ if (responseModel) span.setAttribute(_sentry_conventions_attributes.GEN_AI_RESPONSE_MODEL, responseModel);
7206
+ if (responseId) span.setAttribute(_sentry_conventions_attributes.GEN_AI_RESPONSE_ID, responseId);
7207
+ if (recordOutputs) require_exports.setOutputMessagesAttribute(span, {
7208
+ responseText: outputText,
7209
+ toolCalls: outputToolCalls,
7210
+ finishReason
7211
+ });
7212
+ }
7213
+ }
7214
+ },
7215
+ onInterruptBoundary(ctx) {
7216
+ if (ctx.phase === "afterModel") endChatSpan();
7217
+ },
7218
+ onUsage(_ctx, usage) {
7219
+ chatSpan?.setAttributes(getUsageAttributes(usage));
7220
+ },
7221
+ onGuardToolCall(ctx, { toolName, toolCallId, args, tool }) {
7222
+ if (!agentSpan || tool && typeof tool.execute !== "function") return;
7223
+ toolSpans.set(toolCallId, startSpan({
7224
+ name: `execute_tool ${toolName}`,
7225
+ op: require_exports.getGenAiSpanOp("execute_tool"),
7226
+ parentSpan: agentSpan,
7227
+ attributes: {
7228
+ [_sentry_conventions_attributes.SENTRY_ORIGIN]: TANSTACK_AI_ORIGIN,
7229
+ [_sentry_conventions_attributes.GEN_AI_OPERATION_NAME]: "execute_tool",
7230
+ [_sentry_conventions_attributes.GEN_AI_TOOL_NAME]: toolName,
7231
+ [require_exports.GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: toolCallId,
7232
+ [_sentry_conventions_attributes.GEN_AI_CONVERSATION_ID]: ctx.threadId,
7233
+ [_sentry_conventions_attributes.GEN_AI_TOOL_DESCRIPTION]: tool?.description,
7234
+ ...recordInputs ? { [_sentry_conventions_attributes.GEN_AI_TOOL_CALL_ARGUMENTS]: (0, _sentry_core.stringify)(args) } : {}
7235
+ }
7236
+ }));
7237
+ },
7238
+ onAfterToolCall(ctx, { toolCallId, ok, result, error }) {
7239
+ const span = toolSpans.get(toolCallId);
7240
+ if (!span) return;
7241
+ toolSpans.delete(toolCallId);
7242
+ 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));
7243
+ if (ok) {
7244
+ endSpan(span);
7245
+ return;
7246
+ }
7247
+ const status = require_exports.getErrorStatus(ctx.signal);
7248
+ if (status.message === "internal_error") (0, _sentry_core.withActiveSpan)(span, () => {
7249
+ (0, _sentry_core.captureException)(error, { mechanism: {
7250
+ type: TANSTACK_AI_ORIGIN,
7251
+ handled: false
7252
+ } });
7253
+ });
7254
+ endSpan(span, status, error);
7255
+ },
7256
+ onFinish() {
7257
+ endRun();
7258
+ },
7259
+ onAbort() {
7260
+ endRun({
7261
+ code: _sentry_core.SPAN_STATUS_ERROR,
7262
+ message: "cancelled"
7263
+ });
7264
+ },
7265
+ onError(ctx, { error }) {
7266
+ endRun(require_exports.getErrorStatus(ctx.signal), error);
7267
+ }
7268
+ };
7269
+ }
7270
+ // src/integrations/tanstack-ai.ts
7271
+ const _tanstackAIIntegration = ((options = {}) => {
7272
+ return {
7273
+ name: TANSTACK_AI_INTEGRATION_NAME,
7274
+ setup(client) {
7275
+ invokeOrchestrionInstrumentation(client, require_config.tanstackAiModuleNames, instrumentTanstackAI, [options], { requiresTracingChannelBinding: false });
7276
+ }
7277
+ };
7278
+ });
7279
+ let warnedOtelMiddleware = false;
7280
+ function instrumentTanstackAI(options) {
7281
+ tracingChannel(CHANNELS.TANSTACK_AI_CHAT).start.subscribe((message) => {
7282
+ safeChannelCallback(() => {
7283
+ const data = message;
7284
+ const call = data.arguments[0];
7285
+ if (!(0, _sentry_core.isObjectLike)(call)) return;
7286
+ const existing = call.middleware;
7287
+ if (existing !== void 0 && !Array.isArray(existing)) return;
7288
+ if (existing?.some((entry) => (0, _sentry_core.isObjectLike)(entry) && entry[TANSTACK_AI_MIDDLEWARE_BRAND])) return;
7289
+ if (existing?.some((entry) => (0, _sentry_core.isObjectLike)(entry) && entry.name === "otel")) warnOtelMiddleware();
7290
+ data.arguments[0] = {
7291
+ ...call,
7292
+ middleware: [...existing ?? [], createTanstackAIMiddleware(options, call)]
7293
+ };
7294
+ });
7295
+ });
7296
+ }
7297
+ function warnOtelMiddleware() {
7298
+ if (warnedOtelMiddleware) return;
7299
+ warnedOtelMiddleware = true;
7300
+ (0, _sentry_core.consoleSandbox)(() => {
7301
+ 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.");
7302
+ });
7303
+ }
7304
+ /**
7305
+ * Traces the `chat()` calls of TanStack AI (`@tanstack/ai` >= 1.0.0 < 2), through the
7306
+ * `orchestrion:@tanstack/ai:chat` channel. Each call gets a `gen_ai.invoke_agent` span, with a
7307
+ * `gen_ai.chat` span for each model call and a `gen_ai.execute_tool` span for each tool run.
7308
+ * Needs the Sentry runtime hook (`--import`) or bundler plugin.
7309
+ *
7310
+ * @example
7311
+ * ```javascript
7312
+ * Sentry.init({
7313
+ * integrations: [Sentry.tanstackAIIntegration({ recordInputs: true, recordOutputs: true })],
7314
+ * });
7315
+ * ```
7316
+ */
7317
+ const tanstackAIIntegration = (0, _sentry_core.defineIntegration)(_tanstackAIIntegration);
6987
7318
  // src/integrations/mastra-classifier.ts
6988
7319
  /**
6989
7320
  * Add the evaluated state, questions and answers of a `Classifier.evaluate()` call to the exporter's
@@ -8521,15 +8852,16 @@ function instrumentPostgres(options) {
8521
8852
  * streamable `Submittable` result, so it's the only one that defers span-ending to the emitter.
8522
8853
  */
8523
8854
  function bindPgQueryChannel(channelName, options) {
8524
- subscribeQueryLikeChannel(channelName, (ctx) => querySpanOptions(ctx, options), { deferStreamedResult: true });
8855
+ subscribeQueryLikeChannel(channelName, (ctx) => querySpanOptions(ctx, options), { isQuery: true });
8525
8856
  }
8526
8857
  /**
8527
8858
  * Subscribe to a pg tracing-channel and manage a span across its lifecycle.
8528
8859
  * Shared by the query/connect/pool-connect channels. They differ only in how
8529
8860
  * the span's name + attributes are built (`getSpanOptions`), and whether the
8530
- * result can be a streamable emitter (`deferStreamedResult`, query-only).
8861
+ * result is a query result that can be a streamable emitter and carries a row
8862
+ * count (`isQuery`).
8531
8863
  */
8532
- function subscribeQueryLikeChannel(channelName, getSpanOptions, { deferStreamedResult = false } = {}) {
8864
+ function subscribeQueryLikeChannel(channelName, getSpanOptions, { isQuery = false } = {}) {
8533
8865
  bindTracingChannelToSpan(tracingChannel(channelName), (data) => {
8534
8866
  data._sentryCallerScope = (0, _sentry_core.getCurrentScope)();
8535
8867
  const spanOptions = getSpanOptions(data);
@@ -8541,15 +8873,24 @@ function subscribeQueryLikeChannel(channelName, getSpanOptions, { deferStreamedR
8541
8873
  [_sentry_conventions_attributes.SENTRY_KIND]: "client"
8542
8874
  }
8543
8875
  });
8544
- }, deferStreamedResult ? { deferSpanEnd({ data, end }) {
8545
- const result = data.result;
8546
- if (!result || typeof result !== "object" || !hasOnMethod(result)) return false;
8547
- const callerScope = data._sentryCallerScope;
8548
- if (callerScope) (0, _sentry_core.bindScopeToEmitter)(result, callerScope);
8549
- result.on("error", (err) => end(err));
8550
- result.on("end", () => end());
8551
- return true;
8552
- } } : void 0);
8876
+ }, isQuery ? {
8877
+ beforeSpanEnd(span, data) {
8878
+ if ("error" in data || (0, _sentry_core.isObjectLike)(data.result) && hasOnMethod(data.result)) return;
8879
+ setReturnedRows(span, data.result);
8880
+ },
8881
+ deferSpanEnd({ span, data, end }) {
8882
+ const result = data.result;
8883
+ if (!result || typeof result !== "object" || !hasOnMethod(result)) return false;
8884
+ const callerScope = data._sentryCallerScope;
8885
+ if (callerScope) (0, _sentry_core.bindScopeToEmitter)(result, callerScope);
8886
+ result.on("error", (err) => end(err));
8887
+ result.on("end", (endResult) => {
8888
+ if (!hasReadMethod(result)) setReturnedRows(span, endResult);
8889
+ end();
8890
+ });
8891
+ return true;
8892
+ }
8893
+ } : void 0);
8553
8894
  }
8554
8895
  function querySpanOptions(ctx, { origin, connectionString }) {
8555
8896
  const params = ctx.self?.connectionParameters ?? {};
@@ -8589,6 +8930,23 @@ function poolConnectSpanOptions(ctx) {
8589
8930
  function hasOnMethod(obj) {
8590
8931
  return "on" in obj && typeof obj.on === "function";
8591
8932
  }
8933
+ function hasReadMethod(obj) {
8934
+ return "read" in obj && typeof obj.read === "function";
8935
+ }
8936
+ /**
8937
+ * Sets `db.response.returned_rows` from a pg-style result (`{ rowCount, rows }`), or an array of them
8938
+ * (one per statement of a multi-statement query), summed. Sets nothing when no count is known.
8939
+ */
8940
+ function setReturnedRows(span, results) {
8941
+ const counts = (Array.isArray(results) ? results : [results]).map(getRowCount).filter((count) => count !== void 0);
8942
+ if (counts.length) span.setAttribute(_sentry_conventions_attributes.DB_RESPONSE_RETURNED_ROWS, counts.reduce((sum, count) => sum + count, 0));
8943
+ }
8944
+ function getRowCount(result) {
8945
+ if (!(0, _sentry_core.isObjectLike)(result)) return;
8946
+ const { rowCount, rows } = result;
8947
+ if (typeof rowCount === "number") return rowCount;
8948
+ return Array.isArray(rows) ? rows.length : void 0;
8949
+ }
8592
8950
  function extractQueryConfig(args) {
8593
8951
  const arg0 = args[0];
8594
8952
  if (typeof arg0 === "string") return { text: arg0 };
@@ -8882,7 +9240,11 @@ function instrumentNeon() {
8882
9240
  const span = (0, _sentry_core.startInactiveSpan)(httpQuerySpanOptions(data.arguments));
8883
9241
  httpQuerySpans.add(span);
8884
9242
  return span;
8885
- });
9243
+ }, { beforeSpanEnd(span, data) {
9244
+ if ("error" in data) return;
9245
+ const { result } = data;
9246
+ setReturnedRows(span, Array.isArray(data.arguments[0]) && Array.isArray(result) ? result.map(toPgResult) : toPgResult(result));
9247
+ } });
8886
9248
  tracingChannel(CHANNELS.NEON_RESOLVE_CONNECTION).subscribe({
8887
9249
  start: NOOP$2,
8888
9250
  end: NOOP$2,
@@ -8924,6 +9286,9 @@ function httpQuerySpanOptions(args) {
8924
9286
  attributes
8925
9287
  };
8926
9288
  }
9289
+ function toPgResult(result) {
9290
+ return Array.isArray(result) ? { rows: result } : result;
9291
+ }
8927
9292
  function getBatchOperationName(statements) {
8928
9293
  const operations = new Set(statements.map((s) => s[_sentry_conventions_attributes.DB_OPERATION_NAME]?.toUpperCase()));
8929
9294
  const [operation] = operations;
@@ -9345,7 +9710,6 @@ function mapObjectValues(record, fn) {
9345
9710
  return Object.fromEntries(Object.entries(record).map(([key, value]) => [key, (0, _sentry_core.isObjectLike)(value) ? fn(value, key) : value]));
9346
9711
  }
9347
9712
  // src/integrations/vercel-ai/extract.ts
9348
- /** Maps the AI SDK `experimental_extract` input and output to the Clairic shape of the `gen_ai.extract` schemas. */
9349
9713
  /**
9350
9714
  * Joins the text of the AI SDK state parts into one Clairic `state` string. The gateway does this join on
9351
9715
  * the server and does not show its separator, so this one is our choice. It only makes the recorded text
@@ -9406,7 +9770,7 @@ function toExtractAnswers(answers, parts) {
9406
9770
  return mapObjectValues(answers, ({ pNull, source, items, ...rest }) => {
9407
9771
  const mapped = {
9408
9772
  ...rest,
9409
- p_null: pNull
9773
+ p_null: asNumber(pNull)
9410
9774
  };
9411
9775
  const span = toExtractSpan(source, parts);
9412
9776
  if (span) {
@@ -11677,6 +12041,7 @@ exports.setupExpressErrorHandler = setupExpressErrorHandler;
11677
12041
  exports.setupFastifyErrorHandler = setupFastifyErrorHandler;
11678
12042
  exports.setupHapiErrorHandler = setupHapiErrorHandler;
11679
12043
  exports.subscribeDiagnosticsChannel = subscribe;
12044
+ exports.tanstackAIIntegration = tanstackAIIntegration;
11680
12045
  exports.tediousIntegration = tediousIntegration;
11681
12046
  exports.togetherAIIntegration = togetherAIIntegration;
11682
12047
  exports.typesafeIntegration = typesafeIntegration;