@sentry/core 10.47.0 → 10.49.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 (413) hide show
  1. package/build/cjs/attributes.js +43 -0
  2. package/build/cjs/attributes.js.map +1 -1
  3. package/build/cjs/client.js +13 -6
  4. package/build/cjs/client.js.map +1 -1
  5. package/build/cjs/envelope.js +4 -3
  6. package/build/cjs/envelope.js.map +1 -1
  7. package/build/cjs/fetch.js +36 -17
  8. package/build/cjs/fetch.js.map +1 -1
  9. package/build/cjs/index.js +53 -18
  10. package/build/cjs/index.js.map +1 -1
  11. package/build/cjs/integration.js +6 -0
  12. package/build/cjs/integration.js.map +1 -1
  13. package/build/cjs/integrations/conversationId.js +11 -0
  14. package/build/cjs/integrations/conversationId.js.map +1 -1
  15. package/build/cjs/integrations/express/index.js +243 -0
  16. package/build/cjs/integrations/express/index.js.map +1 -0
  17. package/build/cjs/integrations/express/patch-layer.js +257 -0
  18. package/build/cjs/integrations/express/patch-layer.js.map +1 -0
  19. package/build/cjs/integrations/express/request-layer-store.js +25 -0
  20. package/build/cjs/integrations/express/request-layer-store.js.map +1 -0
  21. package/build/cjs/integrations/express/set-sdk-processing-metadata.js +17 -0
  22. package/build/cjs/integrations/express/set-sdk-processing-metadata.js.map +1 -0
  23. package/build/cjs/integrations/express/types.js +17 -0
  24. package/build/cjs/integrations/express/types.js.map +1 -0
  25. package/build/cjs/integrations/express/utils.js +238 -0
  26. package/build/cjs/integrations/express/utils.js.map +1 -0
  27. package/build/cjs/integrations/mcp-server/correlation.js +5 -1
  28. package/build/cjs/integrations/mcp-server/correlation.js.map +1 -1
  29. package/build/cjs/integrations/mcp-server/handlers.js +18 -10
  30. package/build/cjs/integrations/mcp-server/handlers.js.map +1 -1
  31. package/build/cjs/integrations/mcp-server/index.js +2 -1
  32. package/build/cjs/integrations/mcp-server/index.js.map +1 -1
  33. package/build/cjs/integrations/mcp-server/transport.js +1 -1
  34. package/build/cjs/integrations/mcp-server/transport.js.map +1 -1
  35. package/build/cjs/integrations/mcp-server/validation.js +7 -5
  36. package/build/cjs/integrations/mcp-server/validation.js.map +1 -1
  37. package/build/cjs/integrations/requestdata.js.map +1 -1
  38. package/build/cjs/integrations/spanStreaming.js +48 -0
  39. package/build/cjs/integrations/spanStreaming.js.map +1 -0
  40. package/build/cjs/semanticAttributes.js +35 -3
  41. package/build/cjs/semanticAttributes.js.map +1 -1
  42. package/build/cjs/tracing/ai/gen-ai-attributes.js +3 -89
  43. package/build/cjs/tracing/ai/gen-ai-attributes.js.map +1 -1
  44. package/build/cjs/tracing/ai/utils.js +74 -0
  45. package/build/cjs/tracing/ai/utils.js.map +1 -1
  46. package/build/cjs/tracing/anthropic-ai/index.js +6 -17
  47. package/build/cjs/tracing/anthropic-ai/index.js.map +1 -1
  48. package/build/cjs/tracing/anthropic-ai/streaming.js +2 -100
  49. package/build/cjs/tracing/anthropic-ai/streaming.js.map +1 -1
  50. package/build/cjs/tracing/anthropic-ai/utils.js +4 -2
  51. package/build/cjs/tracing/anthropic-ai/utils.js.map +1 -1
  52. package/build/cjs/tracing/dynamicSamplingContext.js +2 -1
  53. package/build/cjs/tracing/dynamicSamplingContext.js.map +1 -1
  54. package/build/cjs/tracing/google-genai/constants.js +1 -6
  55. package/build/cjs/tracing/google-genai/constants.js.map +1 -1
  56. package/build/cjs/tracing/google-genai/index.js +40 -35
  57. package/build/cjs/tracing/google-genai/index.js.map +1 -1
  58. package/build/cjs/tracing/google-genai/streaming.js +2 -23
  59. package/build/cjs/tracing/google-genai/streaming.js.map +1 -1
  60. package/build/cjs/tracing/langchain/embeddings.js +132 -0
  61. package/build/cjs/tracing/langchain/embeddings.js.map +1 -0
  62. package/build/cjs/tracing/langchain/index.js +3 -0
  63. package/build/cjs/tracing/langchain/index.js.map +1 -1
  64. package/build/cjs/tracing/langchain/utils.js +12 -4
  65. package/build/cjs/tracing/langchain/utils.js.map +1 -1
  66. package/build/cjs/tracing/langgraph/index.js +4 -3
  67. package/build/cjs/tracing/langgraph/index.js.map +1 -1
  68. package/build/cjs/tracing/openai/index.js +14 -34
  69. package/build/cjs/tracing/openai/index.js.map +1 -1
  70. package/build/cjs/tracing/openai/streaming.js +3 -34
  71. package/build/cjs/tracing/openai/streaming.js.map +1 -1
  72. package/build/cjs/tracing/openai/utils.js +78 -204
  73. package/build/cjs/tracing/openai/utils.js.map +1 -1
  74. package/build/cjs/tracing/sentryNonRecordingSpan.js +7 -0
  75. package/build/cjs/tracing/sentryNonRecordingSpan.js.map +1 -1
  76. package/build/cjs/tracing/sentrySpan.js +39 -0
  77. package/build/cjs/tracing/sentrySpan.js.map +1 -1
  78. package/build/cjs/tracing/spans/beforeSendSpan.js +43 -0
  79. package/build/cjs/tracing/spans/beforeSendSpan.js.map +1 -0
  80. package/build/cjs/tracing/spans/captureSpan.js +126 -0
  81. package/build/cjs/tracing/spans/captureSpan.js.map +1 -0
  82. package/build/cjs/tracing/spans/envelope.js +38 -0
  83. package/build/cjs/tracing/spans/envelope.js.map +1 -0
  84. package/build/cjs/tracing/spans/estimateSize.js +41 -0
  85. package/build/cjs/tracing/spans/estimateSize.js.map +1 -0
  86. package/build/cjs/tracing/spans/hasSpanStreamingEnabled.js +11 -0
  87. package/build/cjs/tracing/spans/hasSpanStreamingEnabled.js.map +1 -0
  88. package/build/cjs/tracing/spans/spanBuffer.js +158 -0
  89. package/build/cjs/tracing/spans/spanBuffer.js.map +1 -0
  90. package/build/cjs/tracing/trace.js +83 -13
  91. package/build/cjs/tracing/trace.js.map +1 -1
  92. package/build/cjs/tracing/utils.js +3 -37
  93. package/build/cjs/tracing/utils.js.map +1 -1
  94. package/build/cjs/tracing/vercel-ai/constants.js +15 -23
  95. package/build/cjs/tracing/vercel-ai/constants.js.map +1 -1
  96. package/build/cjs/tracing/vercel-ai/index.js +32 -45
  97. package/build/cjs/tracing/vercel-ai/index.js.map +1 -1
  98. package/build/cjs/tracing/vercel-ai/utils.js +11 -42
  99. package/build/cjs/tracing/vercel-ai/utils.js.map +1 -1
  100. package/build/cjs/tracing/vercel-ai/vercel-ai-attributes.js +4 -1
  101. package/build/cjs/tracing/vercel-ai/vercel-ai-attributes.js.map +1 -1
  102. package/build/cjs/utils/browser.js +2 -3
  103. package/build/cjs/utils/browser.js.map +1 -1
  104. package/build/cjs/utils/featureFlags.js +6 -0
  105. package/build/cjs/utils/featureFlags.js.map +1 -1
  106. package/build/cjs/utils/object.js +33 -0
  107. package/build/cjs/utils/object.js.map +1 -1
  108. package/build/cjs/utils/spanUtils.js +116 -13
  109. package/build/cjs/utils/spanUtils.js.map +1 -1
  110. package/build/cjs/utils/stacktrace.js +3 -1
  111. package/build/cjs/utils/stacktrace.js.map +1 -1
  112. package/build/cjs/utils/string.js +3 -0
  113. package/build/cjs/utils/string.js.map +1 -1
  114. package/build/cjs/utils/version.js +1 -1
  115. package/build/cjs/utils/weakRef.js +62 -0
  116. package/build/cjs/utils/weakRef.js.map +1 -0
  117. package/build/esm/attributes.js +43 -1
  118. package/build/esm/attributes.js.map +1 -1
  119. package/build/esm/client.js +8 -1
  120. package/build/esm/client.js.map +1 -1
  121. package/build/esm/envelope.js +2 -1
  122. package/build/esm/envelope.js.map +1 -1
  123. package/build/esm/fetch.js +36 -17
  124. package/build/esm/fetch.js.map +1 -1
  125. package/build/esm/index.js +12 -3
  126. package/build/esm/index.js.map +1 -1
  127. package/build/esm/integration.js +6 -0
  128. package/build/esm/integration.js.map +1 -1
  129. package/build/esm/integrations/conversationId.js +11 -0
  130. package/build/esm/integrations/conversationId.js.map +1 -1
  131. package/build/esm/integrations/express/index.js +239 -0
  132. package/build/esm/integrations/express/index.js.map +1 -0
  133. package/build/esm/integrations/express/patch-layer.js +255 -0
  134. package/build/esm/integrations/express/patch-layer.js.map +1 -0
  135. package/build/esm/integrations/express/request-layer-store.js +22 -0
  136. package/build/esm/integrations/express/request-layer-store.js.map +1 -0
  137. package/build/esm/integrations/express/set-sdk-processing-metadata.js +15 -0
  138. package/build/esm/integrations/express/set-sdk-processing-metadata.js.map +1 -0
  139. package/build/esm/integrations/express/types.js +10 -0
  140. package/build/esm/integrations/express/types.js.map +1 -0
  141. package/build/esm/integrations/express/utils.js +225 -0
  142. package/build/esm/integrations/express/utils.js.map +1 -0
  143. package/build/esm/integrations/mcp-server/correlation.js +5 -1
  144. package/build/esm/integrations/mcp-server/correlation.js.map +1 -1
  145. package/build/esm/integrations/mcp-server/handlers.js +18 -10
  146. package/build/esm/integrations/mcp-server/handlers.js.map +1 -1
  147. package/build/esm/integrations/mcp-server/index.js +2 -1
  148. package/build/esm/integrations/mcp-server/index.js.map +1 -1
  149. package/build/esm/integrations/mcp-server/transport.js +1 -1
  150. package/build/esm/integrations/mcp-server/transport.js.map +1 -1
  151. package/build/esm/integrations/mcp-server/validation.js +7 -5
  152. package/build/esm/integrations/mcp-server/validation.js.map +1 -1
  153. package/build/esm/integrations/requestdata.js.map +1 -1
  154. package/build/esm/integrations/spanStreaming.js +46 -0
  155. package/build/esm/integrations/spanStreaming.js.map +1 -0
  156. package/build/esm/package.json +1 -1
  157. package/build/esm/semanticAttributes.js +26 -4
  158. package/build/esm/semanticAttributes.js.map +1 -1
  159. package/build/esm/tracing/ai/gen-ai-attributes.js +3 -76
  160. package/build/esm/tracing/ai/gen-ai-attributes.js.map +1 -1
  161. package/build/esm/tracing/ai/utils.js +73 -2
  162. package/build/esm/tracing/ai/utils.js.map +1 -1
  163. package/build/esm/tracing/anthropic-ai/index.js +8 -19
  164. package/build/esm/tracing/anthropic-ai/index.js.map +1 -1
  165. package/build/esm/tracing/anthropic-ai/streaming.js +3 -101
  166. package/build/esm/tracing/anthropic-ai/streaming.js.map +1 -1
  167. package/build/esm/tracing/anthropic-ai/utils.js +5 -3
  168. package/build/esm/tracing/anthropic-ai/utils.js.map +1 -1
  169. package/build/esm/tracing/dynamicSamplingContext.js +2 -1
  170. package/build/esm/tracing/dynamicSamplingContext.js.map +1 -1
  171. package/build/esm/tracing/google-genai/constants.js +2 -5
  172. package/build/esm/tracing/google-genai/constants.js.map +1 -1
  173. package/build/esm/tracing/google-genai/index.js +42 -37
  174. package/build/esm/tracing/google-genai/index.js.map +1 -1
  175. package/build/esm/tracing/google-genai/streaming.js +2 -23
  176. package/build/esm/tracing/google-genai/streaming.js.map +1 -1
  177. package/build/esm/tracing/langchain/embeddings.js +129 -0
  178. package/build/esm/tracing/langchain/embeddings.js.map +1 -0
  179. package/build/esm/tracing/langchain/index.js +4 -1
  180. package/build/esm/tracing/langchain/index.js.map +1 -1
  181. package/build/esm/tracing/langchain/utils.js +13 -5
  182. package/build/esm/tracing/langchain/utils.js.map +1 -1
  183. package/build/esm/tracing/langgraph/index.js +5 -4
  184. package/build/esm/tracing/langgraph/index.js.map +1 -1
  185. package/build/esm/tracing/openai/index.js +16 -36
  186. package/build/esm/tracing/openai/index.js.map +1 -1
  187. package/build/esm/tracing/openai/streaming.js +4 -35
  188. package/build/esm/tracing/openai/streaming.js.map +1 -1
  189. package/build/esm/tracing/openai/utils.js +79 -196
  190. package/build/esm/tracing/openai/utils.js.map +1 -1
  191. package/build/esm/tracing/sentryNonRecordingSpan.js +7 -0
  192. package/build/esm/tracing/sentryNonRecordingSpan.js.map +1 -1
  193. package/build/esm/tracing/sentrySpan.js +40 -1
  194. package/build/esm/tracing/sentrySpan.js.map +1 -1
  195. package/build/esm/tracing/spans/beforeSendSpan.js +40 -0
  196. package/build/esm/tracing/spans/beforeSendSpan.js.map +1 -0
  197. package/build/esm/tracing/spans/captureSpan.js +122 -0
  198. package/build/esm/tracing/spans/captureSpan.js.map +1 -0
  199. package/build/esm/tracing/spans/envelope.js +36 -0
  200. package/build/esm/tracing/spans/envelope.js.map +1 -0
  201. package/build/esm/tracing/spans/estimateSize.js +39 -0
  202. package/build/esm/tracing/spans/estimateSize.js.map +1 -0
  203. package/build/esm/tracing/spans/hasSpanStreamingEnabled.js +9 -0
  204. package/build/esm/tracing/spans/hasSpanStreamingEnabled.js.map +1 -0
  205. package/build/esm/tracing/spans/spanBuffer.js +156 -0
  206. package/build/esm/tracing/spans/spanBuffer.js.map +1 -0
  207. package/build/esm/tracing/trace.js +84 -14
  208. package/build/esm/tracing/trace.js.map +1 -1
  209. package/build/esm/tracing/utils.js +3 -37
  210. package/build/esm/tracing/utils.js.map +1 -1
  211. package/build/esm/tracing/vercel-ai/constants.js +15 -19
  212. package/build/esm/tracing/vercel-ai/constants.js.map +1 -1
  213. package/build/esm/tracing/vercel-ai/index.js +29 -42
  214. package/build/esm/tracing/vercel-ai/index.js.map +1 -1
  215. package/build/esm/tracing/vercel-ai/utils.js +14 -44
  216. package/build/esm/tracing/vercel-ai/utils.js.map +1 -1
  217. package/build/esm/tracing/vercel-ai/vercel-ai-attributes.js +4 -1
  218. package/build/esm/tracing/vercel-ai/vercel-ai-attributes.js.map +1 -1
  219. package/build/esm/utils/browser.js +2 -3
  220. package/build/esm/utils/browser.js.map +1 -1
  221. package/build/esm/utils/featureFlags.js +6 -0
  222. package/build/esm/utils/featureFlags.js.map +1 -1
  223. package/build/esm/utils/object.js +33 -1
  224. package/build/esm/utils/object.js.map +1 -1
  225. package/build/esm/utils/spanUtils.js +112 -14
  226. package/build/esm/utils/spanUtils.js.map +1 -1
  227. package/build/esm/utils/stacktrace.js +3 -1
  228. package/build/esm/utils/stacktrace.js.map +1 -1
  229. package/build/esm/utils/string.js +3 -0
  230. package/build/esm/utils/string.js.map +1 -1
  231. package/build/esm/utils/version.js +1 -1
  232. package/build/esm/utils/weakRef.js +59 -0
  233. package/build/esm/utils/weakRef.js.map +1 -0
  234. package/build/types/attributes.d.ts +5 -0
  235. package/build/types/attributes.d.ts.map +1 -1
  236. package/build/types/build-time-plugins/buildTimeOptionsBase.d.ts +13 -0
  237. package/build/types/build-time-plugins/buildTimeOptionsBase.d.ts.map +1 -1
  238. package/build/types/client.d.ts +35 -1
  239. package/build/types/client.d.ts.map +1 -1
  240. package/build/types/envelope.d.ts.map +1 -1
  241. package/build/types/fetch.d.ts +12 -8
  242. package/build/types/fetch.d.ts.map +1 -1
  243. package/build/types/index.d.ts +16 -5
  244. package/build/types/index.d.ts.map +1 -1
  245. package/build/types/integration.d.ts.map +1 -1
  246. package/build/types/integrations/conversationId.d.ts.map +1 -1
  247. package/build/types/integrations/express/index.d.ts +82 -0
  248. package/build/types/integrations/express/index.d.ts.map +1 -0
  249. package/build/types/integrations/express/patch-layer.d.ts +32 -0
  250. package/build/types/integrations/express/patch-layer.d.ts.map +1 -0
  251. package/build/types/integrations/express/request-layer-store.d.ts +32 -0
  252. package/build/types/integrations/express/request-layer-store.d.ts.map +1 -0
  253. package/build/types/integrations/express/set-sdk-processing-metadata.d.ts +35 -0
  254. package/build/types/integrations/express/set-sdk-processing-metadata.d.ts.map +1 -0
  255. package/build/types/integrations/express/types.d.ts +158 -0
  256. package/build/types/integrations/express/types.d.ts.map +1 -0
  257. package/build/types/integrations/express/utils.d.ts +93 -0
  258. package/build/types/integrations/express/utils.d.ts.map +1 -0
  259. package/build/types/integrations/mcp-server/correlation.d.ts +2 -1
  260. package/build/types/integrations/mcp-server/correlation.d.ts.map +1 -1
  261. package/build/types/integrations/mcp-server/handlers.d.ts +9 -4
  262. package/build/types/integrations/mcp-server/handlers.d.ts.map +1 -1
  263. package/build/types/integrations/mcp-server/index.d.ts +2 -1
  264. package/build/types/integrations/mcp-server/index.d.ts.map +1 -1
  265. package/build/types/integrations/mcp-server/types.d.ts +40 -7
  266. package/build/types/integrations/mcp-server/types.d.ts.map +1 -1
  267. package/build/types/integrations/mcp-server/validation.d.ts +4 -1
  268. package/build/types/integrations/mcp-server/validation.d.ts.map +1 -1
  269. package/build/types/integrations/requestdata.d.ts.map +1 -1
  270. package/build/types/integrations/spanStreaming.d.ts +2 -0
  271. package/build/types/integrations/spanStreaming.d.ts.map +1 -0
  272. package/build/types/semanticAttributes.d.ts +23 -3
  273. package/build/types/semanticAttributes.d.ts.map +1 -1
  274. package/build/types/tracing/ai/gen-ai-attributes.d.ts +4 -44
  275. package/build/types/tracing/ai/gen-ai-attributes.d.ts.map +1 -1
  276. package/build/types/tracing/ai/utils.d.ts +32 -2
  277. package/build/types/tracing/ai/utils.d.ts.map +1 -1
  278. package/build/types/tracing/anthropic-ai/index.d.ts.map +1 -1
  279. package/build/types/tracing/anthropic-ai/streaming.d.ts.map +1 -1
  280. package/build/types/tracing/anthropic-ai/types.d.ts +5 -0
  281. package/build/types/tracing/anthropic-ai/types.d.ts.map +1 -1
  282. package/build/types/tracing/anthropic-ai/utils.d.ts +1 -1
  283. package/build/types/tracing/anthropic-ai/utils.d.ts.map +1 -1
  284. package/build/types/tracing/dynamicSamplingContext.d.ts.map +1 -1
  285. package/build/types/tracing/google-genai/constants.d.ts +1 -3
  286. package/build/types/tracing/google-genai/constants.d.ts.map +1 -1
  287. package/build/types/tracing/google-genai/index.d.ts.map +1 -1
  288. package/build/types/tracing/google-genai/streaming.d.ts.map +1 -1
  289. package/build/types/tracing/google-genai/types.d.ts +5 -0
  290. package/build/types/tracing/google-genai/types.d.ts.map +1 -1
  291. package/build/types/tracing/index.d.ts +1 -0
  292. package/build/types/tracing/index.d.ts.map +1 -1
  293. package/build/types/tracing/langchain/embeddings.d.ts +27 -0
  294. package/build/types/tracing/langchain/embeddings.d.ts.map +1 -0
  295. package/build/types/tracing/langchain/index.d.ts +1 -0
  296. package/build/types/tracing/langchain/index.d.ts.map +1 -1
  297. package/build/types/tracing/langchain/types.d.ts +5 -0
  298. package/build/types/tracing/langchain/types.d.ts.map +1 -1
  299. package/build/types/tracing/langchain/utils.d.ts +2 -2
  300. package/build/types/tracing/langchain/utils.d.ts.map +1 -1
  301. package/build/types/tracing/langgraph/index.d.ts.map +1 -1
  302. package/build/types/tracing/langgraph/types.d.ts +5 -0
  303. package/build/types/tracing/langgraph/types.d.ts.map +1 -1
  304. package/build/types/tracing/openai/index.d.ts.map +1 -1
  305. package/build/types/tracing/openai/streaming.d.ts.map +1 -1
  306. package/build/types/tracing/openai/types.d.ts +5 -0
  307. package/build/types/tracing/openai/types.d.ts.map +1 -1
  308. package/build/types/tracing/openai/utils.d.ts +4 -49
  309. package/build/types/tracing/openai/utils.d.ts.map +1 -1
  310. package/build/types/tracing/sentryNonRecordingSpan.d.ts +12 -1
  311. package/build/types/tracing/sentryNonRecordingSpan.d.ts.map +1 -1
  312. package/build/types/tracing/sentrySpan.d.ts +10 -1
  313. package/build/types/tracing/sentrySpan.d.ts.map +1 -1
  314. package/build/types/tracing/spans/beforeSendSpan.d.ts +35 -0
  315. package/build/types/tracing/spans/beforeSendSpan.d.ts.map +1 -0
  316. package/build/types/tracing/spans/captureSpan.d.ts +26 -0
  317. package/build/types/tracing/spans/captureSpan.d.ts.map +1 -0
  318. package/build/types/tracing/spans/envelope.d.ts +8 -0
  319. package/build/types/tracing/spans/envelope.d.ts.map +1 -0
  320. package/build/types/tracing/spans/estimateSize.d.ts +12 -0
  321. package/build/types/tracing/spans/estimateSize.d.ts.map +1 -0
  322. package/build/types/tracing/spans/hasSpanStreamingEnabled.d.ts +6 -0
  323. package/build/types/tracing/spans/hasSpanStreamingEnabled.d.ts.map +1 -0
  324. package/build/types/tracing/spans/spanBuffer.d.ts +60 -0
  325. package/build/types/tracing/spans/spanBuffer.d.ts.map +1 -0
  326. package/build/types/tracing/trace.d.ts.map +1 -1
  327. package/build/types/tracing/utils.d.ts.map +1 -1
  328. package/build/types/tracing/vercel-ai/constants.d.ts +2 -5
  329. package/build/types/tracing/vercel-ai/constants.d.ts.map +1 -1
  330. package/build/types/tracing/vercel-ai/index.d.ts.map +1 -1
  331. package/build/types/tracing/vercel-ai/utils.d.ts +1 -5
  332. package/build/types/tracing/vercel-ai/utils.d.ts.map +1 -1
  333. package/build/types/tracing/vercel-ai/vercel-ai-attributes.d.ts +0 -480
  334. package/build/types/tracing/vercel-ai/vercel-ai-attributes.d.ts.map +1 -1
  335. package/build/types/types-hoist/envelope.d.ts +22 -2
  336. package/build/types/types-hoist/envelope.d.ts.map +1 -1
  337. package/build/types/types-hoist/integration.d.ts +8 -0
  338. package/build/types/types-hoist/integration.d.ts.map +1 -1
  339. package/build/types/types-hoist/link.d.ts +2 -2
  340. package/build/types/types-hoist/link.d.ts.map +1 -1
  341. package/build/types/types-hoist/options.d.ts +26 -2
  342. package/build/types/types-hoist/options.d.ts.map +1 -1
  343. package/build/types/types-hoist/span.d.ts +35 -0
  344. package/build/types/types-hoist/span.d.ts.map +1 -1
  345. package/build/types/types-hoist/view-hierarchy.d.ts +1 -0
  346. package/build/types/types-hoist/view-hierarchy.d.ts.map +1 -1
  347. package/build/types/utils/browser.d.ts +1 -1
  348. package/build/types/utils/browser.d.ts.map +1 -1
  349. package/build/types/utils/featureFlags.d.ts.map +1 -1
  350. package/build/types/utils/object.d.ts +10 -0
  351. package/build/types/utils/object.d.ts.map +1 -1
  352. package/build/types/utils/spanUtils.d.ts +27 -2
  353. package/build/types/utils/spanUtils.d.ts.map +1 -1
  354. package/build/types/utils/stacktrace.d.ts.map +1 -1
  355. package/build/types/utils/string.d.ts +2 -2
  356. package/build/types/utils/string.d.ts.map +1 -1
  357. package/build/types/utils/weakRef.d.ts +34 -0
  358. package/build/types/utils/weakRef.d.ts.map +1 -0
  359. package/build/types-ts3.8/attributes.d.ts +5 -0
  360. package/build/types-ts3.8/build-time-plugins/buildTimeOptionsBase.d.ts +13 -0
  361. package/build/types-ts3.8/client.d.ts +35 -1
  362. package/build/types-ts3.8/fetch.d.ts +14 -10
  363. package/build/types-ts3.8/index.d.ts +16 -5
  364. package/build/types-ts3.8/integrations/express/index.d.ts +82 -0
  365. package/build/types-ts3.8/integrations/express/patch-layer.d.ts +32 -0
  366. package/build/types-ts3.8/integrations/express/request-layer-store.d.ts +32 -0
  367. package/build/types-ts3.8/integrations/express/set-sdk-processing-metadata.d.ts +35 -0
  368. package/build/types-ts3.8/integrations/express/types.d.ts +158 -0
  369. package/build/types-ts3.8/integrations/express/utils.d.ts +96 -0
  370. package/build/types-ts3.8/integrations/mcp-server/correlation.d.ts +2 -1
  371. package/build/types-ts3.8/integrations/mcp-server/handlers.d.ts +9 -4
  372. package/build/types-ts3.8/integrations/mcp-server/index.d.ts +2 -1
  373. package/build/types-ts3.8/integrations/mcp-server/types.d.ts +40 -7
  374. package/build/types-ts3.8/integrations/mcp-server/validation.d.ts +4 -1
  375. package/build/types-ts3.8/integrations/spanStreaming.d.ts +2 -0
  376. package/build/types-ts3.8/semanticAttributes.d.ts +23 -3
  377. package/build/types-ts3.8/tracing/ai/gen-ai-attributes.d.ts +4 -44
  378. package/build/types-ts3.8/tracing/ai/utils.d.ts +32 -2
  379. package/build/types-ts3.8/tracing/anthropic-ai/types.d.ts +5 -0
  380. package/build/types-ts3.8/tracing/anthropic-ai/utils.d.ts +1 -1
  381. package/build/types-ts3.8/tracing/google-genai/constants.d.ts +1 -3
  382. package/build/types-ts3.8/tracing/google-genai/types.d.ts +5 -0
  383. package/build/types-ts3.8/tracing/index.d.ts +1 -0
  384. package/build/types-ts3.8/tracing/langchain/embeddings.d.ts +27 -0
  385. package/build/types-ts3.8/tracing/langchain/index.d.ts +1 -0
  386. package/build/types-ts3.8/tracing/langchain/types.d.ts +5 -0
  387. package/build/types-ts3.8/tracing/langchain/utils.d.ts +2 -2
  388. package/build/types-ts3.8/tracing/langgraph/types.d.ts +5 -0
  389. package/build/types-ts3.8/tracing/openai/types.d.ts +5 -0
  390. package/build/types-ts3.8/tracing/openai/utils.d.ts +4 -49
  391. package/build/types-ts3.8/tracing/sentryNonRecordingSpan.d.ts +12 -1
  392. package/build/types-ts3.8/tracing/sentrySpan.d.ts +10 -1
  393. package/build/types-ts3.8/tracing/spans/beforeSendSpan.d.ts +35 -0
  394. package/build/types-ts3.8/tracing/spans/captureSpan.d.ts +26 -0
  395. package/build/types-ts3.8/tracing/spans/envelope.d.ts +8 -0
  396. package/build/types-ts3.8/tracing/spans/estimateSize.d.ts +12 -0
  397. package/build/types-ts3.8/tracing/spans/hasSpanStreamingEnabled.d.ts +6 -0
  398. package/build/types-ts3.8/tracing/spans/spanBuffer.d.ts +60 -0
  399. package/build/types-ts3.8/tracing/vercel-ai/constants.d.ts +2 -5
  400. package/build/types-ts3.8/tracing/vercel-ai/utils.d.ts +1 -5
  401. package/build/types-ts3.8/tracing/vercel-ai/vercel-ai-attributes.d.ts +0 -480
  402. package/build/types-ts3.8/types-hoist/envelope.d.ts +22 -2
  403. package/build/types-ts3.8/types-hoist/integration.d.ts +8 -0
  404. package/build/types-ts3.8/types-hoist/link.d.ts +2 -2
  405. package/build/types-ts3.8/types-hoist/options.d.ts +26 -2
  406. package/build/types-ts3.8/types-hoist/span.d.ts +35 -0
  407. package/build/types-ts3.8/types-hoist/view-hierarchy.d.ts +1 -0
  408. package/build/types-ts3.8/utils/browser.d.ts +1 -1
  409. package/build/types-ts3.8/utils/object.d.ts +10 -0
  410. package/build/types-ts3.8/utils/spanUtils.d.ts +27 -2
  411. package/build/types-ts3.8/utils/string.d.ts +2 -2
  412. package/build/types-ts3.8/utils/weakRef.d.ts +34 -0
  413. package/package.json +1 -1
