@sentry/server-utils 11.20.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 (40) 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 +328 -0
  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/index.js +2 -1
  13. package/build/esm/index.js.map +1 -1
  14. package/build/esm/integrations/tanstack-ai.js +59 -0
  15. package/build/esm/integrations/tanstack-ai.js.map +1 -0
  16. package/build/esm/orchestrion/channels.js +2 -0
  17. package/build/esm/orchestrion/channels.js.map +1 -1
  18. package/build/esm/orchestrion/config/index.js +2 -0
  19. package/build/esm/orchestrion/config/index.js.map +1 -1
  20. package/build/esm/orchestrion/config/tanstack-ai.js +19 -0
  21. package/build/esm/orchestrion/config/tanstack-ai.js.map +1 -0
  22. package/build/esm/package.json +1 -1
  23. package/build/types/ai/tanstack-ai/constants.d.ts +8 -0
  24. package/build/types/ai/tanstack-ai/constants.d.ts.map +1 -0
  25. package/build/types/ai/tanstack-ai/index.d.ts +18 -0
  26. package/build/types/ai/tanstack-ai/index.d.ts.map +1 -0
  27. package/build/types/ai/tanstack-ai/types.d.ts +127 -0
  28. package/build/types/ai/tanstack-ai/types.d.ts.map +1 -0
  29. package/build/types/ai/tanstack-ai/utils.d.ts +21 -0
  30. package/build/types/ai/tanstack-ai/utils.d.ts.map +1 -0
  31. package/build/types/index.d.ts +2 -0
  32. package/build/types/index.d.ts.map +1 -1
  33. package/build/types/integrations/tanstack-ai.d.ts +18 -0
  34. package/build/types/integrations/tanstack-ai.d.ts.map +1 -0
  35. package/build/types/orchestrion/channels.d.ts +1 -0
  36. package/build/types/orchestrion/channels.d.ts.map +1 -1
  37. package/build/types/orchestrion/config/index.d.ts.map +1 -1
  38. package/build/types/orchestrion/config/tanstack-ai.d.ts +17 -0
  39. package/build/types/orchestrion/config/tanstack-ai.d.ts.map +1 -0
  40. 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
@@ -11677,6 +12004,7 @@ exports.setupExpressErrorHandler = setupExpressErrorHandler;
11677
12004
  exports.setupFastifyErrorHandler = setupFastifyErrorHandler;
11678
12005
  exports.setupHapiErrorHandler = setupHapiErrorHandler;
11679
12006
  exports.subscribeDiagnosticsChannel = subscribe;
12007
+ exports.tanstackAIIntegration = tanstackAIIntegration;
11680
12008
  exports.tediousIntegration = tediousIntegration;
11681
12009
  exports.togetherAIIntegration = togetherAIIntegration;
11682
12010
  exports.typesafeIntegration = typesafeIntegration;