@sentry/server-utils 11.21.0 → 11.23.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 (261) hide show
  1. package/build/THIRD-PARTY-LICENSES.txt +10 -10
  2. package/build/cjs/chunks/config.js +4 -2
  3. package/build/cjs/chunks/config.js.map +1 -1
  4. package/build/cjs/chunks/core.js +0 -1
  5. package/build/cjs/chunks/exports.js +76 -28
  6. package/build/cjs/chunks/exports.js.map +1 -1
  7. package/build/cjs/chunks/module-details-from-path.js +427 -428
  8. package/build/cjs/chunks/module-details-from-path.js.map +1 -1
  9. package/build/cjs/chunks/moduleInjectedTransform.js +419 -421
  10. package/build/cjs/chunks/moduleInjectedTransform.js.map +1 -1
  11. package/build/cjs/chunks/rolldown-runtime.js +8 -6
  12. package/build/cjs/index.js +95 -41
  13. package/build/cjs/index.js.map +1 -1
  14. package/build/cjs/index.request-handler.js +2 -2
  15. package/build/cjs/orchestrion/bundler/bun.js +1 -1
  16. package/build/cjs/orchestrion/bundler/esbuild.js +1 -1
  17. package/build/cjs/orchestrion/bundler/rollup.js +1 -1
  18. package/build/cjs/orchestrion/bundler/vite.js +2 -2
  19. package/build/cjs/orchestrion/bundler/webpack-loader.js +2 -2
  20. package/build/cjs/orchestrion/bundler/webpack.js +4 -4
  21. package/build/esm/_virtual/{_@oxc-project_runtime@0.158.0 → _@oxc-project_runtime@0.160.0}/helpers/defineProperty.js +1 -1
  22. package/build/esm/_virtual/{_@oxc-project_runtime@0.158.0 → _@oxc-project_runtime@0.160.0}/helpers/esm/assertClassBrand.js +1 -1
  23. package/build/esm/_virtual/{_@oxc-project_runtime@0.158.0 → _@oxc-project_runtime@0.160.0}/helpers/esm/checkPrivateRedeclaration.js +1 -1
  24. package/build/esm/_virtual/{_@oxc-project_runtime@0.158.0 → _@oxc-project_runtime@0.160.0}/helpers/esm/classPrivateFieldGet2.js +1 -1
  25. package/build/esm/_virtual/{_@oxc-project_runtime@0.158.0 → _@oxc-project_runtime@0.160.0}/helpers/esm/classPrivateFieldInitSpec.js +1 -1
  26. package/build/esm/_virtual/{_@oxc-project_runtime@0.158.0 → _@oxc-project_runtime@0.160.0}/helpers/esm/classPrivateFieldSet2.js +1 -1
  27. package/build/esm/_virtual/{_@oxc-project_runtime@0.158.0 → _@oxc-project_runtime@0.160.0}/helpers/esm/classPrivateMethodInitSpec.js +1 -1
  28. package/build/esm/_virtual/{_@oxc-project_runtime@0.158.0 → _@oxc-project_runtime@0.160.0}/helpers/esm/defineProperty.js +1 -1
  29. package/build/esm/_virtual/{_@oxc-project_runtime@0.158.0 → _@oxc-project_runtime@0.160.0}/helpers/esm/toPrimitive.js +1 -1
  30. package/build/esm/_virtual/{_@oxc-project_runtime@0.158.0 → _@oxc-project_runtime@0.160.0}/helpers/esm/toPropertyKey.js +1 -1
  31. package/build/esm/_virtual/{_@oxc-project_runtime@0.158.0 → _@oxc-project_runtime@0.160.0}/helpers/esm/typeof.js +1 -1
  32. package/build/esm/_virtual/{_@oxc-project_runtime@0.158.0 → _@oxc-project_runtime@0.160.0}/helpers/toPrimitive.js +1 -1
  33. package/build/esm/_virtual/{_@oxc-project_runtime@0.158.0 → _@oxc-project_runtime@0.160.0}/helpers/toPropertyKey.js +1 -1
  34. package/build/esm/_virtual/{_@oxc-project_runtime@0.158.0 → _@oxc-project_runtime@0.160.0}/helpers/typeof.js +1 -1
  35. package/build/esm/_virtual/_rolldown/runtime.js +8 -6
  36. package/build/esm/ai/anthropic-ai/index.js +2 -2
  37. package/build/esm/ai/anthropic-ai/streaming.js +11 -2
  38. package/build/esm/ai/anthropic-ai/streaming.js.map +1 -1
  39. package/build/esm/ai/anthropic-ai/tool-runner.js +3 -3
  40. package/build/esm/ai/anthropic-ai/utils.js +2 -2
  41. package/build/esm/ai/core/span-hooks.js +1 -1
  42. package/build/esm/ai/core/time-to-first-chunk.js +1 -1
  43. package/build/esm/ai/core/utils.js +2 -2
  44. package/build/esm/ai/flue/index.js +2 -2
  45. package/build/esm/ai/flue/utils.js +2 -2
  46. package/build/esm/ai/google-genai/decisions.js +1 -1
  47. package/build/esm/ai/google-genai/index.js +2 -2
  48. package/build/esm/ai/google-genai/streaming.js +9 -2
  49. package/build/esm/ai/google-genai/streaming.js.map +1 -1
  50. package/build/esm/ai/google-genai/utils.js +1 -1
  51. package/build/esm/ai/langchain/embeddings.js +3 -3
  52. package/build/esm/ai/langchain/index.js +15 -9
  53. package/build/esm/ai/langchain/index.js.map +1 -1
  54. package/build/esm/ai/langchain/typesafe-classifier.js +2 -2
  55. package/build/esm/ai/langchain/utils.js +3 -4
  56. package/build/esm/ai/langchain/utils.js.map +1 -1
  57. package/build/esm/ai/langgraph/agent-span.js +3 -3
  58. package/build/esm/ai/langgraph/index.js +1 -1
  59. package/build/esm/ai/langgraph/stream.js +2 -2
  60. package/build/esm/ai/langgraph/utils.js +3 -3
  61. package/build/esm/ai/mastra/index.js +2 -2
  62. package/build/esm/ai/mastra/span-registry.js +1 -1
  63. package/build/esm/ai/mastra/utils.js +2 -2
  64. package/build/esm/ai/mistral/index.js +2 -2
  65. package/build/esm/ai/mistral/streaming.js +18 -9
  66. package/build/esm/ai/mistral/streaming.js.map +1 -1
  67. package/build/esm/ai/openai/index.js +2 -2
  68. package/build/esm/ai/openai/mapping.js +1 -1
  69. package/build/esm/ai/openai/streaming.js +15 -2
  70. package/build/esm/ai/openai/streaming.js.map +1 -1
  71. package/build/esm/ai/openai/utils.js +2 -2
  72. package/build/esm/ai/pi-ai/chat.js +12 -4
  73. package/build/esm/ai/pi-ai/chat.js.map +1 -1
  74. package/build/esm/ai/pi-ai/providers.js +1 -1
  75. package/build/esm/ai/pi-ai/recording.js +1 -1
  76. package/build/esm/ai/pi-durable/index.js +2 -2
  77. package/build/esm/ai/pi-durable/runs.js +3 -3
  78. package/build/esm/ai/pi-durable/tools.js +3 -3
  79. package/build/esm/ai/tanstack-ai/index.js +2 -2
  80. package/build/esm/ai/tanstack-ai/utils.js +2 -2
  81. package/build/esm/ai/typesafe/index.js +3 -3
  82. package/build/esm/ai/workers-ai/index.js +2 -2
  83. package/build/esm/ai/workers-ai/streaming.js +7 -5
  84. package/build/esm/ai/workers-ai/streaming.js.map +1 -1
  85. package/build/esm/ai/workers-ai/utils.js +7 -4
  86. package/build/esm/ai/workers-ai/utils.js.map +1 -1
  87. package/build/esm/async-context.js +1 -1
  88. package/build/esm/cron/common.js +1 -1
  89. package/build/esm/cron/cron.js +1 -1
  90. package/build/esm/cron/node-cron.js +1 -1
  91. package/build/esm/cron/node-schedule.js +1 -1
  92. package/build/esm/eve.js +1 -1
  93. package/build/esm/integrations/amqplib.js +3 -3
  94. package/build/esm/integrations/anthropic.js +3 -4
  95. package/build/esm/integrations/anthropic.js.map +1 -1
  96. package/build/esm/integrations/aws-sdk/index.js +3 -3
  97. package/build/esm/integrations/aws-sdk/services/MessageAttributes.js +1 -1
  98. package/build/esm/integrations/aws-sdk/services/bedrock-runtime-content.js +2 -2
  99. package/build/esm/integrations/aws-sdk/services/bedrock-runtime.js +3 -3
  100. package/build/esm/integrations/aws-sdk/services/dynamodb.js +1 -1
  101. package/build/esm/integrations/aws-sdk/services/lambda.js +2 -2
  102. package/build/esm/integrations/aws-sdk/services/sns.js +3 -3
  103. package/build/esm/integrations/aws-sdk/services/sqs.js +2 -2
  104. package/build/esm/integrations/bullmq/meter.js +2 -2
  105. package/build/esm/integrations/bullmq/tracer.js +2 -2
  106. package/build/esm/integrations/clickhouse.js +3 -3
  107. package/build/esm/integrations/cron.js +1 -1
  108. package/build/esm/integrations/dataloader.js +3 -3
  109. package/build/esm/integrations/express/error-handler.js +1 -1
  110. package/build/esm/integrations/express/index.js +1 -1
  111. package/build/esm/integrations/express/instrumentation.js +3 -3
  112. package/build/esm/integrations/fastify/errors.js +1 -1
  113. package/build/esm/integrations/fastify/index.js +1 -1
  114. package/build/esm/integrations/fastify/instrumentation.js +8 -4
  115. package/build/esm/integrations/fastify/instrumentation.js.map +1 -1
  116. package/build/esm/integrations/firebase/firestore.js +2 -2
  117. package/build/esm/integrations/firebase/functions.js +1 -1
  118. package/build/esm/integrations/firebase/index.js +1 -1
  119. package/build/esm/integrations/flue.js +1 -1
  120. package/build/esm/integrations/generic-pool.js +3 -3
  121. package/build/esm/integrations/google-genai.js +2 -2
  122. package/build/esm/integrations/graphql/graphql-dc-subscriber.js +3 -3
  123. package/build/esm/integrations/graphql/index.js +1 -1
  124. package/build/esm/integrations/graphql/resolvers.js +2 -2
  125. package/build/esm/integrations/graphql/spans.js +3 -3
  126. package/build/esm/integrations/groq.js +1 -1
  127. package/build/esm/integrations/hapi/hapi-error-handler.js +1 -1
  128. package/build/esm/integrations/hapi/hapi-utils.js +4 -5
  129. package/build/esm/integrations/hapi/hapi-utils.js.map +1 -1
  130. package/build/esm/integrations/hapi/index.js +1 -1
  131. package/build/esm/integrations/hono/applyPatches.js +1 -1
  132. package/build/esm/integrations/hono/createHonoMiddleware.js +1 -1
  133. package/build/esm/integrations/hono/honoIntegration.js +3 -3
  134. package/build/esm/integrations/hono/matchResult.js +1 -1
  135. package/build/esm/integrations/hono/middlewareHandlers.js +2 -2
  136. package/build/esm/integrations/hono/patchAppRequest.js +3 -3
  137. package/build/esm/integrations/hono/patchAppUse.js +1 -1
  138. package/build/esm/integrations/hono/patchRoute.js +1 -1
  139. package/build/esm/integrations/hono/wrapMiddlewareSpan.js +3 -3
  140. package/build/esm/integrations/kafkajs/consumer.js +2 -2
  141. package/build/esm/integrations/kafkajs/index.js +1 -1
  142. package/build/esm/integrations/kafkajs/spans.js +2 -2
  143. package/build/esm/integrations/knex.js +3 -3
  144. package/build/esm/integrations/koa/index.js +3 -3
  145. package/build/esm/integrations/langchain.js +1 -1
  146. package/build/esm/integrations/langgraph.js +1 -1
  147. package/build/esm/integrations/lru-memoizer.js +1 -1
  148. package/build/esm/integrations/mastra-classifier.js +2 -2
  149. package/build/esm/integrations/mastra.js +4 -4
  150. package/build/esm/integrations/mcp-server.js +2 -2
  151. package/build/esm/integrations/mistral.js +2 -2
  152. package/build/esm/integrations/mongodb/index.js +1 -1
  153. package/build/esm/integrations/mongodb/mongodb-span.js +1 -1
  154. package/build/esm/integrations/mongoose/index.js +1 -1
  155. package/build/esm/integrations/mongoose/mongoose-dc-subscriber.js +3 -3
  156. package/build/esm/integrations/mongoose/mongoose-legacy-span.js +1 -1
  157. package/build/esm/integrations/mysql.js +3 -3
  158. package/build/esm/integrations/mysql2/index.js +1 -1
  159. package/build/esm/integrations/mysql2/mysql2-dc-subscriber.js +3 -3
  160. package/build/esm/integrations/neon.js +13 -5
  161. package/build/esm/integrations/neon.js.map +1 -1
  162. package/build/esm/integrations/nitro/captureStorageEvents.js +3 -3
  163. package/build/esm/integrations/nitro/captureTracingEvents.js +3 -3
  164. package/build/esm/integrations/nitro/index.js +1 -1
  165. package/build/esm/integrations/nitro/setServerTimingHeaders.js +1 -1
  166. package/build/esm/integrations/node-cron.js +1 -1
  167. package/build/esm/integrations/node-schedule.js +1 -1
  168. package/build/esm/integrations/openai-compatible.js +2 -2
  169. package/build/esm/integrations/openai.js +2 -2
  170. package/build/esm/integrations/pg.js +43 -16
  171. package/build/esm/integrations/pg.js.map +1 -1
  172. package/build/esm/integrations/pi-ai.js +1 -1
  173. package/build/esm/integrations/pi-durable.js +1 -1
  174. package/build/esm/integrations/pino.js +1 -1
  175. package/build/esm/integrations/pino.js.map +1 -1
  176. package/build/esm/integrations/postgresjs/index.js +3 -3
  177. package/build/esm/integrations/postgresjs/postgresjs-dc-subscriber.js +3 -3
  178. package/build/esm/integrations/postgresjs-wrapper.js +1 -1
  179. package/build/esm/integrations/prisma/index.js +1 -1
  180. package/build/esm/integrations/prisma/orchestrion.js +8 -12
  181. package/build/esm/integrations/prisma/orchestrion.js.map +1 -1
  182. package/build/esm/integrations/prisma/tracing-helper.js +2 -2
  183. package/build/esm/integrations/redis/index.js +3 -3
  184. package/build/esm/integrations/redis/ioredis-channel-subscriber.js +3 -3
  185. package/build/esm/integrations/redis/redis-cache.js +1 -1
  186. package/build/esm/integrations/redis/redis-dc-subscriber.js +3 -3
  187. package/build/esm/integrations/serveTunnel.js +2 -2
  188. package/build/esm/integrations/tanstack-ai.js +1 -1
  189. package/build/esm/integrations/tedious.js +4 -4
  190. package/build/esm/integrations/together-ai.js +1 -1
  191. package/build/esm/integrations/typesafe.js +1 -1
  192. package/build/esm/integrations/vercel-ai/extract.js +2 -3
  193. package/build/esm/integrations/vercel-ai/extract.js.map +1 -1
  194. package/build/esm/integrations/vercel-ai/index.js +1 -1
  195. package/build/esm/integrations/vercel-ai/util.js +21 -2
  196. package/build/esm/integrations/vercel-ai/util.js.map +1 -1
  197. package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js +3 -3
  198. package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js +1 -1
  199. package/build/esm/integrations/vercel-ai/vercel-ai-tool-telemetry.js +3 -3
  200. package/build/esm/integrations/winston.js +1 -1
  201. package/build/esm/opentelemetry.js +1 -1
  202. package/build/esm/orchestrion/bundler/esbuild.js +1 -1
  203. package/build/esm/orchestrion/bundler/externalRequire.js +1 -1
  204. package/build/esm/orchestrion/bundler/rollup.js +1 -1
  205. package/build/esm/orchestrion/bundler/webpack-loader.js +1 -1
  206. package/build/esm/orchestrion/bundler/webpack.js +1 -1
  207. package/build/esm/orchestrion/config/index.js +1 -1
  208. package/build/esm/orchestrion/config/mistral.js +1 -1
  209. package/build/esm/orchestrion/config/mistral.js.map +1 -1
  210. package/build/esm/orchestrion/config/prisma.js +2 -0
  211. package/build/esm/orchestrion/config/prisma.js.map +1 -1
  212. package/build/esm/orchestrion/detect.js +1 -1
  213. package/build/esm/orchestrion/instrumentation.js +1 -1
  214. package/build/esm/package.json +1 -1
  215. package/build/esm/tracing-channel.js +1 -2
  216. package/build/esm/tracing-channel.js.map +1 -1
  217. package/build/esm/utils/cronMonitoring.js +1 -1
  218. package/build/esm/utils/diagnosticsChannel.js +1 -1
  219. package/build/esm/utils/module.js +2 -2
  220. package/build/esm/utils/module.js.map +1 -1
  221. package/build/esm/utils/monitorStream.js +1 -1
  222. package/build/esm/utils/serverTimingTraceHeader.js +1 -1
  223. package/build/esm/utils/tunnelServer.js +1 -1
  224. package/build/esm/utils/wrapServerRequestHandler.js +4 -4
  225. package/build/esm/vendored/@apm-js-collab/code-transformer/lib/matcher.js +3 -3
  226. package/build/esm/vendored/@apm-js-collab/code-transformer/lib/transformer.js +5 -5
  227. package/build/esm/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/core-BiWIBBjf.js +1 -1
  228. package/build/esm/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/webpack-loader-factory.js +1 -1
  229. package/build/esm/vendored/esquery/dist/esquery.min.js +1 -0
  230. package/build/esm/vendored/esquery/dist/esquery.min.js.map +1 -1
  231. package/build/esm/vendored/meriyah/dist/meriyah.js +416 -418
  232. package/build/esm/vendored/meriyah/dist/meriyah.js.map +1 -1
  233. package/build/esm/vendored/meriyah/dist/meriyah2.js +416 -418
  234. package/build/esm/vendored/meriyah/dist/meriyah2.js.map +1 -1
  235. package/build/esm/vendored/source-map/lib/base64-vlq.js +1 -1
  236. package/build/esm/vendored/source-map/lib/base64-vlq.js.map +1 -1
  237. package/build/types/ai/anthropic-ai/streaming.d.ts.map +1 -1
  238. package/build/types/ai/anthropic-ai/types.d.ts +1 -0
  239. package/build/types/ai/anthropic-ai/types.d.ts.map +1 -1
  240. package/build/types/ai/google-genai/streaming.d.ts.map +1 -1
  241. package/build/types/ai/langchain/index.d.ts.map +1 -1
  242. package/build/types/ai/mistral/streaming.d.ts.map +1 -1
  243. package/build/types/ai/openai/streaming.d.ts.map +1 -1
  244. package/build/types/ai/pi-ai/chat.d.ts.map +1 -1
  245. package/build/types/ai/workers-ai/streaming.d.ts.map +1 -1
  246. package/build/types/ai/workers-ai/utils.d.ts.map +1 -1
  247. package/build/types/integrations/fastify/instrumentation.d.ts.map +1 -1
  248. package/build/types/integrations/neon.d.ts.map +1 -1
  249. package/build/types/integrations/pg.d.ts +6 -1
  250. package/build/types/integrations/pg.d.ts.map +1 -1
  251. package/build/types/integrations/pino.d.ts.map +1 -1
  252. package/build/types/integrations/vercel-ai/extract.d.ts +2 -5
  253. package/build/types/integrations/vercel-ai/extract.d.ts.map +1 -1
  254. package/build/types/integrations/vercel-ai/util.d.ts.map +1 -1
  255. package/build/types/orchestrion/channels.d.ts +1 -0
  256. package/build/types/orchestrion/channels.d.ts.map +1 -1
  257. package/build/types/orchestrion/config/mistral.d.ts +3 -3
  258. package/build/types/orchestrion/config/prisma.d.ts +2 -1
  259. package/build/types/orchestrion/config/prisma.d.ts.map +1 -1
  260. package/build/types/tracing-channel.d.ts.map +1 -1
  261. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","names":["addDecideResponseAttributes"],"sources":["../../../../src/ai/workers-ai/utils.ts"],"sourcesContent":["/* eslint-disable typescript-eslint/no-deprecated */\nimport {\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_OUTPUT_MESSAGES,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_FREQUENCY_PENALTY,\n GEN_AI_REQUEST_MAX_TOKENS,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_REQUEST_PRESENCE_PENALTY,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_REQUEST_TOP_K,\n GEN_AI_REQUEST_TOP_P,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_CHAT, GEN_AI_EMBEDDINGS, GEN_AI_DECIDE, GEN_AI_EXTRACT } from '@sentry/conventions/op';\nimport { isObjectLike, stringify } from '@sentry/core';\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport { GEN_AI_REQUEST_STREAM_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport {\n extractSystemInstructions,\n getEvaluationInputMessages,\n getTokenUsageAttributes,\n setOutputMessagesAttribute,\n} from '../core/utils';\nimport { addResponseAttributes as addDecideResponseAttributes } from '../typesafe';\n// Re-exported so `workers-ai/streaming.ts` keeps importing it from this module.\nexport { setOutputMessagesAttribute };\nimport { WORKERS_AI_ORIGIN, WORKERS_AI_PROVIDER_NAME } from './constants';\nimport type { WorkersAiChoice, WorkersAiInput, WorkersAiOutput } from './types';\n\nexport type WorkersAiOperationName = 'chat' | 'embeddings' | 'decide' | 'extract';\n\nexport const WORKERS_AI_OPERATION_SPAN_OPS: Record<WorkersAiOperationName, string> = {\n chat: GEN_AI_CHAT,\n embeddings: GEN_AI_EMBEDDINGS,\n decide: GEN_AI_DECIDE,\n extract: GEN_AI_EXTRACT,\n};\n\n/**\n * Model ID prefixes of the evaluation models (TypeSafe Jev and Cloudflare Clef), traced as `decide` spans.\n */\nconst DECIDE_MODEL_PREFIXES = ['typesafe/jev', '@cf/cloudflare/clef'];\n\n/**\n * Model ID prefixes of the field extraction models (Cloudflare Clairic), traced as `extract` spans.\n */\nconst EXTRACT_MODEL_PREFIXES = ['@cf/cloudflare/clairic'];\n\nconst BLOB_SUBSTITUTE = '[Blob substitute]';\n\n/**\n * Determine the gen_ai operation name from the model and inputs passed to `AI.run`.\n * Workers AI exposes a single `run` method, so we infer the operation from the model ID and the input shape.\n */\nexport function getOperationName(model: unknown, inputs: unknown): WorkersAiOperationName {\n if (typeof model === 'string' && DECIDE_MODEL_PREFIXES.some(prefix => model.startsWith(prefix))) {\n return 'decide';\n }\n if (typeof model === 'string' && EXTRACT_MODEL_PREFIXES.some(prefix => model.startsWith(prefix))) {\n return 'extract';\n }\n if (inputs && typeof inputs === 'object') {\n if ('messages' in inputs || 'prompt' in inputs) {\n return 'chat';\n }\n if ('text' in inputs) {\n return 'embeddings';\n }\n }\n return 'chat';\n}\n\n/**\n * Extract the request attributes (model, request parameters, system, origin) from a `run` call.\n */\nexport function extractRequestAttributes(\n model: unknown,\n inputs: unknown,\n operationName: string,\n): Record<string, SpanAttributeValue> {\n const attributes: Record<string, SpanAttributeValue> = {\n [GEN_AI_PROVIDER_NAME]: WORKERS_AI_PROVIDER_NAME,\n [GEN_AI_OPERATION_NAME]: operationName,\n [SENTRY_ORIGIN]: WORKERS_AI_ORIGIN,\n [GEN_AI_REQUEST_MODEL]: typeof model === 'string' ? model : 'unknown',\n };\n\n if (inputs && typeof inputs === 'object') {\n const params = inputs as WorkersAiInput;\n\n if (typeof params.temperature === 'number') {\n attributes[GEN_AI_REQUEST_TEMPERATURE] = params.temperature;\n }\n if (typeof params.max_tokens === 'number') {\n attributes[GEN_AI_REQUEST_MAX_TOKENS] = params.max_tokens;\n }\n if (typeof params.top_p === 'number') {\n attributes[GEN_AI_REQUEST_TOP_P] = params.top_p;\n }\n if (typeof params.top_k === 'number') {\n attributes[GEN_AI_REQUEST_TOP_K] = params.top_k;\n }\n if (typeof params.frequency_penalty === 'number') {\n attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY] = params.frequency_penalty;\n }\n if (typeof params.presence_penalty === 'number') {\n attributes[GEN_AI_REQUEST_PRESENCE_PENALTY] = params.presence_penalty;\n }\n if (params.stream === true) {\n attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE] = true;\n }\n }\n\n return attributes;\n}\n\n/**\n * Record the request inputs (messages/prompt/embeddings input) on the span.\n * Only called when `recordInputs` is enabled.\n */\nexport function addRequestAttributes(span: Span, inputs: unknown, operationName: string): void {\n if (!inputs || typeof inputs !== 'object') {\n return;\n }\n const params = inputs as WorkersAiInput;\n\n if (operationName === 'decide') {\n span.setAttribute(GEN_AI_INPUT_MESSAGES, getEvaluationInputMessages(inputs as Record<string, unknown>));\n return;\n }\n\n if (operationName === 'extract') {\n // Record the request body as passed, but never the image data.\n const { model: _model, ...request } = inputs as Record<string, unknown>;\n if (Array.isArray(request.images)) {\n request.images = request.images.map(() => BLOB_SUBSTITUTE);\n }\n span.setAttribute(GEN_AI_INPUT_MESSAGES, stringify([request]));\n return;\n }\n\n // Store embeddings input on a separate attribute\n if (operationName === 'embeddings') {\n const text = params.text;\n\n if (text == null || (typeof text === 'string' && text.length === 0) || (Array.isArray(text) && text.length === 0)) {\n return;\n }\n\n span.setAttribute(GEN_AI_EMBEDDINGS_INPUT, stringify(text, String));\n return;\n }\n\n const src = params.messages ?? params.prompt;\n\n if (src == null || (Array.isArray(src) && src.length === 0)) {\n return;\n }\n\n const { systemInstructions, filteredMessages } = extractSystemInstructions(src);\n\n if (systemInstructions) {\n span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS, systemInstructions);\n }\n\n span.setAttribute(GEN_AI_INPUT_MESSAGES, stringify(filteredMessages));\n}\n\n/**\n * Record the response attributes (token usage, response text, tool calls) on the span.\n */\nexport function addResponseAttributes(\n span: Span,\n result: unknown,\n recordOutputs: boolean,\n operationName?: WorkersAiOperationName,\n): void {\n if (operationName === 'decide') {\n // The binding wraps the TypeSafe response as `{ state, result }`, but the docs show it unwrapped.\n const body = isObjectLike(result) && isObjectLike(result.result) ? result.result : result;\n addDecideResponseAttributes(span, body, recordOutputs);\n return;\n }\n\n if (operationName === 'extract') {\n addExtractResponseAttributes(span, result, recordOutputs);\n return;\n }\n\n if (\n !result ||\n typeof result !== 'object' ||\n // Raw `Response` objects (from `returnRawResponse`/`websocket`) cannot be introspected without consuming them.\n (typeof Response !== 'undefined' && result instanceof Response)\n ) {\n return;\n }\n\n const response = result as WorkersAiOutput;\n\n if (response.usage) {\n span.setAttributes(getTokenUsageAttributes(response.usage.prompt_tokens, response.usage.completion_tokens));\n }\n\n if (Array.isArray(response.choices)) {\n if (typeof response.id === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_ID, response.id);\n }\n if (typeof response.model === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, response.model);\n }\n addChoicesResponseAttributes(span, response.choices, recordOutputs);\n return;\n }\n\n if (recordOutputs) {\n let responseText: string | undefined;\n if (typeof response.response === 'string') {\n responseText = response.response;\n span.setAttribute(GEN_AI_RESPONSE_TEXT, response.response);\n } else if (response.response != null) {\n responseText = JSON.stringify(response.response);\n span.setAttribute(GEN_AI_RESPONSE_TEXT, responseText);\n }\n\n const toolCalls =\n Array.isArray(response.tool_calls) && response.tool_calls.length > 0 ? response.tool_calls : undefined;\n if (toolCalls) {\n span.setAttribute(GEN_AI_RESPONSE_TOOL_CALLS, JSON.stringify(toolCalls));\n }\n\n setOutputMessagesAttribute(span, { responseText, toolCalls });\n }\n}\n\nfunction addChoicesResponseAttributes(span: Span, choices: WorkersAiChoice[], recordOutputs: boolean): void {\n const finishReasons = choices\n .map(choice => choice.finish_reason)\n .filter((reason): reason is string => typeof reason === 'string');\n if (finishReasons.length > 0) {\n span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, JSON.stringify(finishReasons));\n }\n\n if (!recordOutputs) {\n return;\n }\n\n const messages = choices.map(({ message, finish_reason }) => ({\n responseText: typeof message?.content === 'string' ? message.content : undefined,\n toolCalls: message?.tool_calls,\n finishReason: typeof finish_reason === 'string' ? finish_reason : undefined,\n }));\n\n setOutputMessagesAttribute(span, messages);\n}\n\nfunction addExtractResponseAttributes(span: Span, body: unknown, recordOutputs: boolean): void {\n if (!isObjectLike(body)) {\n return;\n }\n\n const { model, usage, ...response } = body;\n\n if (typeof model === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, model);\n }\n\n if (isObjectLike(usage)) {\n span.setAttributes(\n getTokenUsageAttributes(\n typeof usage.input_tokens === 'number' ? usage.input_tokens : undefined,\n typeof usage.output_tokens === 'number' ? usage.output_tokens : undefined,\n ),\n );\n }\n\n if (recordOutputs) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, stringify([response]));\n }\n}\n"],"mappings":";;;;;;;;AAwCA,MAAa,gCAAwE;C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E,OAAO,OAAO,GAAG,aAAa;CAEtC,IAAI,OAAO,UAAU,UACnB,KAAK,aAAa,uBAAuB,KAAK;CAGhD,IAAI,aAAa,KAAK,GACpB,KAAK,cACH,wBACE,OAAO,MAAM,iBAAiB,WAAW,MAAM,eAAe,KAAA,GAC9D,OAAO,MAAM,kBAAkB,WAAW,MAAM,gBAAgB,KAAA,CAClE,CACF;CAGF,IAAI,eACF,KAAK,aAAa,wBAAwB,UAAU,CAAC,QAAQ,CAAC,CAAC;AAEnE"}
1
+ {"version":3,"file":"utils.js","names":["addDecideResponseAttributes"],"sources":["../../../../src/ai/workers-ai/utils.ts"],"sourcesContent":["/* eslint-disable typescript-eslint/no-deprecated */\nimport {\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_OUTPUT_MESSAGES,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_FREQUENCY_PENALTY,\n GEN_AI_REQUEST_MAX_TOKENS,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_REQUEST_PRESENCE_PENALTY,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_REQUEST_TOP_K,\n GEN_AI_REQUEST_TOP_P,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_CHAT, GEN_AI_EMBEDDINGS, GEN_AI_DECIDE, GEN_AI_EXTRACT } from '@sentry/conventions/op';\nimport { isObjectLike, stringify } from '@sentry/core';\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport { GEN_AI_REQUEST_STREAM_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport {\n extractSystemInstructions,\n getEvaluationInputMessages,\n getTokenUsageAttributes,\n setOutputMessagesAttribute,\n} from '../core/utils';\nimport { addResponseAttributes as addDecideResponseAttributes } from '../typesafe';\n// Re-exported so `workers-ai/streaming.ts` keeps importing it from this module.\nexport { setOutputMessagesAttribute };\nimport { WORKERS_AI_ORIGIN, WORKERS_AI_PROVIDER_NAME } from './constants';\nimport type { WorkersAiChoice, WorkersAiInput, WorkersAiOutput } from './types';\n\nexport type WorkersAiOperationName = 'chat' | 'embeddings' | 'decide' | 'extract';\n\nexport const WORKERS_AI_OPERATION_SPAN_OPS: Record<WorkersAiOperationName, string> = {\n chat: GEN_AI_CHAT,\n embeddings: GEN_AI_EMBEDDINGS,\n decide: GEN_AI_DECIDE,\n extract: GEN_AI_EXTRACT,\n};\n\n/**\n * Model ID prefixes of the evaluation models (TypeSafe Jev and Cloudflare Clef), traced as `decide` spans.\n */\nconst DECIDE_MODEL_PREFIXES = ['typesafe/jev', '@cf/cloudflare/clef'];\n\n/**\n * Model ID prefixes of the field extraction models (Cloudflare Clairic), traced as `extract` spans.\n */\nconst EXTRACT_MODEL_PREFIXES = ['@cf/cloudflare/clairic'];\n\nconst BLOB_SUBSTITUTE = '[Blob substitute]';\n\n/**\n * Determine the gen_ai operation name from the model and inputs passed to `AI.run`.\n * Workers AI exposes a single `run` method, so we infer the operation from the model ID and the input shape.\n */\nexport function getOperationName(model: unknown, inputs: unknown): WorkersAiOperationName {\n if (typeof model === 'string' && DECIDE_MODEL_PREFIXES.some(prefix => model.startsWith(prefix))) {\n return 'decide';\n }\n if (typeof model === 'string' && EXTRACT_MODEL_PREFIXES.some(prefix => model.startsWith(prefix))) {\n return 'extract';\n }\n if (inputs && typeof inputs === 'object') {\n if ('messages' in inputs || 'prompt' in inputs) {\n return 'chat';\n }\n if ('text' in inputs) {\n return 'embeddings';\n }\n }\n return 'chat';\n}\n\n/**\n * Extract the request attributes (model, request parameters, system, origin) from a `run` call.\n */\nexport function extractRequestAttributes(\n model: unknown,\n inputs: unknown,\n operationName: string,\n): Record<string, SpanAttributeValue> {\n const attributes: Record<string, SpanAttributeValue> = {\n [GEN_AI_PROVIDER_NAME]: WORKERS_AI_PROVIDER_NAME,\n [GEN_AI_OPERATION_NAME]: operationName,\n [SENTRY_ORIGIN]: WORKERS_AI_ORIGIN,\n [GEN_AI_REQUEST_MODEL]: typeof model === 'string' ? model : 'unknown',\n };\n\n if (inputs && typeof inputs === 'object') {\n const params = inputs as WorkersAiInput;\n\n if (typeof params.temperature === 'number') {\n attributes[GEN_AI_REQUEST_TEMPERATURE] = params.temperature;\n }\n if (typeof params.max_tokens === 'number') {\n attributes[GEN_AI_REQUEST_MAX_TOKENS] = params.max_tokens;\n }\n if (typeof params.top_p === 'number') {\n attributes[GEN_AI_REQUEST_TOP_P] = params.top_p;\n }\n if (typeof params.top_k === 'number') {\n attributes[GEN_AI_REQUEST_TOP_K] = params.top_k;\n }\n if (typeof params.frequency_penalty === 'number') {\n attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY] = params.frequency_penalty;\n }\n if (typeof params.presence_penalty === 'number') {\n attributes[GEN_AI_REQUEST_PRESENCE_PENALTY] = params.presence_penalty;\n }\n if (params.stream === true) {\n attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE] = true;\n }\n }\n\n return attributes;\n}\n\n/**\n * Record the request inputs (messages/prompt/embeddings input) on the span.\n * Only called when `recordInputs` is enabled.\n */\nexport function addRequestAttributes(span: Span, inputs: unknown, operationName: string): void {\n if (!inputs || typeof inputs !== 'object') {\n return;\n }\n const params = inputs as WorkersAiInput;\n\n if (operationName === 'decide') {\n span.setAttribute(GEN_AI_INPUT_MESSAGES, getEvaluationInputMessages(inputs as Record<string, unknown>));\n return;\n }\n\n if (operationName === 'extract') {\n // Record the request body as passed, but never the image or document data.\n const { model: _model, ...request } = inputs as Record<string, unknown>;\n for (const key of ['images', 'documents']) {\n const blobs = request[key];\n if (Array.isArray(blobs)) {\n request[key] = blobs.map(() => BLOB_SUBSTITUTE);\n }\n }\n span.setAttribute(GEN_AI_INPUT_MESSAGES, stringify([request]));\n return;\n }\n\n // Store embeddings input on a separate attribute\n if (operationName === 'embeddings') {\n const text = params.text;\n\n if (text == null || (typeof text === 'string' && text.length === 0) || (Array.isArray(text) && text.length === 0)) {\n return;\n }\n\n span.setAttribute(GEN_AI_EMBEDDINGS_INPUT, stringify(text, String));\n return;\n }\n\n const src = params.messages ?? params.prompt;\n\n if (src == null || (Array.isArray(src) && src.length === 0)) {\n return;\n }\n\n const { systemInstructions, filteredMessages } = extractSystemInstructions(src);\n\n if (systemInstructions) {\n span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS, systemInstructions);\n }\n\n span.setAttribute(GEN_AI_INPUT_MESSAGES, stringify(filteredMessages));\n}\n\n/**\n * Record the response attributes (token usage, response text, tool calls) on the span.\n */\nexport function addResponseAttributes(\n span: Span,\n result: unknown,\n recordOutputs: boolean,\n operationName?: WorkersAiOperationName,\n): void {\n if (operationName === 'decide') {\n // The binding wraps the TypeSafe response as `{ state, result }`, but the docs show it unwrapped.\n const body = isObjectLike(result) && isObjectLike(result.result) ? result.result : result;\n addDecideResponseAttributes(span, body, recordOutputs);\n return;\n }\n\n if (operationName === 'extract') {\n addExtractResponseAttributes(span, result, recordOutputs);\n return;\n }\n\n if (\n !result ||\n typeof result !== 'object' ||\n // Raw `Response` objects (from `returnRawResponse`/`websocket`) cannot be introspected without consuming them.\n (typeof Response !== 'undefined' && result instanceof Response)\n ) {\n return;\n }\n\n const response = result as WorkersAiOutput;\n\n if (response.usage) {\n span.setAttributes(getTokenUsageAttributes(response.usage.prompt_tokens, response.usage.completion_tokens));\n }\n\n if (Array.isArray(response.choices)) {\n if (typeof response.id === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_ID, response.id);\n }\n if (typeof response.model === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, response.model);\n }\n addChoicesResponseAttributes(span, response.choices, recordOutputs);\n return;\n }\n\n if (recordOutputs) {\n let responseText: string | undefined;\n if (typeof response.response === 'string') {\n responseText = response.response;\n span.setAttribute(GEN_AI_RESPONSE_TEXT, response.response);\n } else if (response.response != null) {\n responseText = JSON.stringify(response.response);\n span.setAttribute(GEN_AI_RESPONSE_TEXT, responseText);\n }\n\n const toolCalls =\n Array.isArray(response.tool_calls) && response.tool_calls.length > 0 ? response.tool_calls : undefined;\n if (toolCalls) {\n span.setAttribute(GEN_AI_RESPONSE_TOOL_CALLS, JSON.stringify(toolCalls));\n }\n\n setOutputMessagesAttribute(span, { responseText, toolCalls });\n }\n}\n\nfunction addChoicesResponseAttributes(span: Span, choices: WorkersAiChoice[], recordOutputs: boolean): void {\n const finishReasons = choices\n .map(choice => choice.finish_reason)\n .filter((reason): reason is string => typeof reason === 'string');\n if (finishReasons.length > 0) {\n span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, JSON.stringify(finishReasons));\n }\n\n if (!recordOutputs) {\n return;\n }\n\n const messages = choices.map(({ message, finish_reason }) => ({\n responseText: typeof message?.content === 'string' ? message.content : undefined,\n toolCalls: message?.tool_calls,\n finishReason: typeof finish_reason === 'string' ? finish_reason : undefined,\n }));\n\n setOutputMessagesAttribute(span, messages);\n}\n\nfunction addExtractResponseAttributes(span: Span, body: unknown, recordOutputs: boolean): void {\n if (!isObjectLike(body)) {\n return;\n }\n\n const { model, usage, ...response } = body;\n\n if (typeof model === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, model);\n }\n\n if (isObjectLike(usage)) {\n span.setAttributes(\n getTokenUsageAttributes(\n typeof usage.input_tokens === 'number' ? usage.input_tokens : undefined,\n typeof usage.output_tokens === 'number' ? usage.output_tokens : undefined,\n ),\n );\n }\n\n if (recordOutputs) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, stringify([response]));\n }\n}\n"],"mappings":";;;;;;;;AAwCA,MAAa,gCAAwE;CACnF,MAAM;CACN,YAAY;CACZ,QAAQ;CACR,SAAS;AACX;;;;AAKA,MAAM,wBAAwB,CAAC,gBAAgB,qBAAqB;;;;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,OAAO,UAAU,UACnB,KAAK,aAAa,uBAAuB,KAAK;CAGhD,IAAI,aAAa,KAAK,GACpB,KAAK,cACH,wBACE,OAAO,MAAM,iBAAiB,WAAW,MAAM,eAAe,KAAA,GAC9D,OAAO,MAAM,kBAAkB,WAAW,MAAM,gBAAgB,KAAA,CAClE,CACF;CAGF,IAAI,eACF,KAAK,aAAa,wBAAwB,UAAU,CAAC,QAAQ,CAAC,CAAC;AAEnE"}
@@ -1,5 +1,5 @@
1
- import { _INTERNAL_safeMathRandom, generateTraceId, getAsyncContextStrategy, getDefaultCurrentScope, getDefaultIsolationScope, getMainCarrier, isContinuingTrace, setAsyncContextStrategy } from "@sentry/core";
2
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { _INTERNAL_safeMathRandom, generateTraceId, getAsyncContextStrategy, getDefaultCurrentScope, getDefaultIsolationScope, getMainCarrier, isContinuingTrace, setAsyncContextStrategy } from "@sentry/core";
3
3
  // src/async-context.ts
4
4
  /**
5
5
  * Sets the async context strategy to use AsyncLocalStorage.
@@ -1,6 +1,6 @@
1
+ import { debug } from "@sentry/core";
1
2
  import { DEBUG_BUILD } from "../debug-build.js";
2
3
  import { cronExpressionToMonitorConfig } from "../utils/cronMonitoring.js";
3
- import { debug } from "@sentry/core";
4
4
  // src/cron/common.ts
5
5
  /**
6
6
  * The monitor config for a cron expression, or `undefined` if Sentry would read the expression differently than the
@@ -1,5 +1,5 @@
1
- import { getCronMonitorConfig } from "./common.js";
2
1
  import { addNonEnumerableProperty, captureException, withMonitor } from "@sentry/core";
2
+ import { getCronMonitorConfig } from "./common.js";
3
3
  // src/cron/cron.ts
4
4
  const MONITORED = Symbol.for("sentry.cron.monitored");
5
5
  const ERROR_TEXT = "Automatic instrumentation of CronJob only supports crontab string";
@@ -1,6 +1,6 @@
1
+ import { addNonEnumerableProperty, captureException, startNewTrace, withMonitor } from "@sentry/core";
1
2
  import { isReadAlikeByNodeCron3 } from "../integrations/node-cron.js";
2
3
  import { getCronMonitorConfig } from "./common.js";
3
- import { addNonEnumerableProperty, captureException, startNewTrace, withMonitor } from "@sentry/core";
4
4
  // src/cron/node-cron.ts
5
5
  /**
6
6
  * Wraps the `node-cron` library with check-in monitoring.
@@ -1,5 +1,5 @@
1
- import { getCronMonitorConfig } from "./common.js";
2
1
  import { addNonEnumerableProperty, withMonitor } from "@sentry/core";
2
+ import { getCronMonitorConfig } from "./common.js";
3
3
  // src/cron/node-schedule.ts
4
4
  /**
5
5
  * Instruments the `node-schedule` library to send a check-in event to Sentry for each job execution.
package/build/esm/eve.js CHANGED
@@ -1,5 +1,5 @@
1
- import { markEveGenAiRecordingDefault } from "./integrations/vercel-ai/gen-ai-recording-mode.js";
2
1
  import { defineIntegration, setConversationId } from "@sentry/core";
2
+ import { markEveGenAiRecordingDefault } from "./integrations/vercel-ai/gen-ai-recording-mode.js";
3
3
  // src/eve.ts
4
4
  /**
5
5
  * Builds the hook definition for an eve `agent/hooks/*.ts` file that tags a session's AI spans with
@@ -1,11 +1,11 @@
1
1
  import { tracingChannel } from "../utils/diagnosticsChannel.js";
2
+ import { SPAN_STATUS_ERROR, continueTrace, defineIntegration, getClient, getTraceData, hasSpanStreamingEnabled, startInactiveSpan, timestampInSeconds } from "@sentry/core";
3
+ import { MESSAGING_DESTINATION_NAME, MESSAGING_MESSAGE_CONVERSATION_ID, MESSAGING_MESSAGE_ID, MESSAGING_OPERATION_NAME, MESSAGING_OPERATION_TYPE, MESSAGING_RABBITMQ_DESTINATION_ROUTING_KEY, MESSAGING_SYSTEM, NETWORK_PROTOCOL_NAME, NETWORK_PROTOCOL_VERSION, SENTRY_KIND, SENTRY_OP, SENTRY_ORIGIN, SENTRY_SEGMENT_NAME_SOURCE, SERVER_ADDRESS, SERVER_PORT, URL_FULL } from "@sentry/conventions/attributes";
4
+ import { QUEUE_PROCESS, QUEUE_PUBLISH } from "@sentry/conventions/op";
2
5
  import { amqplibModuleNames } from "../orchestrion/config/amqplib.js";
3
6
  import { invokeOrchestrionInstrumentation } from "../orchestrion/instrumentation.js";
4
7
  import { CHANNELS } from "../orchestrion/channels.js";
5
8
  import { bindTracingChannelToSpan } from "../tracing-channel.js";
6
- import { MESSAGING_DESTINATION_NAME, MESSAGING_MESSAGE_CONVERSATION_ID, MESSAGING_MESSAGE_ID, MESSAGING_OPERATION_NAME, MESSAGING_OPERATION_TYPE, MESSAGING_RABBITMQ_DESTINATION_ROUTING_KEY, MESSAGING_SYSTEM, NETWORK_PROTOCOL_NAME, NETWORK_PROTOCOL_VERSION, SENTRY_KIND, SENTRY_OP, SENTRY_ORIGIN, SENTRY_SEGMENT_NAME_SOURCE, SERVER_ADDRESS, SERVER_PORT, URL_FULL } from "@sentry/conventions/attributes";
7
- import { SPAN_STATUS_ERROR, continueTrace, defineIntegration, getClient, getTraceData, hasSpanStreamingEnabled, startInactiveSpan, timestampInSeconds } from "@sentry/core";
8
- import { QUEUE_PROCESS, QUEUE_PUBLISH } from "@sentry/conventions/op";
9
9
  // src/integrations/amqplib.ts
10
10
  const INTEGRATION_NAME = "Amqplib";
11
11
  const PUBLISHER_ORIGIN = "auto.queue.amqplib.publisher";
@@ -1,4 +1,6 @@
1
+ import { GEN_AI_REQUEST_MODEL, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
1
2
  import { tracingChannel } from "../utils/diagnosticsChannel.js";
3
+ import { defineIntegration, getActiveSpan, getClient, hasSpanStreamingEnabled, startInactiveSpan } from "@sentry/core";
2
4
  import { getGenAiSpanOp, getRequestSignal, markCancelledIfAborted, resolveGenAiCallRecording } from "../ai/core/utils.js";
3
5
  import { wrapApiPromiseResponse } from "../ai/core/apiPromise.js";
4
6
  import { runGenAiSpanEnd, runGenAiSpanStart } from "../ai/core/span-hooks.js";
@@ -12,8 +14,6 @@ import { CHANNELS } from "../orchestrion/channels.js";
12
14
  import { bindTracingChannelToSpan } from "../tracing-channel.js";
13
15
  import { anthropicAiModuleNames } from "../orchestrion/config/anthropic-ai.js";
14
16
  import { invokeOrchestrionInstrumentation } from "../orchestrion/instrumentation.js";
15
- import { GEN_AI_REQUEST_MODEL, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
16
- import { defineIntegration, getActiveSpan, getClient, hasSpanStreamingEnabled, startInactiveSpan } from "@sentry/core";
17
17
  // src/integrations/anthropic.ts
18
18
  const INTEGRATION_NAME = "Anthropic_AI";
19
19
  const INSTRUMENTED_CHANNELS = [{
@@ -74,8 +74,7 @@ function instrumentAnthropic(options) {
74
74
  function createGenAiSpan(data, operation, options, stream) {
75
75
  const args = data.arguments ?? [];
76
76
  if (shouldSkipAiProviderSpan(INTEGRATION_NAME)) return;
77
- const requestOptions = args[1];
78
- if (isStreamHelperRequest(requestOptions?.headers) && isInsideStreamHelperSpan()) return;
77
+ if (isStreamHelperRequest(args[1]?.headers) && isInsideStreamHelperSpan()) return;
79
78
  const params = typeof args[0] === "object" && args[0] !== null ? args[0] : void 0;
80
79
  const call = {
81
80
  operation,
@@ -1 +1 @@
1
- {"version":3,"file":"anthropic.js","names":["diagnosticsChannel.tracingChannel","diagnosticsChannel\n .tracingChannel"],"sources":["../../../src/integrations/anthropic.ts"],"sourcesContent":["import { GEN_AI_REQUEST_MODEL, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn, Span, SpanAttributeValue } from '@sentry/core';\nimport { defineIntegration, getActiveSpan, getClient, hasSpanStreamingEnabled, startInactiveSpan } from '@sentry/core';\nimport { getGenAiSpanOp, getRequestSignal, markCancelledIfAborted, resolveGenAiCallRecording } from '../ai/core/utils';\nimport { wrapApiPromiseResponse } from '../ai/core/apiPromise';\nimport { type GenAiSpanResult, runGenAiSpanEnd, runGenAiSpanStart } from '../ai/core/span-hooks';\nimport { addPrivateRequestAttributes, extractRequestAttributes } from '../ai/anthropic-ai';\nimport { ANTHROPIC_AI_ORIGIN } from '../ai/anthropic-ai/constants';\nimport { addResponseAttributes, getProviderName } from '../ai/anthropic-ai/utils';\nimport { instrumentAsyncIterableStream, instrumentMessageStream } from '../ai/anthropic-ai/streaming';\nimport { instrumentSessionToolRunner, instrumentToolRunner } from '../ai/anthropic-ai/tool-runner';\nimport type { AnthropicAiCallInfo, AnthropicAiOptions, AnthropicAiResponse } from '../ai/anthropic-ai/types';\nimport { shouldSkipAiProviderSpan } from '../ai/pi-ai/providers';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\nimport { anthropicAiModuleNames } from '../orchestrion/config/anthropic-ai';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\n\n// Same name as the OTel integration by design, so the OTel 'Anthropic_AI'\n// integration is deduplicated out of the default set.\nconst INTEGRATION_NAME = 'Anthropic_AI' as const;\n\n// The recording decision is made once, when the span starts, in the caller's async context.\ntype AnthropicChannelContext = OrchestrionChannelContext & {\n _sentryRecordOutputs?: boolean;\n _sentryOnSpanEnd?: (result: GenAiSpanResult<unknown>) => void;\n};\n\n// `stream` determines how the span is ended\nconst INSTRUMENTED_CHANNELS = [\n { channel: CHANNELS.ANTHROPIC_CHAT, operation: 'chat', stream: 'async-iterable' },\n {\n channel: CHANNELS.ANTHROPIC_MESSAGES_STREAM,\n operation: 'chat',\n stream: 'message-stream',\n },\n] as const;\n\ntype StreamMode = (typeof INSTRUMENTED_CHANNELS)[number]['stream'];\n\nconst _anthropicAIIntegration = ((options: AnthropicAiOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, anthropicAiModuleNames, instrumentAnthropic, [options]);\n },\n };\n}) satisfies IntegrationFn;\n\n// Since 0.134 `@anthropic-ai/sdk` traces itself through the global OTel tracer provider, which duplicates our\n// spans. Only turned off once our channels subscribe, so an app we do not instrument keeps the SDK's spans.\n// A value the user set wins.\nfunction disableNativeTracing(): void {\n try {\n process.env.ANTHROPIC_OPEN_TELEMETRY ??= 'false';\n } catch {\n // `process` is absent (edge runtimes) or env access is gated (Deno without `--allow-env`).\n }\n}\n\nfunction instrumentAnthropic(options: AnthropicAiOptions): void {\n disableNativeTracing();\n for (const { channel, operation, stream } of INSTRUMENTED_CHANNELS) {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<AnthropicChannelContext>(channel),\n data => createGenAiSpan(data, operation, options, stream),\n {\n beforeSpanEnd: (span, data) => {\n if ('error' in data) {\n markCancelledIfAborted(span, getRequestSignal(data.arguments?.[1]));\n }\n addResponseAttributes(span, data.result as AnthropicAiResponse, !!data._sentryRecordOutputs);\n data._sentryOnSpanEnd?.('error' in data ? { error: data.error } : { response: data.result });\n },\n deferSpanEnd: ({ span, data, end }) =>\n wrapThreadStreamRequest(span, data, end) ||\n wrapApiPromiseResponse(\n data.result,\n response => {\n data.result = response;\n if (!wrapStreamResult(span, data, stream)) {\n end();\n }\n },\n end,\n ) ||\n wrapStreamResult(span, data, stream),\n },\n );\n }\n\n diagnosticsChannel\n .tracingChannel<OrchestrionChannelContext>(CHANNELS.ANTHROPIC_TOOL_RUNNER)\n .end.subscribe(message => {\n instrumentToolRunner((message as OrchestrionChannelContext).result, options);\n });\n diagnosticsChannel\n .tracingChannel<OrchestrionChannelContext>(CHANNELS.ANTHROPIC_SESSION_TOOL_RUNNER)\n .end.subscribe(message => {\n instrumentSessionToolRunner((message as OrchestrionChannelContext).self, options);\n });\n // On `start`, because `_start()` sends the first request before it returns.\n diagnosticsChannel\n .tracingChannel<OrchestrionChannelContext>(CHANNELS.ANTHROPIC_THREAD_STREAM)\n .start.subscribe(message => {\n const data = message as OrchestrionChannelContext;\n const stream = data.self as ThreadStream | undefined;\n if (isMessageStream(stream) && stream.controller?.signal) {\n // `_start(create, params, options)`: each `create()` gets only the stream's own signal, which doesn't carry\n // the reason a caller's signal fired with.\n threadStreams.set(stream.controller.signal, { stream, callerSignal: getRequestSignal(data.arguments?.[2]) });\n }\n });\n}\n\n/**\n * Build the span for an instrumented call.\n * Returning `undefined` opts the payload out so no span is opened.\n */\nfunction createGenAiSpan(\n data: AnthropicChannelContext,\n operation: 'chat',\n options: AnthropicAiOptions,\n stream: StreamMode,\n): Span | undefined {\n const args = data.arguments ?? [];\n\n if (shouldSkipAiProviderSpan(INTEGRATION_NAME)) {\n return undefined;\n }\n\n // `messages.stream()` internally calls the instrumented `messages.create({ stream: true })` tagged with\n // a `stream` helper-method header. The messages-stream channel already covers it, so skip the nested\n // create to avoid a duplicate span. Only the non-beta helper is on that channel, though:\n // `beta.messages.stream()` and the streaming tool runner send the same header with no span covering\n // them, so the header alone is not enough. Skip only while a stream-helper span of ours is active.\n const requestOptions = args[1] as { headers?: unknown } | undefined;\n if (isStreamHelperRequest(requestOptions?.headers) && isInsideStreamHelperSpan()) {\n return undefined;\n }\n\n const params = typeof args[0] === 'object' && args[0] !== null ? (args[0] as Record<string, unknown>) : undefined;\n\n const call: AnthropicAiCallInfo = { operation, request: params };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n data._sentryRecordOutputs = recordOutputs;\n\n const attributes = extractRequestAttributes(args, operation, recordInputs, getProviderName(data.self));\n const model = (attributes[GEN_AI_REQUEST_MODEL] as string) || 'unknown';\n attributes[SENTRY_ORIGIN] = ANTHROPIC_AI_ORIGIN;\n const client = getClient();\n\n const span = startInactiveSpan({\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name: model !== 'unknown' || !(client && hasSpanStreamingEnabled(client)) ? `${operation} ${model}` : operation,\n op: getGenAiSpanOp(operation),\n attributes: attributes as Record<string, SpanAttributeValue>,\n });\n\n if (recordInputs && params) {\n addPrivateRequestAttributes(span, params);\n }\n\n runGenAiSpanStart(options, span, call);\n data._sentryOnSpanEnd = result => runGenAiSpanEnd(options, span, call, result);\n\n if (stream === 'message-stream') {\n streamHelperSpans.add(span);\n }\n\n return span;\n}\n\nconst STREAM_HELPER_METHOD_HEADER = 'x-stainless-helper-method';\n\n/** The spans opened for the messages-stream channel, i.e. for `messages.stream()` calls. */\nconst streamHelperSpans = new WeakSet<Span>();\n\n/**\n * Whether the active span is one this integration opened for `messages.stream()`. The helper's\n * internal `create` runs inside that span, so this is what tells it apart from the beta helper and\n * the tool runner, which send the same header but are not on the messages-stream channel.\n */\nfunction isInsideStreamHelperSpan(): boolean {\n const activeSpan = getActiveSpan();\n return !!activeSpan && streamHelperSpans.has(activeSpan);\n}\n\n/**\n * Whether request options carry the header the SDK's `messages.stream()` helper puts on its internal\n * `create` call. The SDK sent it as `X-Stainless-Helper-Method` up to 0.105 and lowercase since 0.106, and\n * HTTP header names are case-insensitive either way, so match without regard to case. The headers\n * arrive as a plain object; a `Headers` instance is handled for completeness.\n */\nfunction isStreamHelperRequest(headers: unknown): boolean {\n if (!headers || typeof headers !== 'object') {\n return false;\n }\n\n if (typeof (headers as Headers).get === 'function') {\n return (headers as Headers).get(STREAM_HELPER_METHOD_HEADER) === 'stream';\n }\n\n return Object.entries(headers as Record<string, unknown>).some(\n ([name, value]) => name.toLowerCase() === STREAM_HELPER_METHOD_HEADER && value === 'stream',\n );\n}\n\ntype AsyncIterableStream = { [Symbol.asyncIterator]: () => AsyncIterator<unknown> };\ntype MessageStreamEmitter = { on: (...args: unknown[]) => void };\n\nfunction isAsyncIterable(value: unknown): value is AsyncIterableStream {\n return !!value && typeof (value as AsyncIterableStream)[Symbol.asyncIterator] === 'function';\n}\n\nfunction isMessageStream(value: unknown): value is MessageStreamEmitter {\n return !!value && typeof (value as MessageStreamEmitter).on === 'function';\n}\n\ntype ThreadStream = MessageStreamEmitter & { ended?: boolean; controller?: { signal?: AbortSignal } };\n\n/**\n * The streams of threads and tool runners on 1.2+, by the signal they send each `create()` call with. Such a\n * stream parses the response itself, so the `create()` result is never parsed and never ends its span.\n */\nconst threadStreams = new WeakMap<AbortSignal, { stream: ThreadStream; callerSignal: AbortSignal | undefined }>();\n\n/**\n * End the span of a thread stream's `create()` call from the stream once the response arrives. A thread may\n * retry a rejected call, so a failed call ends its own span and only the one that succeeds reads the stream.\n */\nfunction wrapThreadStreamRequest(span: Span, data: AnthropicChannelContext, end: (error?: unknown) => void): boolean {\n const signal = (data.arguments?.[1] as { signal?: AbortSignal } | undefined)?.signal;\n const threadStream = signal && threadStreams.get(signal);\n const request = data.result as { _responseProps?: () => Promise<unknown> } | undefined;\n // A finished stream sends no more requests, so a later call with its signal is the caller's own.\n if (!threadStream || threadStream.stream.ended || typeof request?._responseProps !== 'function') {\n return false;\n }\n const { stream, callerSignal } = threadStream;\n\n const recordOutputs = !!data._sentryRecordOutputs;\n // Not `asResponse()`, which on 1.x also ends the SDK's own span when the user turned its tracing on.\n void request._responseProps().then(\n () => {\n // Only a rejected attempt is retried, so nothing else may claim this stream.\n threadStreams.delete(signal);\n instrumentMessageStream(stream, span, recordOutputs, callerSignal, data._sentryOnSpanEnd);\n },\n error => {\n // An abort is not a failed request. The stream still emits 'end', which sets the status from the caller's signal.\n // The thread emits 'abort' and 'end' only after it awaits `_responseProps()` itself, which is after this handler,\n // so the listeners cannot miss them.\n if (signal.aborted) {\n instrumentMessageStream(stream, span, recordOutputs, callerSignal, data._sentryOnSpanEnd);\n } else {\n end(error);\n }\n },\n );\n return true;\n}\n\n/**\n * Hand span-ending ownership to a streamed result: returns `true` to skip the normal `beforeSpanEnd`,\n * `false` for non-streaming results (which end via `beforeSpanEnd`).\n *\n * - `async-iterable`: patch the `Stream`'s async iterator in place so `instrumentAsyncIterableStream` ends\n * the span when iteration finishes.\n * - `message-stream`: `instrumentMessageStream` attaches `'message'`/`'error'`/`'end'` listeners that end the span.\n */\nfunction wrapStreamResult(span: Span, data: AnthropicChannelContext, stream: StreamMode): boolean {\n const recordOutputs = !!data._sentryRecordOutputs;\n const result = data.result;\n\n if (stream === 'async-iterable' && isAsyncIterable(result)) {\n const iterate = result[Symbol.asyncIterator].bind(result);\n const instrumented = instrumentAsyncIterableStream(\n { [Symbol.asyncIterator]: iterate },\n span,\n recordOutputs,\n data._sentryOnSpanEnd,\n );\n result[Symbol.asyncIterator] = () => instrumented;\n return true;\n }\n\n if (stream === 'message-stream' && isMessageStream(result)) {\n instrumentMessageStream(result, span, recordOutputs, getRequestSignal(data.arguments?.[1]), data._sentryOnSpanEnd);\n return true;\n }\n\n return false;\n}\n\n/**\n * Diagnostics-channel-based Anthropic integration. Subscribes to the `orchestrion:@anthropic-ai/sdk:*`\n * diagnostics_channels injected into the SDK's chat (`messages`/`completions`/beta `messages`) and\n * `messages.stream()` methods, so it requires the Sentry runtime hook or bundler plugin.\n */\nexport const anthropicAIIntegration = defineIntegration(_anthropicAIIntegration);\n"],"mappings":";;;;;;;;;;;;;;;;;AAsBA,MAAM,mBAAmB;AASzB,MAAM,wBAAwB,CAC5B;CAAE,SAAS,SAAS;CAAgB,WAAW;CAAQ,QAAQ;AAAiB,GAChF;CACE,SAAS,SAAS;CAClB,WAAW;CACX,QAAQ;AACV,CACF;AAIA,MAAM,4BAA4B,UAA8B,CAAC,MAAM;CACrE,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GACZ,iCAAiC,QAAQ,wBAAwB,qBAAqB,CAAC,OAAO,CAAC;EACjG;CACF;AACF;AAKA,SAAS,uBAA6B;CACpC,IAAI;;EACF,CAAA,eAAA,QAAQ,IAAA,CAAI,6BAAA,aAAA,2BAA6B;CAC3C,QAAQ,CAER;AACF;AAEA,SAAS,oBAAoB,SAAmC;CAC9D,qBAAqB;CACrB,KAAK,MAAM,EAAE,SAAS,WAAW,YAAY,uBAC3C,yBACEA,eAA2D,OAAO,IAClE,SAAQ,gBAAgB,MAAM,WAAW,SAAS,MAAM,GACxD;EACE,gBAAgB,MAAM,SAAS;GAC7B,IAAI,WAAW,MACb,uBAAuB,MAAM,iBAAiB,KAAK,YAAY,EAAE,CAAC;GAEpE,sBAAsB,MAAM,KAAK,QAA+B,CAAC,CAAC,KAAK,oBAAoB;GAC3F,KAAK,mBAAmB,WAAW,OAAO,EAAE,OAAO,KAAK,MAAM,IAAI,EAAE,UAAU,KAAK,OAAO,CAAC;EAC7F;EAC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mB,YACnF,OAAO;CAET,MAAM,EAAE,QAAQ,iBAAiB;CAEjC,MAAM,gBAAgB,CAAC,CAAC,KAAK;CAExB,QAAQ,eAAe,CAAC,CAAC,WACtB;EAEJ,cAAc,OAAO,MAAM;EAC3B,wBAAwB,QAAQ,MAAM,eAAe,cAAc,KAAK,gBAAgB;CAC1F,IACA,UAAS;EAIP,IAAI,OAAO,SACT,wBAAwB,QAAQ,MAAM,eAAe,cAAc,KAAK,gBAAgB;OAExF,IAAI,KAAK;CAEb,CACF;CACA,OAAO;AACT;;;;;;;;;AAUA,SAAS,iBAAiB,MAAY,MAA+B,QAA6B;CAChG,MAAM,gBAAgB,CAAC,CAAC,KAAK;CAC7B,MAAM,SAAS,KAAK;CAEpB,IAAI,WAAW,oBAAoB,gBAAgB,MAAM,GAAG;EAC1D,MAAM,UAAU,OAAO,OAAO,cAAc,CAAC,KAAK,MAAM;EACxD,MAAM,eAAe,8BACnB,GAAG,OAAO,gBAAgB,QAAQ,GAClC,MACA,eACA,KAAK,gBACP;EACA,OAAO,OAAO,uBAAuB;EACrC,OAAO;CACT;CAEA,IAAI,WAAW,oBAAoB,gBAAgB,MAAM,GAAG;EAC1D,wBAAwB,QAAQ,MAAM,eAAe,iBAAiB,KAAK,YAAY,EAAE,GAAG,KAAK,gBAAgB;EACjH,OAAO;CACT;CAEA,OAAO;AACT;;;;;;AAOA,MAAa,yBAAyB,kBAAkB,uBAAuB"}
1
+ {"version":3,"file":"anthropic.js","names":["diagnosticsChannel.tracingChannel","diagnosticsChannel\n .tracingChannel"],"sources":["../../../src/integrations/anthropic.ts"],"sourcesContent":["import { GEN_AI_REQUEST_MODEL, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn, Span, SpanAttributeValue } from '@sentry/core';\nimport { defineIntegration, getActiveSpan, getClient, hasSpanStreamingEnabled, startInactiveSpan } from '@sentry/core';\nimport { getGenAiSpanOp, getRequestSignal, markCancelledIfAborted, resolveGenAiCallRecording } from '../ai/core/utils';\nimport { wrapApiPromiseResponse } from '../ai/core/apiPromise';\nimport { type GenAiSpanResult, runGenAiSpanEnd, runGenAiSpanStart } from '../ai/core/span-hooks';\nimport { addPrivateRequestAttributes, extractRequestAttributes } from '../ai/anthropic-ai';\nimport { ANTHROPIC_AI_ORIGIN } from '../ai/anthropic-ai/constants';\nimport { addResponseAttributes, getProviderName } from '../ai/anthropic-ai/utils';\nimport { instrumentAsyncIterableStream, instrumentMessageStream } from '../ai/anthropic-ai/streaming';\nimport { instrumentSessionToolRunner, instrumentToolRunner } from '../ai/anthropic-ai/tool-runner';\nimport type { AnthropicAiCallInfo, AnthropicAiOptions, AnthropicAiResponse } from '../ai/anthropic-ai/types';\nimport { shouldSkipAiProviderSpan } from '../ai/pi-ai/providers';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\nimport { anthropicAiModuleNames } from '../orchestrion/config/anthropic-ai';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\n\n// Same name as the OTel integration by design, so the OTel 'Anthropic_AI'\n// integration is deduplicated out of the default set.\nconst INTEGRATION_NAME = 'Anthropic_AI' as const;\n\n// The recording decision is made once, when the span starts, in the caller's async context.\ntype AnthropicChannelContext = OrchestrionChannelContext & {\n _sentryRecordOutputs?: boolean;\n _sentryOnSpanEnd?: (result: GenAiSpanResult<unknown>) => void;\n};\n\n// `stream` determines how the span is ended\nconst INSTRUMENTED_CHANNELS = [\n { channel: CHANNELS.ANTHROPIC_CHAT, operation: 'chat', stream: 'async-iterable' },\n {\n channel: CHANNELS.ANTHROPIC_MESSAGES_STREAM,\n operation: 'chat',\n stream: 'message-stream',\n },\n] as const;\n\ntype StreamMode = (typeof INSTRUMENTED_CHANNELS)[number]['stream'];\n\nconst _anthropicAIIntegration = ((options: AnthropicAiOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, anthropicAiModuleNames, instrumentAnthropic, [options]);\n },\n };\n}) satisfies IntegrationFn;\n\n// Since 0.134 `@anthropic-ai/sdk` traces itself through the global OTel tracer provider, which duplicates our\n// spans. Only turned off once our channels subscribe, so an app we do not instrument keeps the SDK's spans.\n// A value the user set wins.\nfunction disableNativeTracing(): void {\n try {\n process.env.ANTHROPIC_OPEN_TELEMETRY ??= 'false';\n } catch {\n // `process` is absent (edge runtimes) or env access is gated (Deno without `--allow-env`).\n }\n}\n\nfunction instrumentAnthropic(options: AnthropicAiOptions): void {\n disableNativeTracing();\n for (const { channel, operation, stream } of INSTRUMENTED_CHANNELS) {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<AnthropicChannelContext>(channel),\n data => createGenAiSpan(data, operation, options, stream),\n {\n beforeSpanEnd: (span, data) => {\n if ('error' in data) {\n markCancelledIfAborted(span, getRequestSignal(data.arguments?.[1]));\n }\n addResponseAttributes(span, data.result as AnthropicAiResponse, !!data._sentryRecordOutputs);\n data._sentryOnSpanEnd?.('error' in data ? { error: data.error } : { response: data.result });\n },\n deferSpanEnd: ({ span, data, end }) =>\n wrapThreadStreamRequest(span, data, end) ||\n wrapApiPromiseResponse(\n data.result,\n response => {\n data.result = response;\n if (!wrapStreamResult(span, data, stream)) {\n end();\n }\n },\n end,\n ) ||\n wrapStreamResult(span, data, stream),\n },\n );\n }\n\n diagnosticsChannel\n .tracingChannel<OrchestrionChannelContext>(CHANNELS.ANTHROPIC_TOOL_RUNNER)\n .end.subscribe(message => {\n instrumentToolRunner((message as OrchestrionChannelContext).result, options);\n });\n diagnosticsChannel\n .tracingChannel<OrchestrionChannelContext>(CHANNELS.ANTHROPIC_SESSION_TOOL_RUNNER)\n .end.subscribe(message => {\n instrumentSessionToolRunner((message as OrchestrionChannelContext).self, options);\n });\n // On `start`, because `_start()` sends the first request before it returns.\n diagnosticsChannel\n .tracingChannel<OrchestrionChannelContext>(CHANNELS.ANTHROPIC_THREAD_STREAM)\n .start.subscribe(message => {\n const data = message as OrchestrionChannelContext;\n const stream = data.self as ThreadStream | undefined;\n if (isMessageStream(stream) && stream.controller?.signal) {\n // `_start(create, params, options)`: each `create()` gets only the stream's own signal, which doesn't carry\n // the reason a caller's signal fired with.\n threadStreams.set(stream.controller.signal, { stream, callerSignal: getRequestSignal(data.arguments?.[2]) });\n }\n });\n}\n\n/**\n * Build the span for an instrumented call.\n * Returning `undefined` opts the payload out so no span is opened.\n */\nfunction createGenAiSpan(\n data: AnthropicChannelContext,\n operation: 'chat',\n options: AnthropicAiOptions,\n stream: StreamMode,\n): Span | undefined {\n const args = data.arguments ?? [];\n\n if (shouldSkipAiProviderSpan(INTEGRATION_NAME)) {\n return undefined;\n }\n\n // `messages.stream()` internally calls the instrumented `messages.create({ stream: true })` tagged with\n // a `stream` helper-method header. The messages-stream channel already covers it, so skip the nested\n // create to avoid a duplicate span. Only the non-beta helper is on that channel, though:\n // `beta.messages.stream()` and the streaming tool runner send the same header with no span covering\n // them, so the header alone is not enough. Skip only while a stream-helper span of ours is active.\n const requestOptions = args[1] as { headers?: unknown } | undefined;\n if (isStreamHelperRequest(requestOptions?.headers) && isInsideStreamHelperSpan()) {\n return undefined;\n }\n\n const params = typeof args[0] === 'object' && args[0] !== null ? (args[0] as Record<string, unknown>) : undefined;\n\n const call: AnthropicAiCallInfo = { operation, request: params };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n data._sentryRecordOutputs = recordOutputs;\n\n const attributes = extractRequestAttributes(args, operation, recordInputs, getProviderName(data.self));\n const model = (attributes[GEN_AI_REQUEST_MODEL] as string) || 'unknown';\n attributes[SENTRY_ORIGIN] = ANTHROPIC_AI_ORIGIN;\n const client = getClient();\n\n const span = startInactiveSpan({\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name: model !== 'unknown' || !(client && hasSpanStreamingEnabled(client)) ? `${operation} ${model}` : operation,\n op: getGenAiSpanOp(operation),\n attributes: attributes as Record<string, SpanAttributeValue>,\n });\n\n if (recordInputs && params) {\n addPrivateRequestAttributes(span, params);\n }\n\n runGenAiSpanStart(options, span, call);\n data._sentryOnSpanEnd = result => runGenAiSpanEnd(options, span, call, result);\n\n if (stream === 'message-stream') {\n streamHelperSpans.add(span);\n }\n\n return span;\n}\n\nconst STREAM_HELPER_METHOD_HEADER = 'x-stainless-helper-method';\n\n/** The spans opened for the messages-stream channel, i.e. for `messages.stream()` calls. */\nconst streamHelperSpans = new WeakSet<Span>();\n\n/**\n * Whether the active span is one this integration opened for `messages.stream()`. The helper's\n * internal `create` runs inside that span, so this is what tells it apart from the beta helper and\n * the tool runner, which send the same header but are not on the messages-stream channel.\n */\nfunction isInsideStreamHelperSpan(): boolean {\n const activeSpan = getActiveSpan();\n return !!activeSpan && streamHelperSpans.has(activeSpan);\n}\n\n/**\n * Whether request options carry the header the SDK's `messages.stream()` helper puts on its internal\n * `create` call. The SDK sent it as `X-Stainless-Helper-Method` up to 0.105 and lowercase since 0.106, and\n * HTTP header names are case-insensitive either way, so match without regard to case. The headers\n * arrive as a plain object; a `Headers` instance is handled for completeness.\n */\nfunction isStreamHelperRequest(headers: unknown): boolean {\n if (!headers || typeof headers !== 'object') {\n return false;\n }\n\n if (typeof (headers as Headers).get === 'function') {\n return (headers as Headers).get(STREAM_HELPER_METHOD_HEADER) === 'stream';\n }\n\n return Object.entries(headers as Record<string, unknown>).some(\n ([name, value]) => name.toLowerCase() === STREAM_HELPER_METHOD_HEADER && value === 'stream',\n );\n}\n\ntype AsyncIterableStream = { [Symbol.asyncIterator]: () => AsyncIterator<unknown> };\ntype MessageStreamEmitter = { on: (...args: unknown[]) => void };\n\nfunction isAsyncIterable(value: unknown): value is AsyncIterableStream {\n return !!value && typeof (value as AsyncIterableStream)[Symbol.asyncIterator] === 'function';\n}\n\nfunction isMessageStream(value: unknown): value is MessageStreamEmitter {\n return !!value && typeof (value as MessageStreamEmitter).on === 'function';\n}\n\ntype ThreadStream = MessageStreamEmitter & { ended?: boolean; controller?: { signal?: AbortSignal } };\n\n/**\n * The streams of threads and tool runners on 1.2+, by the signal they send each `create()` call with. Such a\n * stream parses the response itself, so the `create()` result is never parsed and never ends its span.\n */\nconst threadStreams = new WeakMap<AbortSignal, { stream: ThreadStream; callerSignal: AbortSignal | undefined }>();\n\n/**\n * End the span of a thread stream's `create()` call from the stream once the response arrives. A thread may\n * retry a rejected call, so a failed call ends its own span and only the one that succeeds reads the stream.\n */\nfunction wrapThreadStreamRequest(span: Span, data: AnthropicChannelContext, end: (error?: unknown) => void): boolean {\n const signal = (data.arguments?.[1] as { signal?: AbortSignal } | undefined)?.signal;\n const threadStream = signal && threadStreams.get(signal);\n const request = data.result as { _responseProps?: () => Promise<unknown> } | undefined;\n // A finished stream sends no more requests, so a later call with its signal is the caller's own.\n if (!threadStream || threadStream.stream.ended || typeof request?._responseProps !== 'function') {\n return false;\n }\n const { stream, callerSignal } = threadStream;\n\n const recordOutputs = !!data._sentryRecordOutputs;\n // Not `asResponse()`, which on 1.x also ends the SDK's own span when the user turned its tracing on.\n void request._responseProps().then(\n () => {\n // Only a rejected attempt is retried, so nothing else may claim this stream.\n threadStreams.delete(signal);\n instrumentMessageStream(stream, span, recordOutputs, callerSignal, data._sentryOnSpanEnd);\n },\n error => {\n // An abort is not a failed request. The stream still emits 'end', which sets the status from the caller's signal.\n // The thread emits 'abort' and 'end' only after it awaits `_responseProps()` itself, which is after this handler,\n // so the listeners cannot miss them.\n if (signal.aborted) {\n instrumentMessageStream(stream, span, recordOutputs, callerSignal, data._sentryOnSpanEnd);\n } else {\n end(error);\n }\n },\n );\n return true;\n}\n\n/**\n * Hand span-ending ownership to a streamed result: returns `true` to skip the normal `beforeSpanEnd`,\n * `false` for non-streaming results (which end via `beforeSpanEnd`).\n *\n * - `async-iterable`: patch the `Stream`'s async iterator in place so `instrumentAsyncIterableStream` ends\n * the span when iteration finishes.\n * - `message-stream`: `instrumentMessageStream` attaches `'message'`/`'error'`/`'end'` listeners that end the span.\n */\nfunction wrapStreamResult(span: Span, data: AnthropicChannelContext, stream: StreamMode): boolean {\n const recordOutputs = !!data._sentryRecordOutputs;\n const result = data.result;\n\n if (stream === 'async-iterable' && isAsyncIterable(result)) {\n const iterate = result[Symbol.asyncIterator].bind(result);\n const instrumented = instrumentAsyncIterableStream(\n { [Symbol.asyncIterator]: iterate },\n span,\n recordOutputs,\n data._sentryOnSpanEnd,\n );\n result[Symbol.asyncIterator] = () => instrumented;\n return true;\n }\n\n if (stream === 'message-stream' && isMessageStream(result)) {\n instrumentMessageStream(result, span, recordOutputs, getRequestSignal(data.arguments?.[1]), data._sentryOnSpanEnd);\n return true;\n }\n\n return false;\n}\n\n/**\n * Diagnostics-channel-based Anthropic integration. Subscribes to the `orchestrion:@anthropic-ai/sdk:*`\n * diagnostics_channels injected into the SDK's chat (`messages`/`completions`/beta `messages`) and\n * `messages.stream()` methods, so it requires the Sentry runtime hook or bundler plugin.\n */\nexport const anthropicAIIntegration = defineIntegration(_anthropicAIIntegration);\n"],"mappings":";;;;;;;;;;;;;;;;;AAsBA,MAAM,mBAAmB;AASzB,MAAM,wBAAwB,CAC5B;CAAE,SAAS,SAAS;CAAgB,WAAW;CAAQ,QAAQ;AAAiB,GAChF;CACE,SAAS,SAAS;CAClB,WAAW;CACX,QAAQ;AACV,CACF;AAIA,MAAM,4BAA4B,UAA8B,CAAC,MAAM;CACrE,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GACZ,iCAAiC,QAAQ,wBAAwB,qBAAqB,CAAC,OAAO,CAAC;EACjG;CACF;AACF;AAKA,SAAS,uBAA6B;CACpC,IAAI;;EACF,CAAA,eAAA,QAAQ,IAAA,CAAI,6BAAA,aAAA,2BAA6B;CAC3C,QAAQ,CAER;AACF;AAEA,SAAS,oBAAoB,SAAmC;CAC9D,qBAAqB;CACrB,KAAK,MAAM,EAAE,SAAS,WAAW,YAAY,uBAC3C,yBACEA,eAA2D,OAAO,IAClE,SAAQ,gBAA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ntegration, startInactiveSpan } from "@sentry/core";
3
+ import { AWS_REQUEST_EXTENDED_ID, CLOUD_REGION, HTTP_RESPONSE_STATUS_CODE, SENTRY_KIND, SENTRY_ORIGIN, _AWS_REQUEST_ID } from "@sentry/conventions/attributes";
4
+ import { RPC } from "@sentry/conventions/op";
2
5
  import { CHANNELS } from "../../orchestrion/channels.js";
3
6
  import { awsSdkModuleNames } from "../../orchestrion/config/aws-sdk.js";
4
7
  import { invokeOrchestrionInstrumentation } from "../../orchestrion/instrumentation.js";
@@ -7,9 +10,6 @@ import { AWS_SDK_ORIGIN_INTEGRATION_NAME } from "./constants.js";
7
10
  import { ServicesExtensions } from "./services/ServicesExtensions.js";
8
11
  import "./services/index.js";
9
12
  import { extractAttributesFromNormalizedRequest, normalizeV3Request, removeSuffixFromStringIfExists } from "./utils.js";
10
- import { AWS_REQUEST_EXTENDED_ID, CLOUD_REGION, HTTP_RESPONSE_STATUS_CODE, SENTRY_KIND, SENTRY_ORIGIN, _AWS_REQUEST_ID } from "@sentry/conventions/attributes";
11
- import { defineIntegration, startInactiveSpan } from "@sentry/core";
12
- import { RPC } from "@sentry/conventions/op";
13
13
  // src/integrations/aws-sdk/index.ts
14
14
  const INTEGRATION_NAME = "Aws";
15
15
  function setMetadataAttributes(span, metadata) {
@@ -1,5 +1,5 @@
1
- import { DEBUG_BUILD } from "../../../debug-build.js";
2
1
  import { debug, uniq } from "@sentry/core";
2
+ import { DEBUG_BUILD } from "../../../debug-build.js";
3
3
  const SENTRY_TRACE_HEADER = "sentry-trace";
4
4
  const BAGGAGE_HEADER = "baggage";
5
5
  const PROPAGATION_FIELDS = [SENTRY_TRACE_HEADER, BAGGAGE_HEADER];
@@ -1,6 +1,6 @@
1
- import { getMessagesAttributes, messagesFromParams } from "../../../ai/anthropic-ai/utils.js";
2
- import { GEN_AI_INPUT_MESSAGES, GEN_AI_OUTPUT_MESSAGES, GEN_AI_SYSTEM_INSTRUCTIONS, GEN_AI_TOOL_DEFINITIONS } from "@sentry/conventions/attributes";
3
1
  import { isObjectLike, stringify } from "@sentry/core";
2
+ import { GEN_AI_INPUT_MESSAGES, GEN_AI_OUTPUT_MESSAGES, GEN_AI_SYSTEM_INSTRUCTIONS, GEN_AI_TOOL_DEFINITIONS } from "@sentry/conventions/attributes";
3
+ import { getMessagesAttributes, messagesFromParams } from "../../../ai/anthropic-ai/utils.js";
4
4
  // src/integrations/aws-sdk/services/bedrock-runtime-content.ts
5
5
  /**
6
6
  * Translate Converse `ContentBlock`s (also used by Amazon Nova `InvokeModel` bodies) and the Anthropic Messages
@@ -1,12 +1,12 @@
1
+ import { debug } from "@sentry/core";
2
+ import { GEN_AI_OPERATION_NAME, GEN_AI_PROVIDER_NAME, GEN_AI_REQUEST_MAX_TOKENS, GEN_AI_REQUEST_MODEL, GEN_AI_REQUEST_STOP_SEQUENCES, GEN_AI_REQUEST_TEMPERATURE, GEN_AI_REQUEST_TOP_P, GEN_AI_RESPONSE_FINISH_REASONS, GEN_AI_USAGE_INPUT_TOKENS, GEN_AI_USAGE_OUTPUT_TOKENS } from "@sentry/conventions/attributes";
3
+ import { GEN_AI_CHAT, GEN_AI_GENERATE_CONTENT } from "@sentry/conventions/op";
1
4
  import { runGenAiSpanEnd, runGenAiSpanStart } from "../../../ai/core/span-hooks.js";
2
5
  import { endStreamSpan, getErrorStatus, getTokenUsageAttributes, resolveGenAiCallRecording } from "../../../ai/core/utils.js";
3
6
  import { isInsidePiAiSpan } from "../../../ai/pi-ai/providers.js";
4
7
  import { DEBUG_BUILD } from "../../../debug-build.js";
5
8
  import { GEN_AI_OPERATION_NAME_VALUE_CHAT, GEN_AI_OPERATION_NAME_VALUE_GENERATE_CONTENT, GEN_AI_SYSTEM_VALUE_AWS_BEDROCK } from "../constants.js";
6
9
  import { appendStreamPart, contentBlocksToParts, getClaudeInputAttributes, getConverseInputAttributes, getPromptInputAttributes, setOutputMessages, startStreamToolCall } from "./bedrock-runtime-content.js";
7
- import { GEN_AI_OPERATION_NAME, GEN_AI_PROVIDER_NAME, GEN_AI_REQUEST_MAX_TOKENS, GEN_AI_REQUEST_MODEL, GEN_AI_REQUEST_STOP_SEQUENCES, GEN_AI_REQUEST_TEMPERATURE, GEN_AI_REQUEST_TOP_P, GEN_AI_RESPONSE_FINISH_REASONS, GEN_AI_USAGE_INPUT_TOKENS, GEN_AI_USAGE_OUTPUT_TOKENS } from "@sentry/conventions/attributes";
8
- import { debug } from "@sentry/core";
9
- import { GEN_AI_CHAT, GEN_AI_GENERATE_CONTENT } from "@sentry/conventions/op";
10
10
  // src/integrations/aws-sdk/services/bedrock-runtime.ts
11
11
  const textDecoder = new TextDecoder();
12
12
  var BedrockRuntimeServiceExtension = class {
@@ -1,6 +1,6 @@
1
- import { DB_SYSTEM_VALUE_DYNAMODB } from "../constants.js";
2
1
  import { AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS, AWS_DYNAMODB_CONSISTENT_READ, AWS_DYNAMODB_CONSUMED_CAPACITY, AWS_DYNAMODB_COUNT, AWS_DYNAMODB_EXCLUSIVE_START_TABLE, AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES, AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES, AWS_DYNAMODB_INDEX_NAME, AWS_DYNAMODB_ITEM_COLLECTION_METRICS, AWS_DYNAMODB_LIMIT, AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES, AWS_DYNAMODB_PROJECTION, AWS_DYNAMODB_PROVISIONED_READ_CAPACITY, AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY, AWS_DYNAMODB_SCANNED_COUNT, AWS_DYNAMODB_SCAN_FORWARD, AWS_DYNAMODB_SEGMENT, AWS_DYNAMODB_SELECT, AWS_DYNAMODB_TABLE_COUNT, AWS_DYNAMODB_TABLE_NAMES, AWS_DYNAMODB_TOTAL_SEGMENTS, DB_NAMESPACE, DB_OPERATION_NAME, DB_SYSTEM_NAME } from "@sentry/conventions/attributes";
3
2
  import { DB } from "@sentry/conventions/op";
3
+ import { DB_SYSTEM_VALUE_DYNAMODB } from "../constants.js";
4
4
  // src/integrations/aws-sdk/services/dynamodb.ts
5
5
  function toArray(values) {
6
6
  return Array.isArray(values) ? values : [values];
@@ -1,6 +1,6 @@
1
- import { DEBUG_BUILD } from "../../../debug-build.js";
2
- import { FAAS_INVOCATION_ID, FAAS_INVOKED_NAME, FAAS_INVOKED_PROVIDER, FAAS_INVOKED_REGION } from "@sentry/conventions/attributes";
3
1
  import { debug, getTraceData } from "@sentry/core";
2
+ import { FAAS_INVOCATION_ID, FAAS_INVOKED_NAME, FAAS_INVOKED_PROVIDER, FAAS_INVOKED_REGION } from "@sentry/conventions/attributes";
3
+ import { DEBUG_BUILD } from "../../../debug-build.js";
4
4
  // src/integrations/aws-sdk/services/lambda.ts
5
5
  const INVOKE_COMMAND = "Invoke";
6
6
  var LambdaServiceExtension = class {
@@ -1,8 +1,8 @@
1
- import { MESSAGING_DESTINATION_KIND_VALUE_TOPIC } from "../constants.js";
2
- import { injectPropagationContext } from "./MessageAttributes.js";
3
- import { AWS_SNS_TOPIC_ARN, MESSAGING_DESTINATION, MESSAGING_DESTINATION_KIND, MESSAGING_DESTINATION_NAME, MESSAGING_OPERATION_TYPE, MESSAGING_SYSTEM, SENTRY_KIND } from "@sentry/conventions/attributes";
4
1
  import { getClient, getTraceData, hasSpanStreamingEnabled } from "@sentry/core";
2
+ import { AWS_SNS_TOPIC_ARN, MESSAGING_DESTINATION, MESSAGING_DESTINATION_KIND, MESSAGING_DESTINATION_NAME, MESSAGING_OPERATION_TYPE, MESSAGING_SYSTEM, SENTRY_KIND } from "@sentry/conventions/attributes";
5
3
  import { QUEUE_PUBLISH } from "@sentry/conventions/op";
4
+ import { MESSAGING_DESTINATION_KIND_VALUE_TOPIC } from "../constants.js";
5
+ import { injectPropagationContext } from "./MessageAttributes.js";
6
6
  // src/integrations/aws-sdk/services/sns.ts
7
7
  /** Stands in for a destination the command does not name. */
8
8
  const UNKNOWN_DESTINATION = "unknown";
@@ -1,7 +1,7 @@
1
- import { addPropagationFieldsToAttributeNames, extractPropagationHeaders, injectPropagationContext } from "./MessageAttributes.js";
2
- import { MESSAGING_BATCH_MESSAGE_COUNT, MESSAGING_DESTINATION_NAME, MESSAGING_MESSAGE_ID, MESSAGING_OPERATION_TYPE, MESSAGING_SYSTEM, SENTRY_KIND, URL_FULL } from "@sentry/conventions/attributes";
3
1
  import { getClient, getTraceData, hasSpanStreamingEnabled, propagationContextFromHeaders } from "@sentry/core";
2
+ import { MESSAGING_BATCH_MESSAGE_COUNT, MESSAGING_DESTINATION_NAME, MESSAGING_MESSAGE_ID, MESSAGING_OPERATION_TYPE, MESSAGING_SYSTEM, SENTRY_KIND, URL_FULL } from "@sentry/conventions/attributes";
4
3
  import { QUEUE_PUBLISH, QUEUE_RECEIVE } from "@sentry/conventions/op";
4
+ import { addPropagationFieldsToAttributeNames, extractPropagationHeaders, injectPropagationContext } from "./MessageAttributes.js";
5
5
  // src/integrations/aws-sdk/services/sqs.ts
6
6
  var SqsServiceExtension = class {
7
7
  requestPreSpanHook(request) {
@@ -1,7 +1,7 @@
1
- import { toMessagingKey, toSentryAttributes } from "./span.js";
2
1
  import { MESSAGING_OPERATION_NAME, MESSAGING_SYSTEM } from "@sentry/conventions/attributes";
3
- import { metrics } from "@sentry/core";
4
2
  import { MESSAGING_PROCESS_DURATION } from "@sentry/conventions/metrics";
3
+ import { metrics } from "@sentry/core";
4
+ import { toMessagingKey, toSentryAttributes } from "./span.js";
5
5
  // src/integrations/bullmq/meter.ts
6
6
  function toMetricAttributes(attributes) {
7
7
  if (!attributes) return;
@@ -1,7 +1,7 @@
1
- import { SentryBullMQSpan, toSentryAttributes } from "./span.js";
2
1
  import { MESSAGING_SYSTEM, SENTRY_LINK_TYPE, SENTRY_OP, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
3
- import { getCurrentScope, startInactiveSpan, startNewTrace } from "@sentry/core";
4
2
  import { QUEUE, QUEUE_PROCESS, QUEUE_PUBLISH } from "@sentry/conventions/op";
3
+ import { getCurrentScope, startInactiveSpan, startNewTrace } from "@sentry/core";
4
+ import { SentryBullMQSpan, toSentryAttributes } from "./span.js";
5
5
  // src/integrations/bullmq/tracer.ts
6
6
  const PRODUCER_OPERATIONS = /* @__PURE__ */ new Set([
7
7
  "add",
@@ -1,13 +1,13 @@
1
1
  import { tracingChannel } from "../utils/diagnosticsChannel.js";
2
+ import { DB_COLLECTION_NAME, DB_NAMESPACE, DB_OPERATION_NAME, DB_QUERY_SUMMARY, DB_SYSTEM_NAME, DB_USER, SENTRY_KIND, SENTRY_OP, SENTRY_ORIGIN, SERVER_ADDRESS, SERVER_PORT } from "@sentry/conventions/attributes";
3
+ import { DB } from "@sentry/conventions/op";
4
+ import { defineIntegration, startInactiveSpan } from "@sentry/core";
2
5
  import { CHANNELS } from "../orchestrion/channels.js";
3
6
  import { clickhouseModuleNames } from "../orchestrion/config/clickhouse.js";
4
7
  import { invokeOrchestrionInstrumentation } from "../orchestrion/instrumentation.js";
5
8
  import { bindTracingChannelToSpan } from "../tracing-channel.js";
6
9
  import { getLowCardinalitySqlSpanName, getSqlQueryAttributes } from "../utils/sql.js";
7
10
  import { CLICKHOUSE_SQL_RULES } from "./clickhouse-sql.js";
8
- import { DB_COLLECTION_NAME, DB_NAMESPACE, DB_OPERATION_NAME, DB_QUERY_SUMMARY, DB_SYSTEM_NAME, DB_USER, SENTRY_KIND, SENTRY_OP, SENTRY_ORIGIN, SERVER_ADDRESS, SERVER_PORT } from "@sentry/conventions/attributes";
9
- import { defineIntegration, startInactiveSpan } from "@sentry/core";
10
- import { DB } from "@sentry/conventions/op";
11
11
  // src/integrations/clickhouse.ts
12
12
  const INTEGRATION_NAME = "ClickHouse";
13
13
  const ORIGIN = "auto.db.clickhouse";
@@ -1,8 +1,8 @@
1
+ import { defineIntegration } from "@sentry/core";
1
2
  import { CHANNELS } from "../orchestrion/channels.js";
2
3
  import { cronModuleNames } from "../orchestrion/config/cron.js";
3
4
  import { invokeOrchestrionInstrumentation } from "../orchestrion/instrumentation.js";
4
5
  import { cronExpressionToMonitorConfig, shouldMonitorJob, subscribeToJobCreation, subscribeToScheduleChange, updateMonitorConfig, wrapScheduledJob } from "../utils/cronMonitoring.js";
5
- import { defineIntegration } from "@sentry/core";
6
6
  // src/integrations/cron.ts
7
7
  const INTEGRATION_NAME = "CronJob";
8
8
  const _cronJobIntegration = ((options = {}) => {
@@ -1,10 +1,10 @@
1
1
  import { tracingChannel } from "../utils/diagnosticsChannel.js";
2
+ import { CACHE_KEY, CACHE_OPERATION, DB_COLLECTION_NAME, DB_OPERATION_NAME, SENTRY_KIND, SENTRY_OP, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
3
+ import { CACHE_GET, CACHE_PUT, CACHE_REMOVE } from "@sentry/conventions/op";
4
+ import { CACHE_OPERATION_NAMES, debug, defineIntegration, getClient, hasSpanStreamingEnabled, startInactiveSpan, startSpan, waitForTracingChannelBinding } from "@sentry/core";
2
5
  import { DEBUG_BUILD } from "../debug-build.js";
3
6
  import { CHANNELS } from "../orchestrion/channels.js";
4
7
  import { bindTracingChannelToSpan } from "../tracing-channel.js";
5
- import { CACHE_KEY, CACHE_OPERATION, DB_COLLECTION_NAME, DB_OPERATION_NAME, SENTRY_KIND, SENTRY_OP, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
6
- import { CACHE_OPERATION_NAMES, debug, defineIntegration, getClient, hasSpanStreamingEnabled, startInactiveSpan, startSpan, waitForTracingChannelBinding } from "@sentry/core";
7
- import { CACHE_GET, CACHE_PUT, CACHE_REMOVE } from "@sentry/conventions/op";
8
8
  // src/integrations/dataloader.ts
9
9
  const INTEGRATION_NAME = "Dataloader";
10
10
  const MODULE_NAME = "dataloader";
@@ -1,6 +1,6 @@
1
+ import { captureException, getIsolationScope, httpRequestToRequestData } from "@sentry/core";
1
2
  import { isExpressErrorHandled } from "./error-handled.js";
2
3
  import { defaultShouldHandleError } from "./utils.js";
3
- import { captureException, getIsolationScope, httpRequestToRequestData } from "@sentry/core";
4
4
  // src/integrations/express/error-handler.ts
5
5
  /**
6
6
  * Set request data on the isolation scope so a captured error carries request context. Mirrors the
@@ -1,8 +1,8 @@
1
1
  import { tracingChannel } from "../../utils/diagnosticsChannel.js";
2
+ import { defineIntegration } from "@sentry/core";
2
3
  import { expressModuleNames } from "../../orchestrion/config/express.js";
3
4
  import { invokeOrchestrionInstrumentation } from "../../orchestrion/instrumentation.js";
4
5
  import { instrumentExpress } from "./instrumentation.js";
5
- import { defineIntegration } from "@sentry/core";
6
6
  // src/integrations/express/index.ts
7
7
  const INTEGRATION_NAME = "Express";
8
8
  const _expressIntegration = ((options = {}) => {
@@ -1,3 +1,6 @@
1
+ import { HTTP_ROUTE, SENTRY_OP, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
2
+ import { HANDLER, MIDDLEWARE, ROUTER } from "@sentry/conventions/op";
3
+ import { REQUEST_HANDLER_SPAN_NAME_FALLBACK, ROUTER_SPAN_NAME_FALLBACK, SPAN_STATUS_ERROR, captureException, debug, getActiveSpan, getClient, getDefaultIsolationScope, getIsolationScope, hasSpanStreamingEnabled, startInactiveSpan, stringMatchesSomePattern, withActiveSpan } from "@sentry/core";
1
4
  import { DEBUG_BUILD } from "../../debug-build.js";
2
5
  import { CHANNELS } from "../../orchestrion/channels.js";
3
6
  import { bindTracingChannelToSpan } from "../../tracing-channel.js";
@@ -5,9 +8,6 @@ import { getActualMatchedRoute, getConstructedRoute, getLayerPath, getLayerRegis
5
8
  import { defaultShouldHandleError } from "./utils.js";
6
9
  import { isExpressErrorHandled, markExpressErrorHandled } from "./error-handled.js";
7
10
  import { setHttpServerSpanRouteAttribute } from "../../utils/setHttpServerSpanRouteAttribute.js";
8
- import { HTTP_ROUTE, SENTRY_OP, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
9
- import { REQUEST_HANDLER_SPAN_NAME_FALLBACK, ROUTER_SPAN_NAME_FALLBACK, SPAN_STATUS_ERROR, captureException, debug, getActiveSpan, getClient, getDefaultIsolationScope, getIsolationScope, hasSpanStreamingEnabled, startInactiveSpan, stringMatchesSomePattern, withActiveSpan } from "@sentry/core";
10
- import { HANDLER, MIDDLEWARE, ROUTER } from "@sentry/conventions/op";
11
11
  // src/integrations/express/instrumentation.ts
12
12
  const ORIGIN = "auto.http.express";
13
13
  const ATTR_EXPRESS_NAME = "express.name";
@@ -1,6 +1,6 @@
1
1
  import { subscribe } from "../../utils/diagnosticsChannel.js";
2
- import { INTEGRATION_NAME, defaultShouldHandleError } from "./utils.js";
3
2
  import { addNonEnumerableProperty, captureException, getClient } from "@sentry/core";
3
+ import { INTEGRATION_NAME, defaultShouldHandleError } from "./utils.js";
4
4
  // src/integrations/fastify/errors.ts
5
5
  const kErrorCaptured = Symbol("sentry.fastifyErrorCaptured");
6
6
  function getFastifyIntegration() {
@@ -1,7 +1,7 @@
1
+ import { defineIntegration } from "@sentry/core";
1
2
  import { instrumentFastify } from "./instrumentation.js";
2
3
  import { INTEGRATION_NAME, defaultShouldHandleError } from "./utils.js";
3
4
  import { subscribeToFastifyErrorChannel } from "./errors.js";
4
- import { defineIntegration } from "@sentry/core";
5
5
  // src/integrations/fastify/index.ts
6
6
  const _fastifyIntegration = (({ shouldHandleError } = {}) => {
7
7
  let _shouldHandleError;
@@ -1,9 +1,9 @@
1
1
  import { subscribe } from "../../utils/diagnosticsChannel.js";
2
- import { setHttpServerSpanRouteAttribute } from "../../utils/setHttpServerSpanRouteAttribute.js";
3
- import { handleFastifyError } from "./errors.js";
4
2
  import { HTTP_REQUEST_METHOD, HTTP_RESPONSE_STATUS_CODE, HTTP_ROUTE, SENTRY_OP, SENTRY_ORIGIN, URL_PATH } from "@sentry/conventions/attributes";
5
- import { REQUEST_HANDLER_SPAN_NAME_FALLBACK, SPAN_STATUS_ERROR, getActiveSpan, getClient, getIsolationScope, hasSpanStreamingEnabled, isObjectLike, spanIsSampled, startInactiveSpan, startSpan, withActiveSpan } from "@sentry/core";
6
3
  import { HANDLER, MIDDLEWARE } from "@sentry/conventions/op";
4
+ import { REQUEST_HANDLER_SPAN_NAME_FALLBACK, SPAN_STATUS_ERROR, getActiveSpan, getClient, getIsolationScope, hasSpanStreamingEnabled, isObjectLike, spanIsSampled, startInactiveSpan, startSpan, withActiveSpan } from "@sentry/core";
5
+ import { setHttpServerSpanRouteAttribute } from "../../utils/setHttpServerSpanRouteAttribute.js";
6
+ import { handleFastifyError } from "./errors.js";
7
7
  // src/integrations/fastify/instrumentation.ts
8
8
  const ORIGIN = "auto.http.fastify";
9
9
  const FASTIFY_HOOKS = [
@@ -97,6 +97,10 @@ function onRequest(request, _reply, hookDone) {
97
97
  const routeName = getRequestRouteUrl(request);
98
98
  const method = request.method || "GET";
99
99
  getIsolationScope().setTransactionName(`${method} ${routeName}`);
100
+ if (!getActiveSpan()) {
101
+ hookDone();
102
+ return;
103
+ }
100
104
  const attributes = {
101
105
  [SENTRY_ORIGIN]: ORIGIN,
102
106
  [SENTRY_OP]: HANDLER,
@@ -195,7 +199,7 @@ function handlerWrapper(handler, hookName, spanAttributes = {}) {
195
199
  if (!request) return handler.call(this, ...args);
196
200
  const parentSpan = request[kRequestSpan] ?? void 0;
197
201
  const effectiveParentSpan = parentSpan ?? getActiveSpan();
198
- if (effectiveParentSpan && !spanIsSampled(effectiveParentSpan)) return handler.call(this, ...args);
202
+ if (!effectiveParentSpan || !spanIsSampled(effectiveParentSpan)) return handler.call(this, ...args);
199
203
  const handlerName = handler.name?.length > 0 ? handler.name : this.pluginName ?? ANONYMOUS_FUNCTION_NAME;
200
204
  const hookType = spanAttributes[ATTRIBUTE_FASTIFY_TYPE];
201
205
  const op = hookType === HOOK_TYPE_INSTANCE ? MIDDLEWARE : hookType === HOOK_TYPE_HANDLER ? HANDLER : void 0;