@@ -50,9 +50,9 @@ function extractRequestAttributes(args, methodPath, operationName) {
50
50
  * Add private request attributes to spans.
51
51
  * This is only recorded if recordInputs is true.
52
52
  */
53
- function addPrivateRequestAttributes(span, params) {
53
+ function addPrivateRequestAttributes(span, params, enableTruncation) {
54
54
  const messages = utils$1.messagesFromParams(params);
55
- utils$1.setMessagesAttribute(span, messages);
55
+ utils$1.setMessagesAttribute(span, messages, enableTruncation);
56
56
 
57
57
  if ('prompt' in params) {
58
58
  span.setAttributes({ [genAiAttributes.GEN_AI_PROMPT_ATTRIBUTE]: JSON.stringify(params.prompt) });
@@ -105,17 +105,6 @@ function addMetadataAttributes(span, response) {
105
105
  [genAiAttributes.GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: response.model,
106
106
  });
107
107
 
108
- if ('created' in response && typeof response.created === 'number') {
109
- span.setAttributes({
110
- [genAiAttributes.ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE]: new Date(response.created * 1000).toISOString(),
111
- });
112
- }
113
- if ('created_at' in response && typeof response.created_at === 'number') {
114
- span.setAttributes({
115
- [genAiAttributes.ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE]: new Date(response.created_at * 1000).toISOString(),
116
- });
117
- }
118
-
119
108
  if ('usage' in response && response.usage) {
120
109
  utils.setTokenUsageAttributes(
121
110
  span,
@@ -195,7 +184,7 @@ function handleStreamingRequest(
195
184
  originalResult = originalMethod.apply(context, args) ;
196
185
 
197
186
  if (options.recordInputs && params) {
198
- addPrivateRequestAttributes(span, params);
187
+ addPrivateRequestAttributes(span, params, utils.shouldEnableTruncation(options.enableTruncation));
199
188
  }
200
189
 
201
190
  return (async () => {
@@ -217,7 +206,7 @@ function handleStreamingRequest(
217
206
  return trace.startSpanManual(spanConfig, span => {
218
207
  try {
219
208
  if (options.recordInputs && params) {
220
- addPrivateRequestAttributes(span, params);
209
+ addPrivateRequestAttributes(span, params, utils.shouldEnableTruncation(options.enableTruncation));
221
210
  }
222
211
  const messageStream = target.apply(context, args);
223
212
  return streaming.instrumentMessageStream(messageStream, span, options.recordOutputs ?? false);
@@ -242,7 +231,7 @@ function instrumentMethod(
242
231
  ) {
243
232
  return new Proxy(originalMethod, {
244
233
  apply(target, thisArg, args) {
245
- const operationName = instrumentedMethod.operation;
234
+ const operationName = instrumentedMethod.operation || 'unknown';
246
235
  const requestAttributes = extractRequestAttributes(args, methodPath, operationName);
247
236
  const model = requestAttributes[genAiAttributes.GEN_AI_REQUEST_MODEL_ATTRIBUTE] ?? 'unknown';
248
237
 
@@ -278,7 +267,7 @@ function instrumentMethod(
278
267
  originalResult = target.apply(context, args) ;
279
268
 
280
269
  if (options.recordInputs && params) {
281
- addPrivateRequestAttributes(span, params);
270
+ addPrivateRequestAttributes(span, params, utils.shouldEnableTruncation(options.enableTruncation));
282
271
  }
283
272
 
284
273
  return originalResult.then(
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../../src/tracing/anthropic-ai/index.ts"],"sourcesContent":["import { captureException } from '../../exports';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../../semanticAttributes';\nimport { SPAN_STATUS_ERROR } from '../../tracing';\nimport { startSpan, startSpanManual } from '../../tracing/trace';\nimport type { Span, SpanAttributeValue } from '../../types-hoist/span';\nimport {\n ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE,\n GEN_AI_OPERATION_NAME_ATTRIBUTE,\n GEN_AI_PROMPT_ATTRIBUTE,\n GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE,\n GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE,\n GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE,\n GEN_AI_REQUEST_MODEL_ATTRIBUTE,\n GEN_AI_REQUEST_STREAM_ATTRIBUTE,\n GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE,\n GEN_AI_REQUEST_TOP_K_ATTRIBUTE,\n GEN_AI_REQUEST_TOP_P_ATTRIBUTE,\n GEN_AI_RESPONSE_ID_ATTRIBUTE,\n GEN_AI_RESPONSE_MODEL_ATTRIBUTE,\n GEN_AI_RESPONSE_TEXT_ATTRIBUTE,\n GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE,\n GEN_AI_SYSTEM_ATTRIBUTE,\n} from '../ai/gen-ai-attributes';\nimport type { InstrumentedMethodEntry } from '../ai/utils';\nimport {\n buildMethodPath,\n resolveAIRecordingOptions,\n setTokenUsageAttributes,\n wrapPromiseWithMethods,\n} from '../ai/utils';\nimport { ANTHROPIC_METHOD_REGISTRY } from './constants';\nimport { instrumentAsyncIterableStream, instrumentMessageStream } from './streaming';\nimport type { AnthropicAiOptions, AnthropicAiResponse, AnthropicAiStreamingEvent, ContentBlock } from './types';\nimport { handleResponseError, messagesFromParams, setMessagesAttribute } from './utils';\n\n/**\n * Extract request attributes from method arguments\n */\nfunction extractRequestAttributes(args: unknown[], methodPath: string, operationName: string): Record<string, unknown> {\n const attributes: Record<string, unknown> = {\n [GEN_AI_SYSTEM_ATTRIBUTE]: 'anthropic',\n [GEN_AI_OPERATION_NAME_ATTRIBUTE]: operationName,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ai.anthropic',\n };\n\n if (args.length > 0 && typeof args[0] === 'object' && args[0] !== null) {\n const params = args[0] as Record<string, unknown>;\n if (params.tools && Array.isArray(params.tools)) {\n attributes[GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE] = JSON.stringify(params.tools);\n }\n\n attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = params.model ?? 'unknown';\n if ('temperature' in params) attributes[GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE] = params.temperature;\n if ('top_p' in params) attributes[GEN_AI_REQUEST_TOP_P_ATTRIBUTE] = params.top_p;\n if ('stream' in params) attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE] = params.stream;\n if ('top_k' in params) attributes[GEN_AI_REQUEST_TOP_K_ATTRIBUTE] = params.top_k;\n if ('frequency_penalty' in params)\n attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE] = params.frequency_penalty;\n if ('max_tokens' in params) attributes[GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE] = params.max_tokens;\n } else {\n if (methodPath === 'models.retrieve' || methodPath === 'models.get') {\n // models.retrieve(model-id) and models.get(model-id)\n attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = args[0];\n } else {\n attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = 'unknown';\n }\n }\n\n return attributes;\n}\n\n/**\n * Add private request attributes to spans.\n * This is only recorded if recordInputs is true.\n */\nfunction addPrivateRequestAttributes(span: Span, params: Record<string, unknown>): void {\n const messages = messagesFromParams(params);\n setMessagesAttribute(span, messages);\n\n if ('prompt' in params) {\n span.setAttributes({ [GEN_AI_PROMPT_ATTRIBUTE]: JSON.stringify(params.prompt) });\n }\n}\n\n/**\n * Add content attributes when recordOutputs is enabled\n */\nfunction addContentAttributes(span: Span, response: AnthropicAiResponse): void {\n // Messages.create\n if ('content' in response) {\n if (Array.isArray(response.content)) {\n span.setAttributes({\n [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: response.content\n .map((item: ContentBlock) => item.text)\n .filter(text => !!text)\n .join(''),\n });\n\n const toolCalls: Array<ContentBlock> = [];\n\n for (const item of response.content) {\n if (item.type === 'tool_use' || item.type === 'server_tool_use') {\n toolCalls.push(item);\n }\n }\n if (toolCalls.length > 0) {\n span.setAttributes({ [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(toolCalls) });\n }\n }\n }\n // Completions.create\n if ('completion' in response) {\n span.setAttributes({ [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: response.completion });\n }\n // Models.countTokens\n if ('input_tokens' in response) {\n span.setAttributes({ [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: JSON.stringify(response.input_tokens) });\n }\n}\n\n/**\n * Add basic metadata attributes from the response\n */\nfunction addMetadataAttributes(span: Span, response: AnthropicAiResponse): void {\n if ('id' in response && 'model' in response) {\n span.setAttributes({\n [GEN_AI_RESPONSE_ID_ATTRIBUTE]: response.id,\n [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: response.model,\n });\n\n if ('created' in response && typeof response.created === 'number') {\n span.setAttributes({\n [ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE]: new Date(response.created * 1000).toISOString(),\n });\n }\n if ('created_at' in response && typeof response.created_at === 'number') {\n span.setAttributes({\n [ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE]: new Date(response.created_at * 1000).toISOString(),\n });\n }\n\n if ('usage' in response && response.usage) {\n setTokenUsageAttributes(\n span,\n response.usage.input_tokens,\n response.usage.output_tokens,\n response.usage.cache_creation_input_tokens,\n response.usage.cache_read_input_tokens,\n );\n }\n }\n}\n\n/**\n * Add response attributes to spans\n */\nfunction addResponseAttributes(span: Span, response: AnthropicAiResponse, recordOutputs?: boolean): void {\n if (!response || typeof response !== 'object') return;\n\n // capture error, do not add attributes if error (they shouldn't exist)\n if ('type' in response && response.type === 'error') {\n handleResponseError(span, response);\n return;\n }\n\n // Private response attributes that are only recorded if recordOutputs is true.\n if (recordOutputs) {\n addContentAttributes(span, response);\n }\n\n // Add basic metadata attributes\n addMetadataAttributes(span, response);\n}\n\n/**\n * Handle common error catching and reporting for streaming requests\n */\nfunction handleStreamingError(error: unknown, span: Span, methodPath: string): never {\n captureException(error, {\n mechanism: { handled: false, type: 'auto.ai.anthropic', data: { function: methodPath } },\n });\n\n if (span.isRecording()) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n span.end();\n }\n throw error;\n}\n\n/**\n * Handle streaming cases with common logic\n */\nfunction handleStreamingRequest<T extends unknown[], R>(\n originalMethod: (...args: T) => R | Promise<R>,\n target: (...args: T) => R | Promise<R>,\n context: unknown,\n args: T,\n requestAttributes: Record<string, unknown>,\n operationName: string,\n methodPath: string,\n params: Record<string, unknown> | undefined,\n options: AnthropicAiOptions,\n isStreamRequested: boolean,\n isStreamingMethod: boolean,\n): R | Promise<R> {\n const model = requestAttributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] ?? 'unknown';\n const spanConfig = {\n name: `${operationName} ${model}`,\n op: `gen_ai.${operationName}`,\n attributes: requestAttributes as Record<string, SpanAttributeValue>,\n };\n\n // messages.stream() always returns a sync MessageStream, even with stream: true param\n if (isStreamRequested && !isStreamingMethod) {\n let originalResult!: Promise<R>;\n\n const instrumentedPromise = startSpanManual(spanConfig, (span: Span) => {\n originalResult = originalMethod.apply(context, args) as Promise<R>;\n\n if (options.recordInputs && params) {\n addPrivateRequestAttributes(span, params);\n }\n\n return (async () => {\n try {\n const result = await originalResult;\n return instrumentAsyncIterableStream(\n result as AsyncIterable<AnthropicAiStreamingEvent>,\n span,\n options.recordOutputs ?? false,\n ) as unknown as R;\n } catch (error) {\n return handleStreamingError(error, span, methodPath);\n }\n })();\n });\n\n return wrapPromiseWithMethods(originalResult, instrumentedPromise, 'auto.ai.anthropic');\n } else {\n return startSpanManual(spanConfig, span => {\n try {\n if (options.recordInputs && params) {\n addPrivateRequestAttributes(span, params);\n }\n const messageStream = target.apply(context, args);\n return instrumentMessageStream(messageStream, span, options.recordOutputs ?? false);\n } catch (error) {\n return handleStreamingError(error, span, methodPath);\n }\n });\n }\n}\n\n/**\n * Instrument a method with Sentry spans\n * Following Sentry AI Agents Manual Instrumentation conventions\n * @see https://docs.sentry.io/platforms/javascript/guides/node/tracing/instrumentation/ai-agents-module/#manual-instrumentation\n */\nfunction instrumentMethod<T extends unknown[], R>(\n originalMethod: (...args: T) => R | Promise<R>,\n methodPath: string,\n instrumentedMethod: InstrumentedMethodEntry,\n context: unknown,\n options: AnthropicAiOptions,\n): (...args: T) => R | Promise<R> {\n return new Proxy(originalMethod, {\n apply(target, thisArg, args: T): R | Promise<R> {\n const operationName = instrumentedMethod.operation;\n const requestAttributes = extractRequestAttributes(args, methodPath, operationName);\n const model = requestAttributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] ?? 'unknown';\n\n const params = typeof args[0] === 'object' ? (args[0] as Record<string, unknown>) : undefined;\n const isStreamRequested = Boolean(params?.stream);\n const isStreamingMethod = instrumentedMethod.streaming === true;\n\n if (isStreamRequested || isStreamingMethod) {\n return handleStreamingRequest(\n originalMethod,\n target,\n context,\n args,\n requestAttributes,\n operationName,\n methodPath,\n params,\n options,\n isStreamRequested,\n isStreamingMethod,\n );\n }\n\n let originalResult!: Promise<R>;\n\n const instrumentedPromise = startSpan(\n {\n name: `${operationName} ${model}`,\n op: `gen_ai.${operationName}`,\n attributes: requestAttributes as Record<string, SpanAttributeValue>,\n },\n span => {\n originalResult = target.apply(context, args) as Promise<R>;\n\n if (options.recordInputs && params) {\n addPrivateRequestAttributes(span, params);\n }\n\n return originalResult.then(\n result => {\n addResponseAttributes(span, result as AnthropicAiResponse, options.recordOutputs);\n return result;\n },\n error => {\n captureException(error, {\n mechanism: {\n handled: false,\n type: 'auto.ai.anthropic',\n data: {\n function: methodPath,\n },\n },\n });\n throw error;\n },\n );\n },\n );\n\n return wrapPromiseWithMethods(originalResult, instrumentedPromise, 'auto.ai.anthropic');\n },\n }) as (...args: T) => R | Promise<R>;\n}\n\n/**\n * Create a deep proxy for Anthropic AI client instrumentation\n */\nfunction createDeepProxy<T extends object>(target: T, currentPath = '', options: AnthropicAiOptions): T {\n return new Proxy(target, {\n get(obj: object, prop: string): unknown {\n const value = (obj as Record<string, unknown>)[prop];\n const methodPath = buildMethodPath(currentPath, String(prop));\n\n const instrumentedMethod = ANTHROPIC_METHOD_REGISTRY[methodPath as keyof typeof ANTHROPIC_METHOD_REGISTRY];\n if (typeof value === 'function' && instrumentedMethod) {\n return instrumentMethod(\n value as (...args: unknown[]) => unknown | Promise<unknown>,\n methodPath,\n instrumentedMethod,\n obj,\n options,\n );\n }\n\n if (typeof value === 'function') {\n // Bind non-instrumented functions to preserve the original `this` context,\n return value.bind(obj);\n }\n\n if (value && typeof value === 'object') {\n return createDeepProxy(value, methodPath, options);\n }\n\n return value;\n },\n }) as T;\n}\n\n/**\n * Instrument an Anthropic AI client with Sentry tracing\n * Can be used across Node.js, Cloudflare Workers, and Vercel Edge\n *\n * @template T - The type of the client that extends object\n * @param client - The Anthropic AI client to instrument\n * @param options - Optional configuration for recording inputs and outputs\n * @returns The instrumented client with the same type as the input\n */\nexport function instrumentAnthropicAiClient<T extends object>(anthropicAiClient: T, options?: AnthropicAiOptions): T {\n return createDeepProxy(anthropicAiClient, '', resolveAIRecordingOptions(options));\n}\n"],"names":["GEN_AI_SYSTEM_ATTRIBUTE","GEN_AI_OPERATION_NAME_ATTRIBUTE","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE","GEN_AI_REQUEST_MODEL_ATTRIBUTE","GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE","GEN_AI_REQUEST_TOP_P_ATTRIBUTE","GEN_AI_REQUEST_STREAM_ATTRIBUTE","GEN_AI_REQUEST_TOP_K_ATTRIBUTE","GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE","GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE","messagesFromParams","setMessagesAttribute","GEN_AI_PROMPT_ATTRIBUTE","GEN_AI_RESPONSE_TEXT_ATTRIBUTE","GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE","GEN_AI_RESPONSE_ID_ATTRIBUTE","GEN_AI_RESPONSE_MODEL_ATTRIBUTE","ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE","setTokenUsageAttributes","handleResponseError","captureException","SPAN_STATUS_ERROR","startSpanManual","instrumentAsyncIterableStream","wrapPromiseWithMethods","instrumentMessageStream","startSpan","buildMethodPath","ANTHROPIC_METHOD_REGISTRY","resolveAIRecordingOptions"],"mappings":";;;;;;;;;;;;AAmCA;AACA;AACA;AACA,SAAS,wBAAwB,CAAC,IAAI,EAAa,UAAU,EAAU,aAAa,EAAmC;AACvH,EAAE,MAAM,UAAU,GAA4B;AAC9C,IAAI,CAACA,uCAAuB,GAAG,WAAW;AAC1C,IAAI,CAACC,+CAA+B,GAAG,aAAa;AACpD,IAAI,CAACC,mDAAgC,GAAG,mBAAmB;AAC3D,GAAG;;AAEH,EAAE,IAAI,IAAI,CAAC,SAAS,CAAA,IAAK,OAAO,IAAI,CAAC,CAAC,CAAA,KAAM,YAAY,IAAI,CAAC,CAAC,CAAA,KAAM,IAAI,EAAE;AAC1E,IAAI,MAAM,MAAA,GAAS,IAAI,CAAC,CAAC,CAAA;AACzB,IAAI,IAAI,MAAM,CAAC,SAAS,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE;AACrD,MAAM,UAAU,CAACC,wDAAwC,CAAA,GAAI,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,KAAK,CAAC;AACzF,IAAI;;AAEJ,IAAI,UAAU,CAACC,8CAA8B,C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IAAA,GAAA,CAAA,GAAA,EAAA,IAAA,EAAA;AACA,MAAA,MAAA,KAAA,GAAA,CAAA,GAAA,GAAA,IAAA,CAAA;AACA,MAAA,MAAA,UAAA,GAAAG,qBAAA,CAAA,WAAA,EAAA,MAAA,CAAA,IAAA,CAAA,CAAA;;AAEA,MAAA,MAAA,kBAAA,GAAAC,mCAAA,CAAA,UAAA,EAAA;AACA,MAAA,IAAA,OAAA,KAAA,KAAA,UAAA,IAAA,kBAAA,EAAA;AACA,QAAA,OAAA,gBAAA;AACA,UAAA,KAAA;AACA,UAAA,UAAA;AACA,UAAA,kBAAA;AACA,UAAA,GAAA;AACA,UAAA,OAAA;AACA,SAAA;AACA,MAAA;;AAEA,MAAA,IAAA,OAAA,KAAA,KAAA,UAAA,EAAA;AACA;AACA,QAAA,OAAA,KAAA,CAAA,IAAA,CAAA,GAAA,CAAA;AACA,MAAA;;AAEA,MAAA,IAAA,KAAA,IAAA,OAAA,KAAA,KAAA,QAAA,EAAA;AACA,QAAA,OAAA,eAAA,CAAA,KAAA,EAAA,UAAA,EAAA,OAAA,CAAA;AACA,MAAA;;AAEA,MAAA,OAAA,KAAA;AACA,IAAA,CAAA;AACA,GAAA,CAAA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAA,2BAAA,CAAA,iBAAA,EAAA,OAAA,EAAA;AACA,EAAA,OAAA,eAAA,CAAA,iBAAA,EAAA,EAAA,EAAAC,+BAAA,CAAA,OAAA,CAAA,CAAA;AACA;;;;"}
1
+ {"version":3,"file":"index.js","sources":["../../../../src/tracing/anthropic-ai/index.ts"],"sourcesContent":["import { captureException } from '../../exports';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../../semanticAttributes';\nimport { SPAN_STATUS_ERROR } from '../../tracing';\nimport { startSpan, startSpanManual } from '../../tracing/trace';\nimport type { Span, SpanAttributeValue } from '../../types-hoist/span';\nimport {\n GEN_AI_OPERATION_NAME_ATTRIBUTE,\n GEN_AI_PROMPT_ATTRIBUTE,\n GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE,\n GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE,\n GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE,\n GEN_AI_REQUEST_MODEL_ATTRIBUTE,\n GEN_AI_REQUEST_STREAM_ATTRIBUTE,\n GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE,\n GEN_AI_REQUEST_TOP_K_ATTRIBUTE,\n GEN_AI_REQUEST_TOP_P_ATTRIBUTE,\n GEN_AI_RESPONSE_ID_ATTRIBUTE,\n GEN_AI_RESPONSE_MODEL_ATTRIBUTE,\n GEN_AI_RESPONSE_TEXT_ATTRIBUTE,\n GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE,\n GEN_AI_SYSTEM_ATTRIBUTE,\n} from '../ai/gen-ai-attributes';\nimport type { InstrumentedMethodEntry } from '../ai/utils';\nimport {\n buildMethodPath,\n resolveAIRecordingOptions,\n setTokenUsageAttributes,\n shouldEnableTruncation,\n wrapPromiseWithMethods,\n} from '../ai/utils';\nimport { ANTHROPIC_METHOD_REGISTRY } from './constants';\nimport { instrumentAsyncIterableStream, instrumentMessageStream } from './streaming';\nimport type { AnthropicAiOptions, AnthropicAiResponse, AnthropicAiStreamingEvent, ContentBlock } from './types';\nimport { handleResponseError, messagesFromParams, setMessagesAttribute } from './utils';\n\n/**\n * Extract request attributes from method arguments\n */\nfunction extractRequestAttributes(args: unknown[], methodPath: string, operationName: string): Record<string, unknown> {\n const attributes: Record<string, unknown> = {\n [GEN_AI_SYSTEM_ATTRIBUTE]: 'anthropic',\n [GEN_AI_OPERATION_NAME_ATTRIBUTE]: operationName,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ai.anthropic',\n };\n\n if (args.length > 0 && typeof args[0] === 'object' && args[0] !== null) {\n const params = args[0] as Record<string, unknown>;\n if (params.tools && Array.isArray(params.tools)) {\n attributes[GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE] = JSON.stringify(params.tools);\n }\n\n attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = params.model ?? 'unknown';\n if ('temperature' in params) attributes[GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE] = params.temperature;\n if ('top_p' in params) attributes[GEN_AI_REQUEST_TOP_P_ATTRIBUTE] = params.top_p;\n if ('stream' in params) attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE] = params.stream;\n if ('top_k' in params) attributes[GEN_AI_REQUEST_TOP_K_ATTRIBUTE] = params.top_k;\n if ('frequency_penalty' in params)\n attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE] = params.frequency_penalty;\n if ('max_tokens' in params) attributes[GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE] = params.max_tokens;\n } else {\n if (methodPath === 'models.retrieve' || methodPath === 'models.get') {\n // models.retrieve(model-id) and models.get(model-id)\n attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = args[0];\n } else {\n attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = 'unknown';\n }\n }\n\n return attributes;\n}\n\n/**\n * Add private request attributes to spans.\n * This is only recorded if recordInputs is true.\n */\nfunction addPrivateRequestAttributes(span: Span, params: Record<string, unknown>, enableTruncation: boolean): void {\n const messages = messagesFromParams(params);\n setMessagesAttribute(span, messages, enableTruncation);\n\n if ('prompt' in params) {\n span.setAttributes({ [GEN_AI_PROMPT_ATTRIBUTE]: JSON.stringify(params.prompt) });\n }\n}\n\n/**\n * Add content attributes when recordOutputs is enabled\n */\nfunction addContentAttributes(span: Span, response: AnthropicAiResponse): void {\n // Messages.create\n if ('content' in response) {\n if (Array.isArray(response.content)) {\n span.setAttributes({\n [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: response.content\n .map((item: ContentBlock) => item.text)\n .filter(text => !!text)\n .join(''),\n });\n\n const toolCalls: Array<ContentBlock> = [];\n\n for (const item of response.content) {\n if (item.type === 'tool_use' || item.type === 'server_tool_use') {\n toolCalls.push(item);\n }\n }\n if (toolCalls.length > 0) {\n span.setAttributes({ [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(toolCalls) });\n }\n }\n }\n // Completions.create\n if ('completion' in response) {\n span.setAttributes({ [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: response.completion });\n }\n // Models.countTokens\n if ('input_tokens' in response) {\n span.setAttributes({ [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: JSON.stringify(response.input_tokens) });\n }\n}\n\n/**\n * Add basic metadata attributes from the response\n */\nfunction addMetadataAttributes(span: Span, response: AnthropicAiResponse): void {\n if ('id' in response && 'model' in response) {\n span.setAttributes({\n [GEN_AI_RESPONSE_ID_ATTRIBUTE]: response.id,\n [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: response.model,\n });\n\n if ('usage' in response && response.usage) {\n setTokenUsageAttributes(\n span,\n response.usage.input_tokens,\n response.usage.output_tokens,\n response.usage.cache_creation_input_tokens,\n response.usage.cache_read_input_tokens,\n );\n }\n }\n}\n\n/**\n * Add response attributes to spans\n */\nfunction addResponseAttributes(span: Span, response: AnthropicAiResponse, recordOutputs?: boolean): void {\n if (!response || typeof response !== 'object') return;\n\n // capture error, do not add attributes if error (they shouldn't exist)\n if ('type' in response && response.type === 'error') {\n handleResponseError(span, response);\n return;\n }\n\n // Private response attributes that are only recorded if recordOutputs is true.\n if (recordOutputs) {\n addContentAttributes(span, response);\n }\n\n // Add basic metadata attributes\n addMetadataAttributes(span, response);\n}\n\n/**\n * Handle common error catching and reporting for streaming requests\n */\nfunction handleStreamingError(error: unknown, span: Span, methodPath: string): never {\n captureException(error, {\n mechanism: { handled: false, type: 'auto.ai.anthropic', data: { function: methodPath } },\n });\n\n if (span.isRecording()) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n span.end();\n }\n throw error;\n}\n\n/**\n * Handle streaming cases with common logic\n */\nfunction handleStreamingRequest<T extends unknown[], R>(\n originalMethod: (...args: T) => R | Promise<R>,\n target: (...args: T) => R | Promise<R>,\n context: unknown,\n args: T,\n requestAttributes: Record<string, unknown>,\n operationName: string,\n methodPath: string,\n params: Record<string, unknown> | undefined,\n options: AnthropicAiOptions,\n isStreamRequested: boolean,\n isStreamingMethod: boolean,\n): R | Promise<R> {\n const model = requestAttributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] ?? 'unknown';\n const spanConfig = {\n name: `${operationName} ${model}`,\n op: `gen_ai.${operationName}`,\n attributes: requestAttributes as Record<string, SpanAttributeValue>,\n };\n\n // messages.stream() always returns a sync MessageStream, even with stream: true param\n if (isStreamRequested && !isStreamingMethod) {\n let originalResult!: Promise<R>;\n\n const instrumentedPromise = startSpanManual(spanConfig, (span: Span) => {\n originalResult = originalMethod.apply(context, args) as Promise<R>;\n\n if (options.recordInputs && params) {\n addPrivateRequestAttributes(span, params, shouldEnableTruncation(options.enableTruncation));\n }\n\n return (async () => {\n try {\n const result = await originalResult;\n return instrumentAsyncIterableStream(\n result as AsyncIterable<AnthropicAiStreamingEvent>,\n span,\n options.recordOutputs ?? false,\n ) as unknown as R;\n } catch (error) {\n return handleStreamingError(error, span, methodPath);\n }\n })();\n });\n\n return wrapPromiseWithMethods(originalResult, instrumentedPromise, 'auto.ai.anthropic');\n } else {\n return startSpanManual(spanConfig, span => {\n try {\n if (options.recordInputs && params) {\n addPrivateRequestAttributes(span, params, shouldEnableTruncation(options.enableTruncation));\n }\n const messageStream = target.apply(context, args);\n return instrumentMessageStream(messageStream, span, options.recordOutputs ?? false);\n } catch (error) {\n return handleStreamingError(error, span, methodPath);\n }\n });\n }\n}\n\n/**\n * Instrument a method with Sentry spans\n * Following Sentry AI Agents Manual Instrumentation conventions\n * @see https://docs.sentry.io/platforms/javascript/guides/node/tracing/instrumentation/ai-agents-module/#manual-instrumentation\n */\nfunction instrumentMethod<T extends unknown[], R>(\n originalMethod: (...args: T) => R | Promise<R>,\n methodPath: string,\n instrumentedMethod: InstrumentedMethodEntry,\n context: unknown,\n options: AnthropicAiOptions,\n): (...args: T) => R | Promise<R> {\n return new Proxy(originalMethod, {\n apply(target, thisArg, args: T): R | Promise<R> {\n const operationName = instrumentedMethod.operation || 'unknown';\n const requestAttributes = extractRequestAttributes(args, methodPath, operationName);\n const model = requestAttributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] ?? 'unknown';\n\n const params = typeof args[0] === 'object' ? (args[0] as Record<string, unknown>) : undefined;\n const isStreamRequested = Boolean(params?.stream);\n const isStreamingMethod = instrumentedMethod.streaming === true;\n\n if (isStreamRequested || isStreamingMethod) {\n return handleStreamingRequest(\n originalMethod,\n target,\n context,\n args,\n requestAttributes,\n operationName,\n methodPath,\n params,\n options,\n isStreamRequested,\n isStreamingMethod,\n );\n }\n\n let originalResult!: Promise<R>;\n\n const instrumentedPromise = startSpan(\n {\n name: `${operationName} ${model}`,\n op: `gen_ai.${operationName}`,\n attributes: requestAttributes as Record<string, SpanAttributeValue>,\n },\n span => {\n originalResult = target.apply(context, args) as Promise<R>;\n\n if (options.recordInputs && params) {\n addPrivateRequestAttributes(span, params, shouldEnableTruncation(options.enableTruncation));\n }\n\n return originalResult.then(\n result => {\n addResponseAttributes(span, result as AnthropicAiResponse, options.recordOutputs);\n return result;\n },\n error => {\n captureException(error, {\n mechanism: {\n handled: false,\n type: 'auto.ai.anthropic',\n data: {\n function: methodPath,\n },\n },\n });\n throw error;\n },\n );\n },\n );\n\n return wrapPromiseWithMethods(originalResult, instrumentedPromise, 'auto.ai.anthropic');\n },\n }) as (...args: T) => R | Promise<R>;\n}\n\n/**\n * Create a deep proxy for Anthropic AI client instrumentation\n */\nfunction createDeepProxy<T extends object>(target: T, currentPath = '', options: AnthropicAiOptions): T {\n return new Proxy(target, {\n get(obj: object, prop: string): unknown {\n const value = (obj as Record<string, unknown>)[prop];\n const methodPath = buildMethodPath(currentPath, String(prop));\n\n const instrumentedMethod = ANTHROPIC_METHOD_REGISTRY[methodPath as keyof typeof ANTHROPIC_METHOD_REGISTRY];\n if (typeof value === 'function' && instrumentedMethod) {\n return instrumentMethod(\n value as (...args: unknown[]) => unknown | Promise<unknown>,\n methodPath,\n instrumentedMethod,\n obj,\n options,\n );\n }\n\n if (typeof value === 'function') {\n // Bind non-instrumented functions to preserve the original `this` context,\n return value.bind(obj);\n }\n\n if (value && typeof value === 'object') {\n return createDeepProxy(value, methodPath, options);\n }\n\n return value;\n },\n }) as T;\n}\n\n/**\n * Instrument an Anthropic AI client with Sentry tracing\n * Can be used across Node.js, Cloudflare Workers, and Vercel Edge\n *\n * @template T - The type of the client that extends object\n * @param client - The Anthropic AI client to instrument\n * @param options - Optional configuration for recording inputs and outputs\n * @returns The instrumented client with the same type as the input\n */\nexport function instrumentAnthropicAiClient<T extends object>(anthropicAiClient: T, options?: AnthropicAiOptions): T {\n return createDeepProxy(anthropicAiClient, '', resolveAIRecordingOptions(options));\n}\n"],"names":["GEN_AI_SYSTEM_ATTRIBUTE","GEN_AI_OPERATION_NAME_ATTRIBUTE","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE","GEN_AI_REQUEST_MODEL_ATTRIBUTE","GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE","GEN_AI_REQUEST_TOP_P_ATTRIBUTE","GEN_AI_REQUEST_STREAM_ATTRIBUTE","GEN_AI_REQUEST_TOP_K_ATTRIBUTE","GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE","GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE","messagesFromParams","setMessagesAttribute","GEN_AI_PROMPT_ATTRIBUTE","GEN_AI_RESPONSE_TEXT_ATTRIBUTE","GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE","GEN_AI_RESPONSE_ID_ATTRIBUTE","GEN_AI_RESPONSE_MODEL_ATTRIBUTE","setTokenUsageAttributes","handleResponseError","captureException","SPAN_STATUS_ERROR","startSpanManual","shouldEnableTruncation","instrumentAsyncIterableStream","wrapPromiseWithMethods","instrumentMessageStream","startSpan","buildMethodPath","ANTHROPIC_METHOD_REGISTRY","resolveAIRecordingOptions"],"mappings":";;;;;;;;;;;;AAmCA;AACA;AACA;AACA,SAAS,wBAAwB,CAAC,IAAI,EAAa,UAAU,EAAU,aAAa,EAAmC;AACvH,EAAE,MAAM,UAAU,GAA4B;AAC9C,IAAI,CAACA,uCAAuB,GAAG,WAAW;AAC1C,IAAI,CAACC,+CAA+B,GAAG,aAAa;AACpD,IAAI,CAACC,mDAAgC,GAAG,mBAAmB;AAC3D,GAAG;;AAEH,EAAE,IAAI,IAAI,CAAC,SAAS,CAAA,IAAK,OAAO,IAAI,CAAC,CAAC,CAAA,KAAM,YAAY,IAAI,CAAC,CAAC,CAAA,KAAM,IAAI,EAAE;AAC1E,IAAI,MAAM,MAAA,GAAS,IAAI,CAAC,CAAC,CAAA;AACzB,IAAI,IAAI,MAAM,CAAC,SAAS,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE;AACrD,MAAM,UAAU,CAACC,wDAAwC,CAAA,GAAI,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,KAAK,CAAC;AACzF,IAAI;;AAEJ,IAAI,UAAU,CAACC,8CAA8B,CAAA,GAAI,MAAM,CAAC,KAAA,IAAS,SAAS;AAC1E,IAAI,IAAI,aAAA,IAAiB,MAAM,EAAE,UAAU,CAACC,oDAAoC,CAAA,GAAI,MAAM,CAAC,WAAW;AACtG,IAAI,IAAI,OAAA,IAAW,MAAM,EAAE,UAAU,CAACC,8CAA8B,CAAA,GAAI,MAAM,CAAC,KAAK;AACpF,IAAI,IAAI,QAAA,IAAY,MAAM,EAAE,UAAU,CAACC,+CAA+B,CAAA,GAAI,MAAM,CAAC,MAAM;AACvF,IAAI,IAAI,OAAA,IAAW,MAAM,EAAE,UAAU,CAACC,8CAA8B,CAAA,GAAI,MAAM,CAAC,KAAK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;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAA,2BAAA,CAAA,iBAAA,EAAA,OAAA,EAAA;AACA,EAAA,OAAA,eAAA,CAAA,iBAAA,EAAA,EAAA,EAAAC,+BAAA,CAAA,OAAA,CAAA,CAAA;AACA;;;;"}
@@ -2,7 +2,6 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
 
3
3
  const _exports = require('../../exports.js');
4
4
  const spanstatus = require('../spanstatus.js');
5
- const genAiAttributes = require('../ai/gen-ai-attributes.js');
6
5
  const utils = require('../ai/utils.js');
7
6
  const utils$1 = require('./utils.js');
8
7
 
@@ -172,60 +171,6 @@ function processEvent(
172
171
  handleContentBlockStop(event, state);
173
172
  }
174
173
 
175
- /**
176
- * Finalizes span attributes when stream processing completes
177
- */
178
- function finalizeStreamSpan(state, span, recordOutputs) {
179
- if (!span.isRecording()) {
180
- return;
181
- }
182
-
183
- // Set common response attributes if available
184
- if (state.responseId) {
185
- span.setAttributes({
186
- [genAiAttributes.GEN_AI_RESPONSE_ID_ATTRIBUTE]: state.responseId,
187
- });
188
- }
189
- if (state.responseModel) {
190
- span.setAttributes({
191
- [genAiAttributes.GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: state.responseModel,
192
- });
193
- }
194
-
195
- utils.setTokenUsageAttributes(
196
- span,
197
- state.promptTokens,
198
- state.completionTokens,
199
- state.cacheCreationInputTokens,
200
- state.cacheReadInputTokens,
201
- );
202
-
203
- span.setAttributes({
204
- [genAiAttributes.GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true,
205
- });
206
-
207
- if (state.finishReasons.length > 0) {
208
- span.setAttributes({
209
- [genAiAttributes.GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE]: JSON.stringify(state.finishReasons),
210
- });
211
- }
212
-
213
- if (recordOutputs && state.responseTexts.length > 0) {
214
- span.setAttributes({
215
- [genAiAttributes.GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: state.responseTexts.join(''),
216
- });
217
- }
218
-
219
- // Set tool calls if any were captured
220
- if (recordOutputs && state.toolCalls.length > 0) {
221
- span.setAttributes({
222
- [genAiAttributes.GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(state.toolCalls),
223
- });
224
- }
225
-
226
- span.end();
227
- }
228
-
229
174
  /**
230
175
  * Instruments an async iterable stream of Anthropic events, updates the span with
231
176
  * streaming attributes and (optionally) the aggregated output text, and yields
@@ -255,50 +200,7 @@ async function* instrumentAsyncIterableStream(
255
200
  yield event;
256
201
  }
257
202
  } finally {
258
- // Set common response attributes if available
259
- if (state.responseId) {
260
- span.setAttributes({
261
- [genAiAttributes.GEN_AI_RESPONSE_ID_ATTRIBUTE]: state.responseId,
262
- });
263
- }
264
- if (state.responseModel) {
265
- span.setAttributes({
266
- [genAiAttributes.GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: state.responseModel,
267
- });
268
- }
269
-
270
- utils.setTokenUsageAttributes(
271
- span,
272
- state.promptTokens,
273
- state.completionTokens,
274
- state.cacheCreationInputTokens,
275
- state.cacheReadInputTokens,
276
- );
277
-
278
- span.setAttributes({
279
- [genAiAttributes.GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true,
280
- });
281
-
282
- if (state.finishReasons.length > 0) {
283
- span.setAttributes({
284
- [genAiAttributes.GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE]: JSON.stringify(state.finishReasons),
285
- });
286
- }
287
-
288
- if (recordOutputs && state.responseTexts.length > 0) {
289
- span.setAttributes({
290
- [genAiAttributes.GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: state.responseTexts.join(''),
291
- });
292
- }
293
-
294
- // Set tool calls if any were captured
295
- if (recordOutputs && state.toolCalls.length > 0) {
296
- span.setAttributes({
297
- [genAiAttributes.GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(state.toolCalls),
298
- });
299
- }
300
-
301
- span.end();
203
+ utils.endStreamSpan(span, state, recordOutputs);
302
204
  }
303
205
  }
304
206
 
@@ -330,7 +232,7 @@ function instrumentMessageStream(
330
232
  // The event fired when a message is done being streamed by the API. Corresponds to the message_stop SSE event.
331
233
  // @see https://github.com/anthropics/anthropic-sdk-typescript/blob/d3be31f5a4e6ebb4c0a2f65dbb8f381ae73a9166/helpers.md?plain=1#L42-L44
332
234
  stream.on('message', () => {
333
- finalizeStreamSpan(state, span, recordOutputs);
235
+ utils.endStreamSpan(span, state, recordOutputs);
334
236
  });
335
237
 
336
238
  stream.on('error', (error) => {
@@ -1 +1 @@
1
- {"version":3,"file":"streaming.js","sources":["../../../../src/tracing/anthropic-ai/streaming.ts"],"sourcesContent":["import { captureException } from '../../exports';\nimport { SPAN_STATUS_ERROR } from '../../tracing';\nimport type { Span } from '../../types-hoist/span';\nimport {\n GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE,\n GEN_AI_RESPONSE_ID_ATTRIBUTE,\n GEN_AI_RESPONSE_MODEL_ATTRIBUTE,\n GEN_AI_RESPONSE_STREAMING_ATTRIBUTE,\n GEN_AI_RESPONSE_TEXT_ATTRIBUTE,\n GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE,\n} from '../ai/gen-ai-attributes';\nimport { setTokenUsageAttributes } from '../ai/utils';\nimport type { AnthropicAiStreamingEvent } from './types';\nimport { mapAnthropicErrorToStatusMessage } from './utils';\n\n/**\n * State object used to accumulate information from a stream of Anthropic AI events.\n */\ninterface StreamingState {\n /** Collected response text fragments (for output recording). */\n responseTexts: string[];\n /** Reasons for finishing the response, as reported by the API. */\n finishReasons: string[];\n /** The response ID. */\n responseId: string;\n /** The model name. */\n responseModel: string;\n /** Number of prompt/input tokens used. */\n promptTokens: number | undefined;\n /** Number of completion/output tokens used. */\n completionTokens: number | undefined;\n /** Number of cache creation input tokens used. */\n cacheCreationInputTokens: number | undefined;\n /** Number of cache read input tokens used. */\n cacheReadInputTokens: number | undefined;\n /** Accumulated tool calls (finalized) */\n toolCalls: Array<Record<string, unknown>>;\n /** In-progress tool call blocks keyed by index */\n activeToolBlocks: Record<\n number,\n {\n id?: string;\n name?: string;\n inputJsonParts: string[];\n }\n >;\n}\n\n/**\n * Checks if an event is an error event\n * @param event - The event to process\n * @param state - The state of the streaming process\n * @param recordOutputs - Whether to record outputs\n * @param span - The span to update\n * @returns Whether an error occurred\n */\n\nfunction isErrorEvent(event: AnthropicAiStreamingEvent, span: Span): boolean {\n if ('type' in event && typeof event.type === 'string') {\n // If the event is an error, set the span status and capture the error\n // These error events are not rejected by the API by default, but are sent as metadata of the response\n if (event.type === 'error') {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: mapAnthropicErrorToStatusMessage(event.error?.type) });\n captureException(event.error, {\n mechanism: {\n handled: false,\n type: 'auto.ai.anthropic.anthropic_error',\n },\n });\n return true;\n }\n }\n return false;\n}\n\n/**\n * Processes the message metadata of an event\n * @param event - The event to process\n * @param state - The state of the streaming process\n */\n\nfunction handleMessageMetadata(event: AnthropicAiStreamingEvent, state: StreamingState): void {\n // The token counts shown in the usage field of the message_delta event are cumulative.\n // @see https://docs.anthropic.com/en/docs/build-with-claude/streaming#event-types\n if (event.type === 'message_delta' && event.usage) {\n if ('output_tokens' in event.usage && typeof event.usage.output_tokens === 'number') {\n state.completionTokens = event.usage.output_tokens;\n }\n }\n\n if (event.message) {\n const message = event.message;\n\n if (message.id) state.responseId = message.id;\n if (message.model) state.responseModel = message.model;\n if (message.stop_reason) state.finishReasons.push(message.stop_reason);\n\n if (message.usage) {\n if (typeof message.usage.input_tokens === 'number') state.promptTokens = message.usage.input_tokens;\n if (typeof message.usage.cache_creation_input_tokens === 'number')\n state.cacheCreationInputTokens = message.usage.cache_creation_input_tokens;\n if (typeof message.usage.cache_read_input_tokens === 'number')\n state.cacheReadInputTokens = message.usage.cache_read_input_tokens;\n }\n }\n}\n\n/**\n * Handle start of a content block (e.g., tool_use)\n */\nfunction handleContentBlockStart(event: AnthropicAiStreamingEvent, state: StreamingState): void {\n if (event.type !== 'content_block_start' || typeof event.index !== 'number' || !event.content_block) return;\n if (event.content_block.type === 'tool_use' || event.content_block.type === 'server_tool_use') {\n state.activeToolBlocks[event.index] = {\n id: event.content_block.id,\n name: event.content_block.name,\n inputJsonParts: [],\n };\n }\n}\n\n/**\n * Handle deltas of a content block, including input_json_delta for tool_use\n */\nfunction handleContentBlockDelta(\n event: AnthropicAiStreamingEvent,\n state: StreamingState,\n recordOutputs: boolean,\n): void {\n if (event.type !== 'content_block_delta' || !event.delta) return;\n\n // Accumulate tool_use input JSON deltas only when we have an index and an active tool block\n if (\n typeof event.index === 'number' &&\n 'partial_json' in event.delta &&\n typeof event.delta.partial_json === 'string'\n ) {\n const active = state.activeToolBlocks[event.index];\n if (active) {\n active.inputJsonParts.push(event.delta.partial_json);\n }\n }\n\n // Accumulate streamed response text regardless of index\n if (recordOutputs && typeof event.delta.text === 'string') {\n state.responseTexts.push(event.delta.text);\n }\n}\n\n/**\n * Handle stop of a content block; finalize tool_use entries\n */\nfunction handleContentBlockStop(event: AnthropicAiStreamingEvent, state: StreamingState): void {\n if (event.type !== 'content_block_stop' || typeof event.index !== 'number') return;\n\n const active = state.activeToolBlocks[event.index];\n if (!active) return;\n\n const raw = active.inputJsonParts.join('');\n let parsedInput: unknown;\n\n try {\n parsedInput = raw ? JSON.parse(raw) : {};\n } catch {\n parsedInput = { __unparsed: raw };\n }\n\n state.toolCalls.push({\n type: 'tool_use',\n id: active.id,\n name: active.name,\n input: parsedInput,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete state.activeToolBlocks[event.index];\n}\n\n/**\n * Processes an event\n * @param event - The event to process\n * @param state - The state of the streaming process\n * @param recordOutputs - Whether to record outputs\n * @param span - The span to update\n */\nfunction processEvent(\n event: AnthropicAiStreamingEvent,\n state: StreamingState,\n recordOutputs: boolean,\n span: Span,\n): void {\n if (!(event && typeof event === 'object')) {\n return;\n }\n\n const isError = isErrorEvent(event, span);\n if (isError) return;\n\n handleMessageMetadata(event, state);\n\n // Tool call events are sent via 3 separate events:\n // - content_block_start (start of the tool call)\n // - content_block_delta (delta aka input of the tool call)\n // - content_block_stop (end of the tool call)\n // We need to handle them all to capture the full tool call.\n handleContentBlockStart(event, state);\n handleContentBlockDelta(event, state, recordOutputs);\n handleContentBlockStop(event, state);\n}\n\n/**\n * Finalizes span attributes when stream processing completes\n */\nfunction finalizeStreamSpan(state: StreamingState, span: Span, recordOutputs: boolean): void {\n if (!span.isRecording()) {\n return;\n }\n\n // Set common response attributes if available\n if (state.responseId) {\n span.setAttributes({\n [GEN_AI_RESPONSE_ID_ATTRIBUTE]: state.responseId,\n });\n }\n if (state.responseModel) {\n span.setAttributes({\n [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: state.responseModel,\n });\n }\n\n setTokenUsageAttributes(\n span,\n state.promptTokens,\n state.completionTokens,\n state.cacheCreationInputTokens,\n state.cacheReadInputTokens,\n );\n\n span.setAttributes({\n [GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true,\n });\n\n if (state.finishReasons.length > 0) {\n span.setAttributes({\n [GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE]: JSON.stringify(state.finishReasons),\n });\n }\n\n if (recordOutputs && state.responseTexts.length > 0) {\n span.setAttributes({\n [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: state.responseTexts.join(''),\n });\n }\n\n // Set tool calls if any were captured\n if (recordOutputs && state.toolCalls.length > 0) {\n span.setAttributes({\n [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(state.toolCalls),\n });\n }\n\n span.end();\n}\n\n/**\n * Instruments an async iterable stream of Anthropic events, updates the span with\n * streaming attributes and (optionally) the aggregated output text, and yields\n * each event from the input stream unchanged.\n */\nexport async function* instrumentAsyncIterableStream(\n stream: AsyncIterable<AnthropicAiStreamingEvent>,\n span: Span,\n recordOutputs: boolean,\n): AsyncGenerator<AnthropicAiStreamingEvent, void, unknown> {\n const state: StreamingState = {\n responseTexts: [],\n finishReasons: [],\n responseId: '',\n responseModel: '',\n promptTokens: undefined,\n completionTokens: undefined,\n cacheCreationInputTokens: undefined,\n cacheReadInputTokens: undefined,\n toolCalls: [],\n activeToolBlocks: {},\n };\n\n try {\n for await (const event of stream) {\n processEvent(event, state, recordOutputs, span);\n yield event;\n }\n } finally {\n // Set common response attributes if available\n if (state.responseId) {\n span.setAttributes({\n [GEN_AI_RESPONSE_ID_ATTRIBUTE]: state.responseId,\n });\n }\n if (state.responseModel) {\n span.setAttributes({\n [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: state.responseModel,\n });\n }\n\n setTokenUsageAttributes(\n span,\n state.promptTokens,\n state.completionTokens,\n state.cacheCreationInputTokens,\n state.cacheReadInputTokens,\n );\n\n span.setAttributes({\n [GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true,\n });\n\n if (state.finishReasons.length > 0) {\n span.setAttributes({\n [GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE]: JSON.stringify(state.finishReasons),\n });\n }\n\n if (recordOutputs && state.responseTexts.length > 0) {\n span.setAttributes({\n [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: state.responseTexts.join(''),\n });\n }\n\n // Set tool calls if any were captured\n if (recordOutputs && state.toolCalls.length > 0) {\n span.setAttributes({\n [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(state.toolCalls),\n });\n }\n\n span.end();\n }\n}\n\n/**\n * Instruments a MessageStream by registering event handlers and preserving the original stream API.\n */\nexport function instrumentMessageStream<R extends { on: (...args: unknown[]) => void }>(\n stream: R,\n span: Span,\n recordOutputs: boolean,\n): R {\n const state: StreamingState = {\n responseTexts: [],\n finishReasons: [],\n responseId: '',\n responseModel: '',\n promptTokens: undefined,\n completionTokens: undefined,\n cacheCreationInputTokens: undefined,\n cacheReadInputTokens: undefined,\n toolCalls: [],\n activeToolBlocks: {},\n };\n\n stream.on('streamEvent', (event: unknown) => {\n processEvent(event as AnthropicAiStreamingEvent, state, recordOutputs, span);\n });\n\n // The event fired when a message is done being streamed by the API. Corresponds to the message_stop SSE event.\n // @see https://github.com/anthropics/anthropic-sdk-typescript/blob/d3be31f5a4e6ebb4c0a2f65dbb8f381ae73a9166/helpers.md?plain=1#L42-L44\n stream.on('message', () => {\n finalizeStreamSpan(state, span, recordOutputs);\n });\n\n stream.on('error', (error: unknown) => {\n captureException(error, {\n mechanism: {\n handled: false,\n type: 'auto.ai.anthropic.stream_error',\n },\n });\n\n if (span.isRecording()) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n span.end();\n }\n });\n\n return stream;\n}\n"],"names":["SPAN_STATUS_ERROR","mapAnthropicErrorToStatusMessage","captureException","GEN_AI_RESPONSE_ID_ATTRIBUTE","GEN_AI_RESPONSE_MODEL_ATTRIBUTE","setTokenUsageAttributes","GEN_AI_RESPONSE_STREAMING_ATTRIBUTE","GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE","GEN_AI_RESPONSE_TEXT_ATTRIBUTE","GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE"],"mappings":";;;;;;;;AAeA;AACA;AACA;;AA+BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,YAAY,CAAC,KAAK,EAA6B,IAAI,EAAiB;AAC7E,EAAE,IAAI,MAAA,IAAU,KAAA,IAAS,OAAO,KAAK,CAAC,IAAA,KAAS,QAAQ,EAAE;AACzD;AACA;AACA,IAAI,IAAI,KAAK,CAAC,IAAA,KAAS,OAAO,EAAE;AAChC,MAAM,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,EAAEA,4BAAiB,EAAE,OAAO,EAAEC,wCAAgC,CAAC,KAAK,CAAC,KAAK,EAAE,IAAI,CAAA,EAAG,CAAC;AAC/G,MAAMC,yBAAgB,CAAC,KAAK,CAAC,KAAK,EAAE;AACpC,QAAQ,SAAS,EAAE;AACnB,UAAU,OAAO,EAAE,KAAK;AACxB,UAAU,IAA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MAAM,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,EAAEF,4BAAiB,EAAE,OAAO,EAAE,gBAAA,EAAkB,CAAC;AAC5E,MAAM,IAAI,CAAC,GAAG,EAAE;AAChB,IAAI;AACJ,EAAE,CAAC,CAAC;;AAEJ,EAAE,OAAO,MAAM;AACf;;;;;"}
1
+ {"version":3,"file":"streaming.js","sources":["../../../../src/tracing/anthropic-ai/streaming.ts"],"sourcesContent":["import { captureException } from '../../exports';\nimport { SPAN_STATUS_ERROR } from '../../tracing';\nimport type { Span } from '../../types-hoist/span';\nimport { endStreamSpan } from '../ai/utils';\nimport type { AnthropicAiStreamingEvent } from './types';\nimport { mapAnthropicErrorToStatusMessage } from './utils';\n\n/**\n * State object used to accumulate information from a stream of Anthropic AI events.\n */\ninterface StreamingState {\n /** Collected response text fragments (for output recording). */\n responseTexts: string[];\n /** Reasons for finishing the response, as reported by the API. */\n finishReasons: string[];\n /** The response ID. */\n responseId: string;\n /** The model name. */\n responseModel: string;\n /** Number of prompt/input tokens used. */\n promptTokens: number | undefined;\n /** Number of completion/output tokens used. */\n completionTokens: number | undefined;\n /** Number of cache creation input tokens used. */\n cacheCreationInputTokens: number | undefined;\n /** Number of cache read input tokens used. */\n cacheReadInputTokens: number | undefined;\n /** Accumulated tool calls (finalized) */\n toolCalls: Array<Record<string, unknown>>;\n /** In-progress tool call blocks keyed by index */\n activeToolBlocks: Record<\n number,\n {\n id?: string;\n name?: string;\n inputJsonParts: string[];\n }\n >;\n}\n\n/**\n * Checks if an event is an error event\n * @param event - The event to process\n * @param state - The state of the streaming process\n * @param recordOutputs - Whether to record outputs\n * @param span - The span to update\n * @returns Whether an error occurred\n */\n\nfunction isErrorEvent(event: AnthropicAiStreamingEvent, span: Span): boolean {\n if ('type' in event && typeof event.type === 'string') {\n // If the event is an error, set the span status and capture the error\n // These error events are not rejected by the API by default, but are sent as metadata of the response\n if (event.type === 'error') {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: mapAnthropicErrorToStatusMessage(event.error?.type) });\n captureException(event.error, {\n mechanism: {\n handled: false,\n type: 'auto.ai.anthropic.anthropic_error',\n },\n });\n return true;\n }\n }\n return false;\n}\n\n/**\n * Processes the message metadata of an event\n * @param event - The event to process\n * @param state - The state of the streaming process\n */\n\nfunction handleMessageMetadata(event: AnthropicAiStreamingEvent, state: StreamingState): void {\n // The token counts shown in the usage field of the message_delta event are cumulative.\n // @see https://docs.anthropic.com/en/docs/build-with-claude/streaming#event-types\n if (event.type === 'message_delta' && event.usage) {\n if ('output_tokens' in event.usage && typeof event.usage.output_tokens === 'number') {\n state.completionTokens = event.usage.output_tokens;\n }\n }\n\n if (event.message) {\n const message = event.message;\n\n if (message.id) state.responseId = message.id;\n if (message.model) state.responseModel = message.model;\n if (message.stop_reason) state.finishReasons.push(message.stop_reason);\n\n if (message.usage) {\n if (typeof message.usage.input_tokens === 'number') state.promptTokens = message.usage.input_tokens;\n if (typeof message.usage.cache_creation_input_tokens === 'number')\n state.cacheCreationInputTokens = message.usage.cache_creation_input_tokens;\n if (typeof message.usage.cache_read_input_tokens === 'number')\n state.cacheReadInputTokens = message.usage.cache_read_input_tokens;\n }\n }\n}\n\n/**\n * Handle start of a content block (e.g., tool_use)\n */\nfunction handleContentBlockStart(event: AnthropicAiStreamingEvent, state: StreamingState): void {\n if (event.type !== 'content_block_start' || typeof event.index !== 'number' || !event.content_block) return;\n if (event.content_block.type === 'tool_use' || event.content_block.type === 'server_tool_use') {\n state.activeToolBlocks[event.index] = {\n id: event.content_block.id,\n name: event.content_block.name,\n inputJsonParts: [],\n };\n }\n}\n\n/**\n * Handle deltas of a content block, including input_json_delta for tool_use\n */\nfunction handleContentBlockDelta(\n event: AnthropicAiStreamingEvent,\n state: StreamingState,\n recordOutputs: boolean,\n): void {\n if (event.type !== 'content_block_delta' || !event.delta) return;\n\n // Accumulate tool_use input JSON deltas only when we have an index and an active tool block\n if (\n typeof event.index === 'number' &&\n 'partial_json' in event.delta &&\n typeof event.delta.partial_json === 'string'\n ) {\n const active = state.activeToolBlocks[event.index];\n if (active) {\n active.inputJsonParts.push(event.delta.partial_json);\n }\n }\n\n // Accumulate streamed response text regardless of index\n if (recordOutputs && typeof event.delta.text === 'string') {\n state.responseTexts.push(event.delta.text);\n }\n}\n\n/**\n * Handle stop of a content block; finalize tool_use entries\n */\nfunction handleContentBlockStop(event: AnthropicAiStreamingEvent, state: StreamingState): void {\n if (event.type !== 'content_block_stop' || typeof event.index !== 'number') return;\n\n const active = state.activeToolBlocks[event.index];\n if (!active) return;\n\n const raw = active.inputJsonParts.join('');\n let parsedInput: unknown;\n\n try {\n parsedInput = raw ? JSON.parse(raw) : {};\n } catch {\n parsedInput = { __unparsed: raw };\n }\n\n state.toolCalls.push({\n type: 'tool_use',\n id: active.id,\n name: active.name,\n input: parsedInput,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete state.activeToolBlocks[event.index];\n}\n\n/**\n * Processes an event\n * @param event - The event to process\n * @param state - The state of the streaming process\n * @param recordOutputs - Whether to record outputs\n * @param span - The span to update\n */\nfunction processEvent(\n event: AnthropicAiStreamingEvent,\n state: StreamingState,\n recordOutputs: boolean,\n span: Span,\n): void {\n if (!(event && typeof event === 'object')) {\n return;\n }\n\n const isError = isErrorEvent(event, span);\n if (isError) return;\n\n handleMessageMetadata(event, state);\n\n // Tool call events are sent via 3 separate events:\n // - content_block_start (start of the tool call)\n // - content_block_delta (delta aka input of the tool call)\n // - content_block_stop (end of the tool call)\n // We need to handle them all to capture the full tool call.\n handleContentBlockStart(event, state);\n handleContentBlockDelta(event, state, recordOutputs);\n handleContentBlockStop(event, state);\n}\n\n/**\n * Instruments an async iterable stream of Anthropic events, updates the span with\n * streaming attributes and (optionally) the aggregated output text, and yields\n * each event from the input stream unchanged.\n */\nexport async function* instrumentAsyncIterableStream(\n stream: AsyncIterable<AnthropicAiStreamingEvent>,\n span: Span,\n recordOutputs: boolean,\n): AsyncGenerator<AnthropicAiStreamingEvent, void, unknown> {\n const state: StreamingState = {\n responseTexts: [],\n finishReasons: [],\n responseId: '',\n responseModel: '',\n promptTokens: undefined,\n completionTokens: undefined,\n cacheCreationInputTokens: undefined,\n cacheReadInputTokens: undefined,\n toolCalls: [],\n activeToolBlocks: {},\n };\n\n try {\n for await (const event of stream) {\n processEvent(event, state, recordOutputs, span);\n yield event;\n }\n } finally {\n endStreamSpan(span, state, recordOutputs);\n }\n}\n\n/**\n * Instruments a MessageStream by registering event handlers and preserving the original stream API.\n */\nexport function instrumentMessageStream<R extends { on: (...args: unknown[]) => void }>(\n stream: R,\n span: Span,\n recordOutputs: boolean,\n): R {\n const state: StreamingState = {\n responseTexts: [],\n finishReasons: [],\n responseId: '',\n responseModel: '',\n promptTokens: undefined,\n completionTokens: undefined,\n cacheCreationInputTokens: undefined,\n cacheReadInputTokens: undefined,\n toolCalls: [],\n activeToolBlocks: {},\n };\n\n stream.on('streamEvent', (event: unknown) => {\n processEvent(event as AnthropicAiStreamingEvent, state, recordOutputs, span);\n });\n\n // The event fired when a message is done being streamed by the API. Corresponds to the message_stop SSE event.\n // @see https://github.com/anthropics/anthropic-sdk-typescript/blob/d3be31f5a4e6ebb4c0a2f65dbb8f381ae73a9166/helpers.md?plain=1#L42-L44\n stream.on('message', () => {\n endStreamSpan(span, state, recordOutputs);\n });\n\n stream.on('error', (error: unknown) => {\n captureException(error, {\n mechanism: {\n handled: false,\n type: 'auto.ai.anthropic.stream_error',\n },\n });\n\n if (span.isRecording()) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n span.end();\n }\n });\n\n return stream;\n}\n"],"names":["SPAN_STATUS_ERROR","mapAnthropicErrorToStatusMessage","captureException","endStreamSpan"],"mappings":";;;;;;;AAOA;AACA;AACA;;AA+BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,YAAY,CAAC,KAAK,EAA6B,IAAI,EAAiB;AAC7E,EAAE,IAAI,MAAA,IAAU,KAAA,IAAS,OAAO,KAAK,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E,gCAAgC;AAC9C,OAAO;AACP,KAAK,CAAC;;AAEN,IAAI,IAAI,IAAI,CAAC,WAAW,EAAE,EAAE;AAC5B,MAAM,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,EAAEF,4BAAiB,EAAE,OAAO,EAAE,gBAAA,EAAkB,CAAC;AAC5E,MAAM,IAAI,CAAC,GAAG,EAAE;AAChB,IAAI;AACJ,EAAE,CAAC,CAAC;;AAEJ,EAAE,OAAO,MAAM;AACf;;;;;"}
@@ -9,7 +9,7 @@ const utils = require('../ai/utils.js');
9
9
  * Set the messages and messages original length attributes.
10
10
  * Extracts system instructions before truncation.
11
11
  */
12
- function setMessagesAttribute(span, messages) {
12
+ function setMessagesAttribute(span, messages, enableTruncation) {
13
13
  if (Array.isArray(messages) && messages.length === 0) {
14
14
  return;
15
15
  }
@@ -24,7 +24,9 @@ function setMessagesAttribute(span, messages) {
24
24
 
25
25
  const filteredLength = Array.isArray(filteredMessages) ? filteredMessages.length : 1;
26
26
  span.setAttributes({
27
- [genAiAttributes.GEN_AI_INPUT_MESSAGES_ATTRIBUTE]: utils.getTruncatedJsonString(filteredMessages),
27
+ [genAiAttributes.GEN_AI_INPUT_MESSAGES_ATTRIBUTE]: enableTruncation
28
+ ? utils.getTruncatedJsonString(filteredMessages)
29
+ : utils.getJsonString(filteredMessages),
28
30
  [genAiAttributes.GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE]: filteredLength,
29
31
  });
30
32
  }
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sources":["../../../../src/tracing/anthropic-ai/utils.ts"],"sourcesContent":["import { captureException } from '../../exports';\nimport { SPAN_STATUS_ERROR } from '../../tracing';\nimport type { Span } from '../../types-hoist/span';\nimport type { SpanStatusType } from '../../types-hoist/spanStatus';\nimport {\n GEN_AI_INPUT_MESSAGES_ATTRIBUTE,\n GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE,\n GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE,\n} from '../ai/gen-ai-attributes';\nimport { extractSystemInstructions, getTruncatedJsonString } from '../ai/utils';\nimport type { AnthropicAiResponse } from './types';\n\n/**\n * Set the messages and messages original length attributes.\n * Extracts system instructions before truncation.\n */\nexport function setMessagesAttribute(span: Span, messages: unknown): void {\n if (Array.isArray(messages) && messages.length === 0) {\n return;\n }\n\n const { systemInstructions, filteredMessages } = extractSystemInstructions(messages);\n\n if (systemInstructions) {\n span.setAttributes({\n [GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE]: systemInstructions,\n });\n }\n\n const filteredLength = Array.isArray(filteredMessages) ? filteredMessages.length : 1;\n span.setAttributes({\n [GEN_AI_INPUT_MESSAGES_ATTRIBUTE]: getTruncatedJsonString(filteredMessages),\n [GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE]: filteredLength,\n });\n}\n\nconst ANTHROPIC_ERROR_TYPE_TO_SPAN_STATUS: Record<string, SpanStatusType> = {\n invalid_request_error: 'invalid_argument',\n authentication_error: 'unauthenticated',\n permission_error: 'permission_denied',\n not_found_error: 'not_found',\n request_too_large: 'failed_precondition',\n rate_limit_error: 'resource_exhausted',\n api_error: 'internal_error',\n overloaded_error: 'unavailable',\n};\n\n/**\n * Map an Anthropic API error type to a SpanStatusType value.\n * @see https://docs.anthropic.com/en/api/errors#error-shapes\n */\nexport function mapAnthropicErrorToStatusMessage(errorType: string | undefined): SpanStatusType {\n if (!errorType) {\n return 'internal_error';\n }\n return ANTHROPIC_ERROR_TYPE_TO_SPAN_STATUS[errorType] || 'internal_error';\n}\n\n/**\n * Capture error information from the response\n * @see https://docs.anthropic.com/en/api/errors#error-shapes\n */\nexport function handleResponseError(span: Span, response: AnthropicAiResponse): void {\n if (response.error) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: mapAnthropicErrorToStatusMessage(response.error.type) });\n\n captureException(response.error, {\n mechanism: {\n handled: false,\n type: 'auto.ai.anthropic.anthropic_error',\n },\n });\n }\n}\n\n/**\n * Include the system prompt in the messages list, if available\n */\nexport function messagesFromParams(params: Record<string, unknown>): unknown[] {\n const { system, messages, input } = params;\n\n const systemMessages = typeof system === 'string' ? [{ role: 'system', content: params.system }] : [];\n\n const inputParamMessages = Array.isArray(input) ? input : input != null ? [input] : undefined;\n\n const messagesParamMessages = Array.isArray(messages) ? messages : messages != null ? [messages] : [];\n\n const userMessages = inputParamMessages ?? messagesParamMessages;\n\n return [...systemMessages, ...userMessages];\n}\n"],"names":["extractSystemInstructions","GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE","GEN_AI_INPUT_MESSAGES_ATTRIBUTE","getTruncatedJsonString","GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE","SPAN_STATUS_ERROR","captureException"],"mappings":";;;;;;;AAYA;AACA;AACA;AACA;AACO,SAAS,oBAAoB,CAAC,IAAI,EAAQ,QAAQ,EAAiB;AAC1E,EAAE,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAA,IAAK,QAAQ,CAAC,MAAA,KAAW,CAAC,EAAE;AACxD,IAAI;AACJ,EAAE;;AAEF,EAAE,MAAM,EAAE,kBAAkB,EAAE,gBAAA,KAAqBA,+BAAyB,CAAC,QAAQ,CAAC;;AAEtF,EAAE,IAAI,kBAAkB,EAAE;AAC1B,IAAI,IAAI,CAAC,aAAa,CAAC;AACvB,MAAM,CAACC,oDAAoC,GAAG,kBAAkB;AAChE,KAAK,CAAC;AACN,EAAE;;AAEF,EAAE,MAAM,cAAA,GAAiB,KAAK,CAAC,OAAO,CAAC,gBAAgB,CAAA,GAAI,gBAAgB,CAAC,MAAA,GAAS,CAAC;AACtF,EAAE,IAAI,CAAC,aAAa,CAAC;AACrB,IAAI,CAACC,+CAA+B,GAAGC,4BAAsB,CAAC,gBAAgB,CAAC;AAC/E,IAAI,CAACC,+DAA+C,GAAG,cAAc;AACrE,GAAG,CAAC;AACJ;;AAEA,MAAM,mCAAmC,G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AM,qBAAqB,KAAK,CAAC,OAAO,CAAC,KAAK,CAAA,GAAI,QAAQ,KAAA,IAAS,IAAA,GAAO,CAAC,KAAK,CAAA,GAAI,SAAS;;AAE/F,EAAE,MAAM,wBAAwB,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAA,GAAI,WAAW,QAAA,IAAY,IAAA,GAAO,CAAC,QAAQ,CAAA,GAAI,EAAE;;AAEvG,EAAE,MAAM,YAAA,GAAe,kBAAA,IAAsB,qBAAqB;;AAElE,EAAE,OAAO,CAAC,GAAG,cAAc,EAAE,GAAG,YAAY,CAAC;AAC7C;;;;;;;"}
1
+ {"version":3,"file":"utils.js","sources":["../../../../src/tracing/anthropic-ai/utils.ts"],"sourcesContent":["import { captureException } from '../../exports';\nimport { SPAN_STATUS_ERROR } from '../../tracing';\nimport type { Span } from '../../types-hoist/span';\nimport type { SpanStatusType } from '../../types-hoist/spanStatus';\nimport {\n GEN_AI_INPUT_MESSAGES_ATTRIBUTE,\n GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE,\n GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE,\n} from '../ai/gen-ai-attributes';\nimport { extractSystemInstructions, getJsonString, getTruncatedJsonString } from '../ai/utils';\nimport type { AnthropicAiResponse } from './types';\n\n/**\n * Set the messages and messages original length attributes.\n * Extracts system instructions before truncation.\n */\nexport function setMessagesAttribute(span: Span, messages: unknown, enableTruncation: boolean): void {\n if (Array.isArray(messages) && messages.length === 0) {\n return;\n }\n\n const { systemInstructions, filteredMessages } = extractSystemInstructions(messages);\n\n if (systemInstructions) {\n span.setAttributes({\n [GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE]: systemInstructions,\n });\n }\n\n const filteredLength = Array.isArray(filteredMessages) ? filteredMessages.length : 1;\n span.setAttributes({\n [GEN_AI_INPUT_MESSAGES_ATTRIBUTE]: enableTruncation\n ? getTruncatedJsonString(filteredMessages)\n : getJsonString(filteredMessages),\n [GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE]: filteredLength,\n });\n}\n\nconst ANTHROPIC_ERROR_TYPE_TO_SPAN_STATUS: Record<string, SpanStatusType> = {\n invalid_request_error: 'invalid_argument',\n authentication_error: 'unauthenticated',\n permission_error: 'permission_denied',\n not_found_error: 'not_found',\n request_too_large: 'failed_precondition',\n rate_limit_error: 'resource_exhausted',\n api_error: 'internal_error',\n overloaded_error: 'unavailable',\n};\n\n/**\n * Map an Anthropic API error type to a SpanStatusType value.\n * @see https://docs.anthropic.com/en/api/errors#error-shapes\n */\nexport function mapAnthropicErrorToStatusMessage(errorType: string | undefined): SpanStatusType {\n if (!errorType) {\n return 'internal_error';\n }\n return ANTHROPIC_ERROR_TYPE_TO_SPAN_STATUS[errorType] || 'internal_error';\n}\n\n/**\n * Capture error information from the response\n * @see https://docs.anthropic.com/en/api/errors#error-shapes\n */\nexport function handleResponseError(span: Span, response: AnthropicAiResponse): void {\n if (response.error) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: mapAnthropicErrorToStatusMessage(response.error.type) });\n\n captureException(response.error, {\n mechanism: {\n handled: false,\n type: 'auto.ai.anthropic.anthropic_error',\n },\n });\n }\n}\n\n/**\n * Include the system prompt in the messages list, if available\n */\nexport function messagesFromParams(params: Record<string, unknown>): unknown[] {\n const { system, messages, input } = params;\n\n const systemMessages = typeof system === 'string' ? [{ role: 'system', content: params.system }] : [];\n\n const inputParamMessages = Array.isArray(input) ? input : input != null ? [input] : undefined;\n\n const messagesParamMessages = Array.isArray(messages) ? messages : messages != null ? [messages] : [];\n\n const userMessages = inputParamMessages ?? messagesParamMessages;\n\n return [...systemMessages, ...userMessages];\n}\n"],"names":["extractSystemInstructions","GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE","GEN_AI_INPUT_MESSAGES_ATTRIBUTE","getTruncatedJsonString","getJsonString","GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE","SPAN_STATUS_ERRO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109
  const dsc = getDynamicSamplingContextFromClient(span.spanContext().traceId, client);
110
110
 
111
111
  // We don't want to have a transaction name in the DSC if the source is "url" because URLs might contain PII
112
- const source = rootSpanAttributes[semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
112
+ // TODO(v11): Only read `SEMANTIC_ATTRIBUTE_SENTRY_SOURCE` again, once we renamed it to `sentry.span.source`
113
+ const source = rootSpanAttributes[semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] ?? rootSpanAttributes['sentry.span.source'];
113
114
 
114
115
  // after JSON conversion, txn.name becomes jsonSpan.description
115
116
  const name = rootSpanJson.description;
@@ -1 +1 @@
1
- {"version":3,"file":"dynamicSamplingContext.js","sources":["../../../src/tracing/dynamicSamplingContext.ts"],"sourcesContent":["import type { Client } from '../client';\nimport { DEFAULT_ENVIRONMENT } from '../constants';\nimport { getClient } from '../currentScopes';\nimport type { Scope } from '../scope';\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE,\n SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE,\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n} from '../semanticAttributes';\nimport type { DynamicSamplingContext } from '../types-hoist/envelope';\nimport type { Span } from '../types-hoist/span';\nimport { baggageHeaderToDynamicSamplingContext, dynamicSamplingContextToSentryBaggageHeader } from '../utils/baggage';\nimport { extractOrgIdFromClient } from '../utils/dsn';\nimport { hasSpansEnabled } from '../utils/hasSpansEnabled';\nimport { addNonEnumerableProperty } from '../utils/object';\nimport { getRootSpan, spanIsSampled, spanToJSON } from '../utils/spanUtils';\nimport { getCapturedScopesOnSpan } from './utils';\n\n/**\n * If you change this value, also update the terser plugin config to\n * avoid minification of the object property!\n */\nconst FROZEN_DSC_FIELD = '_frozenDsc';\n\ntype SpanWithMaybeDsc = Span & {\n [FROZEN_DSC_FIELD]?: Partial<DynamicSamplingContext> | undefined;\n};\n\n/**\n * Freeze the given DSC on the given span.\n */\nexport function freezeDscOnSpan(span: Span, dsc: Partial<DynamicSamplingContext>): void {\n const spanWithMaybeDsc = span as SpanWithMaybeDsc;\n addNonEnumerableProperty(spanWithMaybeDsc, FROZEN_DSC_FIELD, dsc);\n}\n\n/**\n * Creates a dynamic sampling context from a client.\n *\n * Dispatches the `createDsc` lifecycle hook as a side effect.\n */\nexport function getDynamicSamplingContextFromClient(trace_id: string, client: Client): DynamicSamplingContext {\n const options = client.getOptions();\n\n const { publicKey: public_key } = client.getDsn() || {};\n\n // Instead of conditionally adding non-undefined values, we add them and then remove them if needed\n // otherwise, the order of baggage entries changes, which \"breaks\" a bunch of tests etc.\n const dsc: DynamicSamplingContext = {\n environment: options.environment || DEFAULT_ENVIRONMENT,\n release: options.release,\n public_key,\n trace_id,\n org_id: extractOrgIdFromClient(client),\n };\n\n client.emit('createDsc', dsc);\n\n return dsc;\n}\n\n/**\n * Get the dynamic sampling context for the currently active scopes.\n */\nexport function getDynamicSamplingContextFromScope(client: Client, scope: Scope): Partial<DynamicSamplingContext> {\n const propagationContext = scope.getPropagationContext();\n return propagationContext.dsc || getDynamicSamplingContextFromClient(propagationContext.traceId, client);\n}\n\n/**\n * Creates a dynamic sampling context from a span (and client and scope)\n *\n * @param span the span from which a few values like the root span name and sample rate are extracted.\n *\n * @returns a dynamic sampling context\n */\nexport function getDynamicSamplingContextFromSpan(span: Span): Readonly<Partial<DynamicSamplingContext>> {\n const client = getClient();\n if (!client) {\n return {};\n }\n\n const rootSpan = getRootSpan(span);\n const rootSpanJson = spanToJSON(rootSpan);\n const rootSpanAttributes = rootSpanJson.data;\n const traceState = rootSpan.spanContext().traceState;\n\n // The span sample rate that was locally applied to the root span should also always be applied to the DSC, even if the DSC is frozen.\n // This is so that the downstream traces/services can use parentSampleRate in their `tracesSampler` to make consistent sampling decisions across the entire trace.\n const rootSpanSampleRate =\n traceState?.get('sentry.sample_rate') ??\n rootSpanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] ??\n rootSpanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE];\n\n function applyLocalSampleRateToDsc(dsc: Partial<DynamicSamplingContext>): Partial<DynamicSamplingContext> {\n if (typeof rootSpanSampleRate === 'number' || typeof rootSpanSampleRate === 'string') {\n dsc.sample_rate = `${rootSpanSampleRate}`;\n }\n return dsc;\n }\n\n // For core implementation, we freeze the DSC onto the span as a non-enumerable property\n const frozenDsc = (rootSpan as SpanWithMaybeDsc)[FROZEN_DSC_FIELD];\n if (frozenDsc) {\n return applyLocalSampleRateToDsc(frozenDsc);\n }\n\n // For OpenTelemetry, we freeze the DSC on the trace state\n const traceStateDsc = traceState?.get('sentry.dsc');\n\n // If the span has a DSC, we want it to take precedence\n const dscOnTraceState = traceStateDsc && baggageHeaderToDynamicSamplingContext(traceStateDsc);\n\n if (dscOnTraceState) {\n return applyLocalSampleRateToDsc(dscOnTraceState);\n }\n\n // Else, we generate it from the span\n const dsc = getDynamicSamplingContextFromClient(span.spanContext().traceId, client);\n\n // We don't want to have a transaction name in the DSC if the source is \"url\" because URLs might contain PII\n const source = rootSpanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n\n // after JSON conversion, txn.name becomes jsonSpan.description\n const name = rootSpanJson.description;\n if (source !== 'url' && name) {\n dsc.transaction = name;\n }\n\n // How can we even land here with hasSpansEnabled() returning false?\n // Otel creates a Non-recording span in Tracing Without Performance mode when handling incoming requests\n // So we end up with an active span that is not sampled (neither positively nor negatively)\n if (hasSpansEnabled()) {\n dsc.sampled = String(spanIsSampled(rootSpan));\n dsc.sample_rand =\n // In OTEL we store the sample rand on the trace state because we cannot access scopes for NonRecordingSpans\n // The Sentry OTEL SpanSampler takes care of writing the sample rand on the root span\n traceState?.get('sentry.sample_rand') ??\n // On all other platforms we can actually get the scopes from a root span (we use this as a fallback)\n getCapturedScopesOnSpan(rootSpan).scope?.getPropagationContext().sampleRand.toString();\n }\n\n applyLocalSampleRateToDsc(dsc);\n\n client.emit('createDsc', dsc, rootSpan);\n\n return dsc;\n}\n\n/**\n * Convert a Span to a baggage header.\n */\nexport function spanToBaggageHeader(span: Span): string | undefined {\n const dsc = getDynamicSamplingContextFromSpan(span);\n return dynamicSamplingContextToSentryBaggageHeader(dsc);\n}\n"],"names":["addNonEnumerableProperty","DEFAULT_ENVIRONMENT","extractOrgIdFromClient","getClient","getRootSpan","spanToJSON","SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE","SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE","baggageHeaderToDynamicSamplingContext","SEMANTIC_ATTRIBUTE_SENTRY_SOURCE","hasSpansEnabled","spanIsSampled","getCapturedScopesOnSpan","dynamicSamplingContextToSentryBaggageHeader"],"mappings":";;;;;;;;;;;;AAkBA;AACA;AACA;AACA;AACA,MAAM,gBAAA,GAAmB,YAAY;;AAMrC;AACA;AACA;AACO,SAAS,eAAe,CAAC,IAAI,EAAQ,GAAG,EAAyC;AACxF,EAAE,MAAM,gBAAA,GAAmB,IAAA;AAC3B,EAAEA,+BAAwB,CAAC,gBAAgB,EAAE,gBAAgB,EAAE,GAAG,CAAC;AACnE;;AAEA;AACA;AACA;AACA;AACA;AACO,SAAS,mCAAmC,CAAC,QAAQ,EAAU,MAAM,EAAkC;AAC9G,EAAE,MAAM,OAAA,GAAU,MAAM,CAAC,UAAU,EAAE;;AAErC,EAAE,MAAM,EAAE,SAAS,EAAE,YAAW,GAAI,MAAM,CAAC,MAAM,EAAC,IAAK,EAAE;;AAEzD;AACA;AACA,EAAE,MAAM,GAAG,GAA2B;AACtC,IAAI,WAAW,EAAE,OAAO,CAAC,WAAA,IAAeC,6BAAmB;AAC3D,IAAI,OAAO,EAAE,OAAO,CAAC,OAAO;AAC5B,IAAI,UAAU;AACd,IAAI,QAAQ;AACZ,IAAI,MAAM,EAAEC,0BAAsB,CAAC,MAAM,CAAC;AAC1C,GAAG;;AAEH,EAA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,CAAA,GAAA,CAAA;AACA;;;;;;;;"}
1
+ {"version":3,"file":"dynamicSamplingContext.js","sources":["../../../src/tracing/dynamicSamplingContext.ts"],"sourcesContent":["import type { Client } from '../client';\nimport { DEFAULT_ENVIRONMENT } from '../constants';\nimport { getClient } from '../currentScopes';\nimport type { Scope } from '../scope';\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE,\n SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE,\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n} from '../semanticAttributes';\nimport type { DynamicSamplingContext } from '../types-hoist/envelope';\nimport type { Span } from '../types-hoist/span';\nimport { baggageHeaderToDynamicSamplingContext, dynamicSamplingContextToSentryBaggageHeader } from '../utils/baggage';\nimport { extractOrgIdFromClient } from '../utils/dsn';\nimport { hasSpansEnabled } from '../utils/hasSpansEnabled';\nimport { addNonEnumerableProperty } from '../utils/object';\nimport { getRootSpan, spanIsSampled, spanToJSON } from '../utils/spanUtils';\nimport { getCapturedScopesOnSpan } from './utils';\n\n/**\n * If you change this value, also update the terser plugin config to\n * avoid minification of the object property!\n */\nconst FROZEN_DSC_FIELD = '_frozenDsc';\n\ntype SpanWithMaybeDsc = Span & {\n [FROZEN_DSC_FIELD]?: Partial<DynamicSamplingContext> | undefined;\n};\n\n/**\n * Freeze the given DSC on the given span.\n */\nexport function freezeDscOnSpan(span: Span, dsc: Partial<DynamicSamplingContext>): void {\n const spanWithMaybeDsc = span as SpanWithMaybeDsc;\n addNonEnumerableProperty(spanWithMaybeDsc, FROZEN_DSC_FIELD, dsc);\n}\n\n/**\n * Creates a dynamic sampling context from a client.\n *\n * Dispatches the `createDsc` lifecycle hook as a side effect.\n */\nexport function getDynamicSamplingContextFromClient(trace_id: string, client: Client): DynamicSamplingContext {\n const options = client.getOptions();\n\n const { publicKey: public_key } = client.getDsn() || {};\n\n // Instead of conditionally adding non-undefined values, we add them and then remove them if needed\n // otherwise, the order of baggage entries changes, which \"breaks\" a bunch of tests etc.\n const dsc: DynamicSamplingContext = {\n environment: options.environment || DEFAULT_ENVIRONMENT,\n release: options.release,\n public_key,\n trace_id,\n org_id: extractOrgIdFromClient(client),\n };\n\n client.emit('createDsc', dsc);\n\n return dsc;\n}\n\n/**\n * Get the dynamic sampling context for the currently active scopes.\n */\nexport function getDynamicSamplingContextFromScope(client: Client, scope: Scope): Partial<DynamicSamplingContext> {\n const propagationContext = scope.getPropagationContext();\n return propagationContext.dsc || getDynamicSamplingContextFromClient(propagationContext.traceId, client);\n}\n\n/**\n * Creates a dynamic sampling context from a span (and client and scope)\n *\n * @param span the span from which a few values like the root span name and sample rate are extracted.\n *\n * @returns a dynamic sampling context\n */\nexport function getDynamicSamplingContextFromSpan(span: Span): Readonly<Partial<DynamicSamplingContext>> {\n const client = getClient();\n if (!client) {\n return {};\n }\n\n const rootSpan = getRootSpan(span);\n const rootSpanJson = spanToJSON(rootSpan);\n const rootSpanAttributes = rootSpanJson.data;\n const traceState = rootSpan.spanContext().traceState;\n\n // The span sample rate that was locally applied to the root span should also always be applied to the DSC, even if the DSC is frozen.\n // This is so that the downstream traces/services can use parentSampleRate in their `tracesSampler` to make consistent sampling decisions across the entire trace.\n const rootSpanSampleRate =\n traceState?.get('sentry.sample_rate') ??\n rootSpanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] ??\n rootSpanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE];\n\n function applyLocalSampleRateToDsc(dsc: Partial<DynamicSamplingContext>): Partial<DynamicSamplingContext> {\n if (typeof rootSpanSampleRate === 'number' || typeof rootSpanSampleRate === 'string') {\n dsc.sample_rate = `${rootSpanSampleRate}`;\n }\n return dsc;\n }\n\n // For core implementation, we freeze the DSC onto the span as a non-enumerable property\n const frozenDsc = (rootSpan as SpanWithMaybeDsc)[FROZEN_DSC_FIELD];\n if (frozenDsc) {\n return applyLocalSampleRateToDsc(frozenDsc);\n }\n\n // For OpenTelemetry, we freeze the DSC on the trace state\n const traceStateDsc = traceState?.get('sentry.dsc');\n\n // If the span has a DSC, we want it to take precedence\n const dscOnTraceState = traceStateDsc && baggageHeaderToDynamicSamplingContext(traceStateDsc);\n\n if (dscOnTraceState) {\n return applyLocalSampleRateToDsc(dscOnTraceState);\n }\n\n // Else, we generate it from the span\n const dsc = getDynamicSamplingContextFromClient(span.spanContext().traceId, client);\n\n // We don't want to have a transaction name in the DSC if the source is \"url\" because URLs might contain PII\n // TODO(v11): Only read `SEMANTIC_ATTRIBUTE_SENTRY_SOURCE` again, once we renamed it to `sentry.span.source`\n const source = rootSpanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] ?? rootSpanAttributes['sentry.span.source'];\n\n // after JSON conversion, txn.name becomes jsonSpan.description\n const name = rootSpanJson.description;\n if (source !== 'url' && name) {\n dsc.transaction = name;\n }\n\n // How can we even land here with hasSpansEnabled() returning false?\n // Otel creates a Non-recording span in Tracing Without Performance mode when handling incoming requests\n // So we end up with an active span that is not sampled (neither positively nor negatively)\n if (hasSpansEnabled()) {\n dsc.sampled = String(spanIsSampled(rootSpan));\n dsc.sample_rand =\n // In OTEL we store the sample rand on the trace state because we cannot access scopes for NonRecordingSpans\n // The Sentry OTEL SpanSampler takes care of writing the sample rand on the root span\n traceState?.get('sentry.sample_rand') ??\n // On all other platforms we can actually get the scopes from a root span (we use this as a fallback)\n getCapturedScopesOnSpan(rootSpan).scope?.getPropagationContext().sampleRand.toString();\n }\n\n applyLocalSampleRateToDsc(dsc);\n\n client.emit('createDsc', dsc, rootSpan);\n\n return dsc;\n}\n\n/**\n * Convert a Span to a baggage header.\n */\nexport function spanToBaggageHeader(span: Span): string | undefined {\n const dsc = getDynamicSamplingContextFromSpan(span);\n return dynamicSamplingContextToSentryBaggageHeader(dsc);\n}\n"],"names":["addNonEnumerableProperty","DEFAULT_ENVIRONMENT","extractOrgIdFromClient","getClient","getRootSpan","spanToJSON","SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE","SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE","baggageHeaderToDynamicSamplingContext","SEMANTIC_ATTRIBUTE_SENTRY_SOURCE","hasSpansEnabled","spanIsSampled","getCapturedScopesOnSpan","dynamicSamplingContextToSentryBaggageHeader"],"mappings":";;;;;;;;;;;;AAkBA;AACA;AACA;AACA;AACA,MAAM,gBAAA,GAAmB,YAAY;;AAMrC;AACA;AACA;AACO,SAAS,eAAe,CAAC,IAAI,EAAQ,GAAG,EAAyC;AACxF,EAAE,MAAM,gBAAA,GAAmB,IAAA;AAC3B,EAAEA,+BAAwB,CAAC,gBAAgB,EAAE,gBAAgB,EAAE,GAAG,CAAC;AACnE;;AAEA;AACA;AACA;AACA;AACA;AACO,SAAS,mCAAmC,CAAC,QAAQ,EAAU,MAAM,EAAkC;AAC9G,EAAE,MAAM,OAAA,GAAU,MAAM,CAAC,UAAU,EAAE;;AAErC,EAAE,MAAM,EAAE,SAAS,EAAE,YAAW,GAAI,MAAM,CAAC,MAAM,EAAC,IAAK,EAAE;;AAEzD;AACA;AACA,EAAE,MAAM,GAAG,GAA2B;AACtC,IAAI,WAAW,EAAE,OAAO,CAAC,WAAA,IAAeC,6BAAmB;AAC3D,IAAI,OAAO,EAAE,OAAO,CAAC,OAAO;AAC5B,IAAI,UAAU;AACd,IAAI,QAAQ;AACZ,IAAI,MAAM,EAAEC,0BAAsB,CAAC,MAAM,CAAC;AAC1C,GAAG;;AAEH,EAAE,MAAM,CAAC,IAAI,CAAC,WAAW,EAAE,GAAG,CAAC;;AAE/B,EAAE,OAAO,GAAG;AACZ;;AAEA;AACA;AACA;AACO,SAAS,kCAAkC,CAAC,MAAM,EAAU,KAAK,EAA0C;AAClH,EAAE,MAAM,kBAAA,GAAqB,KAAK,CAAC,qBAAqB,EAAE;AAC1D,EAAE,OAAO,kBAAkB,CAAC,GAAA,IAAO,mCAAmC,CAAC,kBAAkB,CA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,CAAA;AACA,EAAA;;AAEA;AACA,EAAA,MAAA,GAAA,GAAA,mCAAA,CAAA,IAAA,CAAA,WAAA,EAAA,CAAA,OAAA,EAAA,MAAA,CAAA;;AAEA;AACA;AACA,EAAA,MAAA,MAAA,GAAA,kBAAA,CAAAC,mDAAA,CAAA,IAAA,kBAAA,CAAA,oBAAA,CAAA;;AAEA;AACA,EAAA,MAAA,IAAA,GAAA,YAAA,CAAA,WAAA;AACA,EAAA,IAAA,MAAA,KAAA,KAAA,IAAA,IAAA,EAAA;AACA,IAAA,GAAA,CAAA,WAAA,GAAA,IAAA;AACA,EAAA;;AAEA;AACA;AACA;AACA,EAAA,IAAAC,+BAAA,EAAA,EAAA;AACA,IAAA,GAAA,CAAA,OAAA,GAAA,MAAA,CAAAC,uBAAA,CAAA,QAAA,CAAA,CAAA;AACA,IAAA,GAAA,CAAA,WAAA;AACA;AACA;AACA,MAAA,UAAA,EAAA,GAAA,CAAA,oBAAA,CAAA;AACA;AACA,MAAAC,6BAAA,CAAA,QAAA,CAAA,CAAA,KAAA,EAAA,qBAAA,EAAA,CAAA,UAAA,CAAA,QAAA,EAAA;AACA,EAAA;;AAEA,EAAA,yBAAA,CAAA,GAAA,CAAA;;AAEA,EAAA,MAAA,CAAA,IAAA,CAAA,WAAA,EAAA,GAAA,EAAA,QAAA,CAAA;;AAEA,EAAA,OAAA,GAAA;AACA;;AAEA;AACA;AACA;AACA,SAAA,mBAAA,CAAA,IAAA,EAAA;AACA,EAAA,MAAA,GAAA,GAAA,iCAAA,CAAA,IAAA,CAAA;AACA,EAAA,OAAAC,mDAAA,CAAA,GAAA,CAAA;AACA;;;;;;;;"}
@@ -10,19 +10,14 @@ const GOOGLE_GENAI_METHOD_REGISTRY = {
10
10
  'models.generateContent': { operation: 'generate_content' },
11
11
  'models.generateContentStream': { operation: 'generate_content', streaming: true },
12
12
  'models.embedContent': { operation: 'embeddings' },
13
- 'chats.create': { operation: 'chat' },
14
- // chat.* paths are built by createDeepProxy when it proxies the chat instance with CHAT_PATH as base
13
+ 'chats.create': { proxyResultPath: 'chat' },
15
14
  'chat.sendMessage': { operation: 'chat' },
16
15
  'chat.sendMessageStream': { operation: 'chat', streaming: true },
17
16
  } ;
18
17
 
19
18
  // Constants for internal use
20
19
  const GOOGLE_GENAI_SYSTEM_NAME = 'google_genai';
21
- const CHATS_CREATE_METHOD = 'chats.create';
22
- const CHAT_PATH = 'chat';
23
20
 
24
- exports.CHATS_CREATE_METHOD = CHATS_CREATE_METHOD;
25
- exports.CHAT_PATH = CHAT_PATH;
26
21
  exports.GOOGLE_GENAI_INTEGRATION_NAME = GOOGLE_GENAI_INTEGRATION_NAME;
27
22
  exports.GOOGLE_GENAI_METHOD_REGISTRY = GOOGLE_GENAI_METHOD_REGISTRY;
28
23
  exports.GOOGLE_GENAI_SYSTEM_NAME = GOOGLE_GENAI_SYSTEM_NAME;
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","sources":["../../../../src/tracing/google-genai/constants.ts"],"sourcesContent":["import type { InstrumentedMethodRegistry } from '../ai/utils';\n\nexport const GOOGLE_GENAI_INTEGRATION_NAME = 'Google_GenAI';\n\n// https://ai.google.dev/api/rest/v1/models/generateContent\n// https://ai.google.dev/api/rest/v1/chats/sendMessage\n// https://googleapis.github.io/js-genai/release_docs/classes/models.Models.html#generatecontentstream\n// https://googleapis.github.io/js-genai/release_docs/classes/chats.Chat.html#sendmessagestream\nexport const GOOGLE_GENAI_METHOD_REGISTRY = {\n 'models.generateContent': { operation: 'generate_content' },\n 'models.generateContentStream': { operation: 'generate_content', streaming: true },\n 'models.embedContent': { operation: 'embeddings' },\n 'chats.create': { operation: 'chat' },\n // chat.* paths are built by createDeepProxy when it proxies the chat instance with CHAT_PATH as base\n 'chat.sendMessage': { operation: 'chat' },\n 'chat.sendMessageStream': { operation: 'chat', streaming: true },\n} as const satisfies InstrumentedMethodRegistry;\n\n// Constants for internal use\nexport const GOOGLE_GENAI_SYSTEM_NAME = 'google_genai';\nexport const CHATS_CREATE_METHOD = 'chats.create';\nexport const CHAT_PATH = 'chat';\n"],"names":[],"mappings":";;AAEO,MAAM,6BAAA,GAAgC;;AAE7C;AACA;AACA;AACA;AACO,MAAM,+BAA+B;AAC5C,EAAE,wBAAwB,EAAE,EAAE,SAAS,EAAE,oBAAoB;AAC7D,EAAE,8BAA8B,EAAE,EAAE,SAAS,EAAE,kBAAkB,EAAE,SAAS,EAAE,IAAA,EAAM;AACpF,EAAE,qBAAqB,EAAE,EAAE,SAAS,EAAE,cAAc;AACpD,EAAE,cAAc,EAAE,EAAE,SAAS,EAAE,QAAQ;AACvC;AACA,EAAE,kBAAkB,EAAE,EAAE,SAAS,EAAE,QAAQ;AAC3C,EAAE,wBAAwB,EAAE,EAAE,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,IAAA,EAAM;AAClE,CAAA;;AAEA;AACO,MAAM,wBAAA,GAA2B;AACjC,MAAM,mBAAA,GAAsB;AAC5B,MAAM,SAAA,GAAY;;;;;;;;"}
1
+ {"version":3,"file":"constants.js","sources":["../../../../src/tracing/google-genai/constants.ts"],"sourcesContent":["import type { InstrumentedMethodRegistry } from '../ai/utils';\n\nexport const GOOGLE_GENAI_INTEGRATION_NAME = 'Google_GenAI';\n\n// https://ai.google.dev/api/rest/v1/models/generateContent\n// https://ai.google.dev/api/rest/v1/chats/sendMessage\n// https://googleapis.github.io/js-genai/release_docs/classes/models.Models.html#generatecontentstream\n// https://googleapis.github.io/js-genai/release_docs/classes/chats.Chat.html#sendmessagestream\nexport const GOOGLE_GENAI_METHOD_REGISTRY = {\n 'models.generateContent': { operation: 'generate_content' },\n 'models.generateContentStream': { operation: 'generate_content', streaming: true },\n 'models.embedContent': { operation: 'embeddings' },\n 'chats.create': { proxyResultPath: 'chat' },\n 'chat.sendMessage': { operation: 'chat' },\n 'chat.sendMessageStream': { operation: 'chat', streaming: true },\n} as const satisfies InstrumentedMethodRegistry;\n\n// Constants for internal use\nexport const GOOGLE_GENAI_SYSTEM_NAME = 'google_genai';\n"],"names":[],"mappings":";;AAEO,MAAM,6BAAA,GAAgC;;AAE7C;AACA;AACA;AACA;AACO,MAAM,+BAA+B;AAC5C,EAAE,wBAAwB,EAAE,EAAE,SAAS,EAAE,oBAAoB;AAC7D,EAAE,8BAA8B,EAAE,EAAE,SAAS,EAAE,kBAAkB,EAAE,SAAS,EAAE,IAAA,EAAM;AACpF,EAAE,qBAAqB,EAAE,EAAE,SAAS,EAAE,cAAc;AACpD,EAAE,cAAc,EAAE,EAAE,eAAe,EAAE,QAAQ;AAC7C,EAAE,kBAAkB,EAAE,EAAE,SAAS,EAAE,QAAQ;AAC3C,EAAE,wBAAwB,EAAE,EAAE,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,IAAA,EAAM;AAClE,CAAA;;AAEA;AACO,MAAM,wBAAA,GAA2B;;;;;;"}