@sentry/server-utils 11.13.0 → 11.15.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 (328) hide show
  1. package/build/cjs/chunks/config.js +19 -5
  2. package/build/cjs/chunks/config.js.map +1 -1
  3. package/build/cjs/chunks/exports.js +593 -238
  4. package/build/cjs/chunks/exports.js.map +1 -1
  5. package/build/cjs/chunks/moduleInjectedTransform.js +6 -5
  6. package/build/cjs/chunks/moduleInjectedTransform.js.map +1 -1
  7. package/build/cjs/index.js +1186 -182
  8. package/build/cjs/index.js.map +1 -1
  9. package/build/cjs/orchestrion/bundler/rollup.js +4 -4
  10. package/build/cjs/orchestrion/bundler/rollup.js.map +1 -1
  11. package/build/esm/ai/anthropic-ai/index.js +32 -56
  12. package/build/esm/ai/anthropic-ai/index.js.map +1 -1
  13. package/build/esm/ai/anthropic-ai/streaming.js +10 -6
  14. package/build/esm/ai/anthropic-ai/streaming.js.map +1 -1
  15. package/build/esm/ai/anthropic-ai/tool-runner.js +18 -3
  16. package/build/esm/ai/anthropic-ai/tool-runner.js.map +1 -1
  17. package/build/esm/ai/anthropic-ai/utils.js +41 -3
  18. package/build/esm/ai/anthropic-ai/utils.js.map +1 -1
  19. package/build/esm/ai/core/span-hooks.js +23 -0
  20. package/build/esm/ai/core/span-hooks.js.map +1 -0
  21. package/build/esm/ai/core/time-to-first-chunk.js +14 -0
  22. package/build/esm/ai/core/time-to-first-chunk.js.map +1 -0
  23. package/build/esm/ai/core/utils.js +29 -3
  24. package/build/esm/ai/core/utils.js.map +1 -1
  25. package/build/esm/ai/flue/index.js +15 -12
  26. package/build/esm/ai/flue/index.js.map +1 -1
  27. package/build/esm/ai/flue/utils.js +24 -17
  28. package/build/esm/ai/flue/utils.js.map +1 -1
  29. package/build/esm/ai/google-genai/constants.js +2 -1
  30. package/build/esm/ai/google-genai/constants.js.map +1 -1
  31. package/build/esm/ai/google-genai/decisions.js +25 -0
  32. package/build/esm/ai/google-genai/decisions.js.map +1 -0
  33. package/build/esm/ai/google-genai/index.js +35 -11
  34. package/build/esm/ai/google-genai/index.js.map +1 -1
  35. package/build/esm/ai/google-genai/streaming.js +6 -2
  36. package/build/esm/ai/google-genai/streaming.js.map +1 -1
  37. package/build/esm/ai/langchain/embeddings.js +5 -2
  38. package/build/esm/ai/langchain/embeddings.js.map +1 -1
  39. package/build/esm/ai/langchain/index.js +82 -24
  40. package/build/esm/ai/langchain/index.js.map +1 -1
  41. package/build/esm/ai/langchain/utils.js +9 -1
  42. package/build/esm/ai/langchain/utils.js.map +1 -1
  43. package/build/esm/ai/langgraph/agent-span.js +13 -5
  44. package/build/esm/ai/langgraph/agent-span.js.map +1 -1
  45. package/build/esm/ai/langgraph/index.js +13 -15
  46. package/build/esm/ai/langgraph/index.js.map +1 -1
  47. package/build/esm/ai/langgraph/stream.js +4 -3
  48. package/build/esm/ai/langgraph/stream.js.map +1 -1
  49. package/build/esm/ai/langgraph/utils.js +17 -8
  50. package/build/esm/ai/langgraph/utils.js.map +1 -1
  51. package/build/esm/ai/mastra/classifier-evaluation.js.map +1 -1
  52. package/build/esm/ai/mastra/index.js +33 -16
  53. package/build/esm/ai/mastra/index.js.map +1 -1
  54. package/build/esm/ai/mastra/utils.js +3 -5
  55. package/build/esm/ai/mastra/utils.js.map +1 -1
  56. package/build/esm/ai/mistral/index.js +28 -13
  57. package/build/esm/ai/mistral/index.js.map +1 -1
  58. package/build/esm/ai/mistral/streaming.js +6 -8
  59. package/build/esm/ai/mistral/streaming.js.map +1 -1
  60. package/build/esm/ai/mistral/utils.js +9 -1
  61. package/build/esm/ai/mistral/utils.js.map +1 -1
  62. package/build/esm/ai/openai/index.js +19 -8
  63. package/build/esm/ai/openai/index.js.map +1 -1
  64. package/build/esm/ai/openai/streaming.js +7 -2
  65. package/build/esm/ai/openai/streaming.js.map +1 -1
  66. package/build/esm/ai/pi-ai/chat.js +18 -1
  67. package/build/esm/ai/pi-ai/chat.js.map +1 -1
  68. package/build/esm/ai/pi-ai/recording.js +34 -15
  69. package/build/esm/ai/pi-ai/recording.js.map +1 -1
  70. package/build/esm/ai/pi-durable/index.js +7 -2
  71. package/build/esm/ai/pi-durable/index.js.map +1 -1
  72. package/build/esm/ai/pi-durable/runs.js.map +1 -1
  73. package/build/esm/ai/pi-durable/tools.js +18 -3
  74. package/build/esm/ai/pi-durable/tools.js.map +1 -1
  75. package/build/esm/ai/typesafe/index.js +14 -6
  76. package/build/esm/ai/typesafe/index.js.map +1 -1
  77. package/build/esm/ai/vercel-ai/index.js +3 -1
  78. package/build/esm/ai/vercel-ai/index.js.map +1 -1
  79. package/build/esm/ai/workers-ai/index.js +32 -14
  80. package/build/esm/ai/workers-ai/index.js.map +1 -1
  81. package/build/esm/ai/workers-ai/streaming.js +8 -10
  82. package/build/esm/ai/workers-ai/streaming.js.map +1 -1
  83. package/build/esm/cron/common.js +16 -0
  84. package/build/esm/cron/common.js.map +1 -0
  85. package/build/esm/cron/cron.js +82 -0
  86. package/build/esm/cron/cron.js.map +1 -0
  87. package/build/esm/cron/index.js +13 -0
  88. package/build/esm/cron/index.js.map +1 -0
  89. package/build/esm/cron/node-cron.js +66 -0
  90. package/build/esm/cron/node-cron.js.map +1 -0
  91. package/build/esm/cron/node-schedule.js +43 -0
  92. package/build/esm/cron/node-schedule.js.map +1 -0
  93. package/build/esm/index.js +6 -1
  94. package/build/esm/index.js.map +1 -1
  95. package/build/esm/integrations/anthropic.js +25 -16
  96. package/build/esm/integrations/anthropic.js.map +1 -1
  97. package/build/esm/integrations/aws-sdk/index.js +1 -0
  98. package/build/esm/integrations/aws-sdk/index.js.map +1 -1
  99. package/build/esm/integrations/aws-sdk/services/ServicesExtensions.js +3 -0
  100. package/build/esm/integrations/aws-sdk/services/ServicesExtensions.js.map +1 -1
  101. package/build/esm/integrations/aws-sdk/services/bedrock-runtime.js +45 -12
  102. package/build/esm/integrations/aws-sdk/services/bedrock-runtime.js.map +1 -1
  103. package/build/esm/integrations/bullmq/contextManager.js +45 -0
  104. package/build/esm/integrations/bullmq/contextManager.js.map +1 -0
  105. package/build/esm/integrations/bullmq/index.js +44 -0
  106. package/build/esm/integrations/bullmq/index.js.map +1 -0
  107. package/build/esm/integrations/bullmq/meter.js +86 -0
  108. package/build/esm/integrations/bullmq/meter.js.map +1 -0
  109. package/build/esm/integrations/bullmq/span.js +114 -0
  110. package/build/esm/integrations/bullmq/span.js.map +1 -0
  111. package/build/esm/integrations/bullmq/tracer.js +62 -0
  112. package/build/esm/integrations/bullmq/tracer.js.map +1 -0
  113. package/build/esm/integrations/cron.js +2 -2
  114. package/build/esm/integrations/cron.js.map +1 -1
  115. package/build/esm/integrations/express/instrumentation.js +10 -1
  116. package/build/esm/integrations/express/instrumentation.js.map +1 -1
  117. package/build/esm/integrations/google-genai.js +26 -14
  118. package/build/esm/integrations/google-genai.js.map +1 -1
  119. package/build/esm/integrations/langgraph.js +5 -7
  120. package/build/esm/integrations/langgraph.js.map +1 -1
  121. package/build/esm/integrations/mastra-classifier.js +1 -1
  122. package/build/esm/integrations/mastra-classifier.js.map +1 -1
  123. package/build/esm/integrations/mistral.js +15 -5
  124. package/build/esm/integrations/mistral.js.map +1 -1
  125. package/build/esm/integrations/node-cron.js +5 -4
  126. package/build/esm/integrations/node-cron.js.map +1 -1
  127. package/build/esm/integrations/node-schedule.js +2 -2
  128. package/build/esm/integrations/node-schedule.js.map +1 -1
  129. package/build/esm/integrations/openai-compatible.js +16 -8
  130. package/build/esm/integrations/openai-compatible.js.map +1 -1
  131. package/build/esm/integrations/openai.js +16 -8
  132. package/build/esm/integrations/openai.js.map +1 -1
  133. package/build/esm/integrations/pi-ai.js +39 -18
  134. package/build/esm/integrations/pi-ai.js.map +1 -1
  135. package/build/esm/integrations/pino.js +131 -0
  136. package/build/esm/integrations/pino.js.map +1 -0
  137. package/build/esm/integrations/typesafe.js +17 -3
  138. package/build/esm/integrations/typesafe.js.map +1 -1
  139. package/build/esm/integrations/vercel-ai/index.js.map +1 -1
  140. package/build/esm/integrations/vercel-ai/util.js +3 -2
  141. package/build/esm/integrations/vercel-ai/util.js.map +1 -1
  142. package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js +53 -18
  143. package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -1
  144. package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js +22 -16
  145. package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js.map +1 -1
  146. package/build/esm/integrations/winston.js +90 -0
  147. package/build/esm/integrations/winston.js.map +1 -0
  148. package/build/esm/orchestrion/bundler/moduleInjectedTransform.js +6 -5
  149. package/build/esm/orchestrion/bundler/moduleInjectedTransform.js.map +1 -1
  150. package/build/esm/orchestrion/bundler/rollup.js +4 -4
  151. package/build/esm/orchestrion/bundler/rollup.js.map +1 -1
  152. package/build/esm/orchestrion/config/google-genai.js +19 -5
  153. package/build/esm/orchestrion/config/google-genai.js.map +1 -1
  154. package/build/esm/orchestrion/detect.js +1 -1
  155. package/build/esm/orchestrion/detect.js.map +1 -1
  156. package/build/esm/package.json +1 -1
  157. package/build/esm/utils/cronMonitoring.js +128 -50
  158. package/build/esm/utils/cronMonitoring.js.map +1 -1
  159. package/build/types/ai/anthropic-ai/index.d.ts +1 -5
  160. package/build/types/ai/anthropic-ai/index.d.ts.map +1 -1
  161. package/build/types/ai/anthropic-ai/streaming.d.ts +3 -2
  162. package/build/types/ai/anthropic-ai/streaming.d.ts.map +1 -1
  163. package/build/types/ai/anthropic-ai/tool-runner.d.ts.map +1 -1
  164. package/build/types/ai/anthropic-ai/types.d.ts +24 -3
  165. package/build/types/ai/anthropic-ai/types.d.ts.map +1 -1
  166. package/build/types/ai/anthropic-ai/utils.d.ts +2 -3
  167. package/build/types/ai/anthropic-ai/utils.d.ts.map +1 -1
  168. package/build/types/ai/core/span-hooks.d.ts +31 -0
  169. package/build/types/ai/core/span-hooks.d.ts.map +1 -0
  170. package/build/types/ai/core/time-to-first-chunk.d.ts +7 -0
  171. package/build/types/ai/core/time-to-first-chunk.d.ts.map +1 -0
  172. package/build/types/ai/core/utils.d.ts +30 -1
  173. package/build/types/ai/core/utils.d.ts.map +1 -1
  174. package/build/types/ai/flue/index.d.ts +13 -5
  175. package/build/types/ai/flue/index.d.ts.map +1 -1
  176. package/build/types/ai/flue/types.d.ts +20 -2
  177. package/build/types/ai/flue/types.d.ts.map +1 -1
  178. package/build/types/ai/flue/utils.d.ts +5 -9
  179. package/build/types/ai/flue/utils.d.ts.map +1 -1
  180. package/build/types/ai/google-genai/constants.d.ts +3 -0
  181. package/build/types/ai/google-genai/constants.d.ts.map +1 -1
  182. package/build/types/ai/google-genai/decisions.d.ts +8 -0
  183. package/build/types/ai/google-genai/decisions.d.ts.map +1 -0
  184. package/build/types/ai/google-genai/index.d.ts +3 -1
  185. package/build/types/ai/google-genai/index.d.ts.map +1 -1
  186. package/build/types/ai/google-genai/streaming.d.ts +2 -1
  187. package/build/types/ai/google-genai/streaming.d.ts.map +1 -1
  188. package/build/types/ai/google-genai/types.d.ts +17 -3
  189. package/build/types/ai/google-genai/types.d.ts.map +1 -1
  190. package/build/types/ai/langchain/index.d.ts.map +1 -1
  191. package/build/types/ai/langchain/types.d.ts +49 -3
  192. package/build/types/ai/langchain/types.d.ts.map +1 -1
  193. package/build/types/ai/langchain/utils.d.ts +6 -0
  194. package/build/types/ai/langchain/utils.d.ts.map +1 -1
  195. package/build/types/ai/langgraph/agent-span.d.ts +4 -1
  196. package/build/types/ai/langgraph/agent-span.d.ts.map +1 -1
  197. package/build/types/ai/langgraph/index.d.ts +1 -1
  198. package/build/types/ai/langgraph/index.d.ts.map +1 -1
  199. package/build/types/ai/langgraph/stream.d.ts.map +1 -1
  200. package/build/types/ai/langgraph/types.d.ts +14 -3
  201. package/build/types/ai/langgraph/types.d.ts.map +1 -1
  202. package/build/types/ai/langgraph/utils.d.ts +3 -0
  203. package/build/types/ai/langgraph/utils.d.ts.map +1 -1
  204. package/build/types/ai/mastra/classifier-evaluation.d.ts +3 -3
  205. package/build/types/ai/mastra/classifier-evaluation.d.ts.map +1 -1
  206. package/build/types/ai/mastra/index.d.ts +17 -3
  207. package/build/types/ai/mastra/index.d.ts.map +1 -1
  208. package/build/types/ai/mastra/types.d.ts +2 -0
  209. package/build/types/ai/mastra/types.d.ts.map +1 -1
  210. package/build/types/ai/mastra/utils.d.ts.map +1 -1
  211. package/build/types/ai/mistral/index.d.ts.map +1 -1
  212. package/build/types/ai/mistral/streaming.d.ts +2 -1
  213. package/build/types/ai/mistral/streaming.d.ts.map +1 -1
  214. package/build/types/ai/mistral/types.d.ts +14 -3
  215. package/build/types/ai/mistral/types.d.ts.map +1 -1
  216. package/build/types/ai/mistral/utils.d.ts +5 -0
  217. package/build/types/ai/mistral/utils.d.ts.map +1 -1
  218. package/build/types/ai/openai/index.d.ts.map +1 -1
  219. package/build/types/ai/openai/streaming.d.ts +3 -1
  220. package/build/types/ai/openai/streaming.d.ts.map +1 -1
  221. package/build/types/ai/openai/types.d.ts +14 -3
  222. package/build/types/ai/openai/types.d.ts.map +1 -1
  223. package/build/types/ai/pi-ai/chat.d.ts +7 -1
  224. package/build/types/ai/pi-ai/chat.d.ts.map +1 -1
  225. package/build/types/ai/pi-ai/recording.d.ts +21 -9
  226. package/build/types/ai/pi-ai/recording.d.ts.map +1 -1
  227. package/build/types/ai/pi-ai/types.d.ts +16 -0
  228. package/build/types/ai/pi-ai/types.d.ts.map +1 -1
  229. package/build/types/ai/pi-durable/index.d.ts +12 -3
  230. package/build/types/ai/pi-durable/index.d.ts.map +1 -1
  231. package/build/types/ai/pi-durable/runs.d.ts +2 -0
  232. package/build/types/ai/pi-durable/runs.d.ts.map +1 -1
  233. package/build/types/ai/pi-durable/tools.d.ts +4 -3
  234. package/build/types/ai/pi-durable/tools.d.ts.map +1 -1
  235. package/build/types/ai/pi-durable/types.d.ts +15 -0
  236. package/build/types/ai/pi-durable/types.d.ts.map +1 -1
  237. package/build/types/ai/typesafe/index.d.ts +10 -2
  238. package/build/types/ai/typesafe/index.d.ts.map +1 -1
  239. package/build/types/ai/vercel-ai/index.d.ts.map +1 -1
  240. package/build/types/ai/vercel-ai/vercel-ai-attributes.d.ts +3 -0
  241. package/build/types/ai/vercel-ai/vercel-ai-attributes.d.ts.map +1 -1
  242. package/build/types/ai/workers-ai/index.d.ts.map +1 -1
  243. package/build/types/ai/workers-ai/streaming.d.ts +2 -1
  244. package/build/types/ai/workers-ai/streaming.d.ts.map +1 -1
  245. package/build/types/ai/workers-ai/types.d.ts +18 -3
  246. package/build/types/ai/workers-ai/types.d.ts.map +1 -1
  247. package/build/types/cron/common.d.ts +8 -0
  248. package/build/types/cron/common.d.ts.map +1 -0
  249. package/build/types/cron/cron.d.ts +45 -0
  250. package/build/types/cron/cron.d.ts.map +1 -0
  251. package/build/types/cron/index.d.ts +10 -0
  252. package/build/types/cron/index.d.ts.map +1 -0
  253. package/build/types/cron/node-cron.d.ts +33 -0
  254. package/build/types/cron/node-cron.d.ts.map +1 -0
  255. package/build/types/cron/node-schedule.d.ts +19 -0
  256. package/build/types/cron/node-schedule.d.ts.map +1 -0
  257. package/build/types/index.d.ts +5 -0
  258. package/build/types/index.d.ts.map +1 -1
  259. package/build/types/integrations/anthropic.d.ts +2 -1
  260. package/build/types/integrations/anthropic.d.ts.map +1 -1
  261. package/build/types/integrations/aws-sdk/index.d.ts +3 -3
  262. package/build/types/integrations/aws-sdk/index.d.ts.map +1 -1
  263. package/build/types/integrations/aws-sdk/services/ServiceExtension.d.ts +1 -0
  264. package/build/types/integrations/aws-sdk/services/ServiceExtension.d.ts.map +1 -1
  265. package/build/types/integrations/aws-sdk/services/ServicesExtensions.d.ts +3 -2
  266. package/build/types/integrations/aws-sdk/services/ServicesExtensions.d.ts.map +1 -1
  267. package/build/types/integrations/aws-sdk/services/bedrock-runtime.d.ts +25 -4
  268. package/build/types/integrations/aws-sdk/services/bedrock-runtime.d.ts.map +1 -1
  269. package/build/types/integrations/bullmq/contextManager.d.ts +13 -0
  270. package/build/types/integrations/bullmq/contextManager.d.ts.map +1 -0
  271. package/build/types/integrations/bullmq/index.d.ts +43 -0
  272. package/build/types/integrations/bullmq/index.d.ts.map +1 -0
  273. package/build/types/integrations/bullmq/meter.d.ts +7 -0
  274. package/build/types/integrations/bullmq/meter.d.ts.map +1 -0
  275. package/build/types/integrations/bullmq/span.d.ts +35 -0
  276. package/build/types/integrations/bullmq/span.d.ts.map +1 -0
  277. package/build/types/integrations/bullmq/tracer.d.ts +5 -0
  278. package/build/types/integrations/bullmq/tracer.d.ts.map +1 -0
  279. package/build/types/integrations/bullmq/types.d.ts +72 -0
  280. package/build/types/integrations/bullmq/types.d.ts.map +1 -0
  281. package/build/types/integrations/cron.d.ts.map +1 -1
  282. package/build/types/integrations/express/types.d.ts +1 -0
  283. package/build/types/integrations/express/types.d.ts.map +1 -1
  284. package/build/types/integrations/flue.d.ts +2 -1
  285. package/build/types/integrations/flue.d.ts.map +1 -1
  286. package/build/types/integrations/google-genai.d.ts +5 -4
  287. package/build/types/integrations/google-genai.d.ts.map +1 -1
  288. package/build/types/integrations/groq.d.ts +1 -1
  289. package/build/types/integrations/langchain.d.ts +2 -1
  290. package/build/types/integrations/langchain.d.ts.map +1 -1
  291. package/build/types/integrations/langgraph.d.ts +2 -1
  292. package/build/types/integrations/langgraph.d.ts.map +1 -1
  293. package/build/types/integrations/mistral.d.ts +2 -1
  294. package/build/types/integrations/mistral.d.ts.map +1 -1
  295. package/build/types/integrations/node-cron.d.ts +1 -1
  296. package/build/types/integrations/node-cron.d.ts.map +1 -1
  297. package/build/types/integrations/node-schedule.d.ts.map +1 -1
  298. package/build/types/integrations/openai-compatible.d.ts.map +1 -1
  299. package/build/types/integrations/openai.d.ts +2 -1
  300. package/build/types/integrations/openai.d.ts.map +1 -1
  301. package/build/types/integrations/pi-ai.d.ts +6 -3
  302. package/build/types/integrations/pi-ai.d.ts.map +1 -1
  303. package/build/types/integrations/pi-durable.d.ts +2 -1
  304. package/build/types/integrations/pi-durable.d.ts.map +1 -1
  305. package/build/types/integrations/pino.d.ts +61 -0
  306. package/build/types/integrations/pino.d.ts.map +1 -0
  307. package/build/types/integrations/together-ai.d.ts +1 -1
  308. package/build/types/integrations/typesafe.d.ts +2 -2
  309. package/build/types/integrations/typesafe.d.ts.map +1 -1
  310. package/build/types/integrations/vercel-ai/index.d.ts +3 -3
  311. package/build/types/integrations/vercel-ai/index.d.ts.map +1 -1
  312. package/build/types/integrations/vercel-ai/util.d.ts +2 -1
  313. package/build/types/integrations/vercel-ai/util.d.ts.map +1 -1
  314. package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts +20 -4
  315. package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts.map +1 -1
  316. package/build/types/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.d.ts.map +1 -1
  317. package/build/types/integrations/winston.d.ts +55 -0
  318. package/build/types/integrations/winston.d.ts.map +1 -0
  319. package/build/types/orchestrion/bundler/moduleInjectedTransform.d.ts.map +1 -1
  320. package/build/types/orchestrion/bundler/rollup.d.ts +3 -3
  321. package/build/types/orchestrion/bundler/rollup.d.ts.map +1 -1
  322. package/build/types/orchestrion/channels.d.ts +1 -0
  323. package/build/types/orchestrion/channels.d.ts.map +1 -1
  324. package/build/types/orchestrion/config/google-genai.d.ts +13 -0
  325. package/build/types/orchestrion/config/google-genai.d.ts.map +1 -1
  326. package/build/types/utils/cronMonitoring.d.ts +4 -5
  327. package/build/types/utils/cronMonitoring.d.ts.map +1 -1
  328. package/package.json +3 -3
@@ -195,6 +195,29 @@ function resolveAIRecordingOptions(options) {
195
195
  };
196
196
  }
197
197
  /**
198
+ * Resolves the recording options of one call, like {@link resolveAIRecordingOptions}, and calls the
199
+ * options that are functions with `call`. Call it once when the call starts, so the functions run in the
200
+ * caller's async context.
201
+ */
202
+ function resolveGenAiCallRecording(options, call) {
203
+ const genAI = (0, _sentry_core.getClient)()?.getDataCollectionOptions().genAI;
204
+ return {
205
+ recordInputs: resolveRecordingOption(options?.recordInputs, call) ?? genAI?.inputs ?? true,
206
+ recordOutputs: resolveRecordingOption(options?.recordOutputs, call) ?? genAI?.outputs ?? true
207
+ };
208
+ }
209
+ /** Calls `option` with `call` when it is a function; `undefined` means the option does not decide. */
210
+ function resolveRecordingOption(option, call) {
211
+ if (typeof option !== "function") return option;
212
+ try {
213
+ const result = option(call);
214
+ return result === void 0 ? void 0 : result === true;
215
+ } catch (error) {
216
+ require_debug_build.DEBUG_BUILD && _sentry_core.debug.warn("[gen_ai] `recordInputs`/`recordOutputs` threw, not recording content", error);
217
+ return false;
218
+ }
219
+ }
220
+ /**
198
221
  * Build method path from current traversal
199
222
  */
200
223
  function buildMethodPath(currentPath, prop) {
@@ -314,8 +337,9 @@ function markCancelledIfAborted(span, abortSignal) {
314
337
  /**
315
338
  * Ends a streaming span by setting all accumulated response attributes and ending the span.
316
339
  * Shared across OpenAI, Anthropic, and Google GenAI streaming implementations.
340
+ * `beforeSpanEnd` runs after the attributes are set, right before the span ends.
317
341
  */
318
- function endStreamSpan(span, state, recordOutputs) {
342
+ function endStreamSpan(span, state, recordOutputs, beforeSpanEnd) {
319
343
  if (!span.isRecording()) return;
320
344
  const attrs = { [_sentry_conventions_attributes.GEN_AI_RESPONSE_STREAMING]: true };
321
345
  if (state.responseId) attrs[_sentry_conventions_attributes.GEN_AI_RESPONSE_ID] = state.responseId;
@@ -326,6 +350,7 @@ function endStreamSpan(span, state, recordOutputs) {
326
350
  if (recordOutputs && state.responseTexts.length) attrs[_sentry_conventions_attributes.GEN_AI_RESPONSE_TEXT] = state.responseTexts.join("");
327
351
  if (recordOutputs && state.toolCalls.length) attrs[_sentry_conventions_attributes.GEN_AI_RESPONSE_TOOL_CALLS] = JSON.stringify(state.toolCalls);
328
352
  span.setAttributes(attrs);
353
+ beforeSpanEnd?.();
329
354
  span.end();
330
355
  }
331
356
  /**
@@ -390,6 +415,24 @@ function wrapPromiseWithMethods(originalPromiseLike, instrumentedPromise) {
390
415
  return typeof value === "function" ? value.bind(source) : value;
391
416
  } });
392
417
  }
418
+ // src/ai/core/span-hooks.ts
419
+ /** Runs {@link GenAiSpanHooks.onSpanStart}. */
420
+ function runGenAiSpanStart(hooks, span, call) {
421
+ const onSpanStart = hooks.onSpanStart;
422
+ if (onSpanStart && span.isRecording()) runGenAiSpanHook("onSpanStart", () => onSpanStart(span, call));
423
+ }
424
+ /** Runs {@link GenAiSpanHooks.onSpanEnd}. Call it right before the span ends. */
425
+ function runGenAiSpanEnd(hooks, span, call, result) {
426
+ const onSpanEnd = hooks.onSpanEnd;
427
+ if (onSpanEnd && span.isRecording()) runGenAiSpanHook("onSpanEnd", () => onSpanEnd(span, call, result));
428
+ }
429
+ function runGenAiSpanHook(name, hook) {
430
+ try {
431
+ hook();
432
+ } catch (error) {
433
+ require_debug_build.DEBUG_BUILD && _sentry_core.debug.warn(`[gen_ai] \`${name}\` threw`, error);
434
+ }
435
+ }
393
436
  // src/ai/openai/constants.ts
394
437
  const OPENAI_INTEGRATION_NAME = "OpenAI";
395
438
  const OPENAI_METHOD_REGISTRY = {
@@ -448,6 +491,15 @@ function getToolCallKey(toolCall, name, accumulator) {
448
491
  if (toolCall.id || name || accumulator.lastKey === void 0) return `no-index-${calls.size}`;
449
492
  return accumulator.lastKey;
450
493
  }
494
+ // src/ai/core/time-to-first-chunk.ts
495
+ /**
496
+ * Sets `gen_ai.response.time_to_first_chunk` on a streamed span, in seconds from the span start.
497
+ * Call it for each received chunk. Only the first call per span records a value.
498
+ */
499
+ function recordTimeToFirstChunk(span) {
500
+ const { attributes, start_timestamp } = (0, _sentry_core.spanToJSON)(span);
501
+ if (attributes[_sentry_conventions_attributes.GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK] === void 0) span.setAttribute(_sentry_conventions_attributes.GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK, (0, _sentry_core.timestampInSeconds)() - start_timestamp);
502
+ }
451
503
  // src/ai/core/gen-ai-attributes.ts
452
504
  /**
453
505
  * Gen-AI telemetry attributes that are not (yet) covered by `@sentry/conventions`.
@@ -489,7 +541,7 @@ const GEN_AI_TOOL_CALL_ID_ATTRIBUTE = "gen_ai.tool.call.id";
489
541
  * Serialize a decisions request. Its evidence is `input` where Jev's is `state`; it is recorded as `state`
490
542
  * so both render the same.
491
543
  */
492
- function getDecisionInputMessages(params) {
544
+ function getDecisionInputMessages$1(params) {
493
545
  const questions = Array.isArray(params.questions) ? params.questions.map(toJevQuestionFormat) : params.questions;
494
546
  return getEvaluationInputMessages({
495
547
  state: params.input,
@@ -777,9 +829,10 @@ function processResponsesApiEvent(streamEvent, state, recordOutputs, span) {
777
829
  * @param stream - The async iterable stream of events to instrument.
778
830
  * @param span - The span to add attributes to and to finish at the end of the stream.
779
831
  * @param recordOutputs - Whether to record output text fragments in the span.
832
+ * @param beforeSpanEnd - Runs right before the span ends, with the error when the stream failed.
780
833
  * @returns An async generator yielding each event from the input stream.
781
834
  */
782
- async function* instrumentStream$1(stream, span, recordOutputs) {
835
+ async function* instrumentStream$1(stream, span, recordOutputs, beforeSpanEnd) {
783
836
  const state = {
784
837
  eventTypes: [],
785
838
  responseTexts: [],
@@ -794,8 +847,10 @@ async function* instrumentStream$1(stream, span, recordOutputs) {
794
847
  chatCompletionToolCalls: /* @__PURE__ */ new Map(),
795
848
  responsesApiToolCalls: []
796
849
  };
850
+ const result = {};
797
851
  try {
798
852
  for await (const event of stream) {
853
+ recordTimeToFirstChunk(span);
799
854
  if (isChatCompletionChunk(event)) processChatCompletionChunk(event, state, recordOutputs);
800
855
  else if (isResponsesApiStreamEvent(event)) processResponsesApiEvent(event, state, recordOutputs, span);
801
856
  yield event;
@@ -805,13 +860,14 @@ async function* instrumentStream$1(stream, span, recordOutputs) {
805
860
  code: _sentry_core.SPAN_STATUS_ERROR,
806
861
  message: "internal_error"
807
862
  });
863
+ result.error = error;
808
864
  throw error;
809
865
  } finally {
810
866
  const allToolCalls = [...state.chatCompletionToolCalls.values(), ...state.responsesApiToolCalls];
811
867
  endStreamSpan(span, {
812
868
  ...state,
813
869
  toolCalls: allToolCalls
814
- }, recordOutputs);
870
+ }, recordOutputs, () => beforeSpanEnd?.(result));
815
871
  }
816
872
  }
817
873
  // src/ai/openai/index.ts
@@ -846,7 +902,7 @@ function extractRequestAttributes$4(args, operationName, recordInputs) {
846
902
  const params = args[0];
847
903
  if (recordInputs) attributes[_sentry_conventions_attributes.GEN_AI_TOOL_DEFINITIONS] = extractAvailableTools(params);
848
904
  Object.assign(attributes, extractRequestParameters$1(params));
849
- if (recordInputs && operationName === "decide") attributes[_sentry_conventions_attributes.GEN_AI_INPUT_MESSAGES] = getDecisionInputMessages(params);
905
+ if (recordInputs && operationName === "decide") attributes[_sentry_conventions_attributes.GEN_AI_INPUT_MESSAGES] = getDecisionInputMessages$1(params);
850
906
  } else attributes[_sentry_conventions_attributes.GEN_AI_REQUEST_MODEL] = "unknown";
851
907
  return attributes;
852
908
  }
@@ -875,9 +931,14 @@ function addRequestAttributes$2(span, params, operationName) {
875
931
  function instrumentMethod$3(originalMethod, methodPath, instrumentedMethod, context, options) {
876
932
  return function instrumentedCall(...args) {
877
933
  const operationName = instrumentedMethod.operation || "unknown";
878
- const requestAttributes = extractRequestAttributes$4(args, operationName, !!options.recordInputs);
879
- const model = requestAttributes[_sentry_conventions_attributes.GEN_AI_REQUEST_MODEL] || "unknown";
880
934
  const params = args[0];
935
+ const call = {
936
+ operation: operationName,
937
+ request: params
938
+ };
939
+ const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);
940
+ const requestAttributes = extractRequestAttributes$4(args, operationName, recordInputs);
941
+ const model = requestAttributes[_sentry_conventions_attributes.GEN_AI_REQUEST_MODEL] || "unknown";
881
942
  const isStreamRequested = params && typeof params === "object" && params.stream === true;
882
943
  const abortSignal = getRequestSignal(args[1]);
883
944
  const client = (0, _sentry_core.getClient)();
@@ -890,12 +951,14 @@ function instrumentMethod$3(originalMethod, methodPath, instrumentedMethod, cont
890
951
  let originalResult;
891
952
  const instrumentedPromise = (0, _sentry_core.startSpanManual)(spanConfig, (span) => {
892
953
  originalResult = originalMethod.apply(context, args);
893
- if (options.recordInputs && params) addRequestAttributes$2(span, params, operationName);
954
+ if (recordInputs && params) addRequestAttributes$2(span, params, operationName);
955
+ runGenAiSpanStart(options, span, call);
894
956
  return (async () => {
895
957
  try {
896
- return instrumentStream$1(await originalResult, span, options.recordOutputs ?? false);
958
+ return instrumentStream$1(await originalResult, span, recordOutputs, (streamResult) => runGenAiSpanEnd(options, span, call, streamResult));
897
959
  } catch (error) {
898
960
  span.setStatus(getErrorStatus(abortSignal));
961
+ runGenAiSpanEnd(options, span, call, { error });
899
962
  span.end();
900
963
  throw error;
901
964
  }
@@ -906,12 +969,15 @@ function instrumentMethod$3(originalMethod, methodPath, instrumentedMethod, cont
906
969
  let originalResult;
907
970
  const instrumentedPromise = (0, _sentry_core.startSpan)(spanConfig, (span) => {
908
971
  originalResult = originalMethod.apply(context, args);
909
- if (options.recordInputs && params) addRequestAttributes$2(span, params, operationName);
972
+ if (recordInputs && params) addRequestAttributes$2(span, params, operationName);
973
+ runGenAiSpanStart(options, span, call);
910
974
  return originalResult.then((result) => {
911
- addResponseAttributes$5(span, result, options.recordOutputs, operationName);
975
+ addResponseAttributes$5(span, result, recordOutputs, operationName);
976
+ runGenAiSpanEnd(options, span, call, { response: result });
912
977
  return result;
913
978
  }, (error) => {
914
979
  span.setStatus(getErrorStatus(abortSignal));
980
+ runGenAiSpanEnd(options, span, call, { error });
915
981
  throw error;
916
982
  });
917
983
  });
@@ -964,7 +1030,7 @@ function createDeepProxy$2(target, currentPath = "", options) {
964
1030
  * Can be used across Node.js, Cloudflare Workers, and Vercel Edge
965
1031
  */
966
1032
  function instrumentOpenAiClient(client, options) {
967
- return createDeepProxy$2(client, "", resolveAIRecordingOptions(options));
1033
+ return createDeepProxy$2(client, "", options ?? {});
968
1034
  }
969
1035
  // src/ai/anthropic-ai/constants.ts
970
1036
  const ANTHROPIC_AI_INTEGRATION_NAME = "Anthropic_AI";
@@ -1032,6 +1098,44 @@ function handleResponseError(span, response) {
1032
1098
  } });
1033
1099
  }
1034
1100
  }
1101
+ /**
1102
+ * Add content attributes when recordOutputs is enabled
1103
+ */
1104
+ function addContentAttributes(span, response) {
1105
+ if ("content" in response) {
1106
+ if (Array.isArray(response.content)) {
1107
+ span.setAttributes({ [_sentry_conventions_attributes.GEN_AI_RESPONSE_TEXT]: response.content.map((item) => item.text).filter((text) => !!text).join("") });
1108
+ const toolCalls = [];
1109
+ for (const item of response.content) if (item.type === "tool_use" || item.type === "server_tool_use") toolCalls.push(item);
1110
+ if (toolCalls.length > 0) span.setAttributes({ [_sentry_conventions_attributes.GEN_AI_RESPONSE_TOOL_CALLS]: JSON.stringify(toolCalls) });
1111
+ }
1112
+ }
1113
+ if ("completion" in response) span.setAttributes({ [_sentry_conventions_attributes.GEN_AI_RESPONSE_TEXT]: response.completion });
1114
+ }
1115
+ /**
1116
+ * Add basic metadata attributes from the response
1117
+ */
1118
+ function addMetadataAttributes(span, response) {
1119
+ if ("id" in response && "model" in response) {
1120
+ span.setAttributes({
1121
+ [_sentry_conventions_attributes.GEN_AI_RESPONSE_ID]: response.id,
1122
+ [_sentry_conventions_attributes.GEN_AI_RESPONSE_MODEL]: response.model
1123
+ });
1124
+ if ("usage" in response && response.usage) span.setAttributes(getTokenUsageAttributes(response.usage.input_tokens + (response.usage.cache_creation_input_tokens ?? 0) + (response.usage.cache_read_input_tokens ?? 0), response.usage.output_tokens, response.usage.cache_creation_input_tokens, response.usage.cache_read_input_tokens));
1125
+ }
1126
+ }
1127
+ /**
1128
+ * Add response attributes to spans
1129
+ */
1130
+ function addResponseAttributes$4(span, response, recordOutputs) {
1131
+ if (!response || typeof response !== "object") return;
1132
+ if ("type" in response && response.type === "error") {
1133
+ handleResponseError(span, response);
1134
+ return;
1135
+ }
1136
+ if (recordOutputs) addContentAttributes(span, response);
1137
+ addMetadataAttributes(span, response);
1138
+ }
1035
1139
  /** Anthropic accepts the system prompt as a string or as an array of text blocks. */
1036
1140
  function systemToText(system) {
1037
1141
  if (!Array.isArray(system)) return typeof system === "string" ? system : void 0;
@@ -1160,6 +1264,7 @@ function handleContentBlockStop(event, state) {
1160
1264
  function processEvent$1(event, state, recordOutputs, span) {
1161
1265
  if (!(event && typeof event === "object")) return;
1162
1266
  if (isErrorEvent(event, span)) return;
1267
+ recordTimeToFirstChunk(span);
1163
1268
  handleMessageMetadata(event, state);
1164
1269
  handleContentBlockStart(event, state);
1165
1270
  handleContentBlockDelta(event, state, recordOutputs);
@@ -1170,7 +1275,7 @@ function processEvent$1(event, state, recordOutputs, span) {
1170
1275
  * streaming attributes and (optionally) the aggregated output text, and yields
1171
1276
  * each event from the input stream unchanged.
1172
1277
  */
1173
- async function* instrumentAsyncIterableStream(stream, span, recordOutputs) {
1278
+ async function* instrumentAsyncIterableStream(stream, span, recordOutputs, beforeSpanEnd) {
1174
1279
  const state = {
1175
1280
  responseTexts: [],
1176
1281
  finishReasons: [],
@@ -1184,6 +1289,7 @@ async function* instrumentAsyncIterableStream(stream, span, recordOutputs) {
1184
1289
  toolCalls: [],
1185
1290
  activeToolBlocks: {}
1186
1291
  };
1292
+ const result = {};
1187
1293
  try {
1188
1294
  for await (const event of stream) {
1189
1295
  processEvent$1(event, state, recordOutputs, span);
@@ -1194,15 +1300,16 @@ async function* instrumentAsyncIterableStream(stream, span, recordOutputs) {
1194
1300
  code: _sentry_core.SPAN_STATUS_ERROR,
1195
1301
  message: "internal_error"
1196
1302
  });
1303
+ result.error = error;
1197
1304
  throw error;
1198
1305
  } finally {
1199
- endStreamSpan(span, state, recordOutputs);
1306
+ endStreamSpan(span, state, recordOutputs, () => beforeSpanEnd?.(result));
1200
1307
  }
1201
1308
  }
1202
1309
  /**
1203
1310
  * Instruments a MessageStream by registering event handlers and preserving the original stream API.
1204
1311
  */
1205
- function instrumentMessageStream(stream, span, recordOutputs, abortSignal) {
1312
+ function instrumentMessageStream(stream, span, recordOutputs, abortSignal, beforeSpanEnd) {
1206
1313
  const state = {
1207
1314
  responseTexts: [],
1208
1315
  finishReasons: [],
@@ -1220,14 +1327,14 @@ function instrumentMessageStream(stream, span, recordOutputs, abortSignal) {
1220
1327
  processEvent$1(event, state, recordOutputs, span);
1221
1328
  });
1222
1329
  stream.on("message", () => {
1223
- endStreamSpan(span, state, recordOutputs);
1330
+ endStreamSpan(span, state, recordOutputs, () => beforeSpanEnd?.({}));
1224
1331
  });
1225
1332
  stream.on("end", () => {
1226
1333
  if (span.isRecording() && stream.aborted) span.setStatus(abortSignal?.aborted ? getErrorStatus(abortSignal) : {
1227
1334
  code: _sentry_core.SPAN_STATUS_ERROR,
1228
1335
  message: "cancelled"
1229
1336
  });
1230
- endStreamSpan(span, state, recordOutputs);
1337
+ endStreamSpan(span, state, recordOutputs, () => beforeSpanEnd?.({}));
1231
1338
  });
1232
1339
  stream.on("error", (error) => {
1233
1340
  (0, _sentry_core.captureException)(error, { mechanism: {
@@ -1239,7 +1346,7 @@ function instrumentMessageStream(stream, span, recordOutputs, abortSignal) {
1239
1346
  code: _sentry_core.SPAN_STATUS_ERROR,
1240
1347
  message: "internal_error"
1241
1348
  });
1242
- endStreamSpan(span, state, recordOutputs);
1349
+ endStreamSpan(span, state, recordOutputs, () => beforeSpanEnd?.({ error }));
1243
1350
  }
1244
1351
  });
1245
1352
  return stream;
@@ -1344,8 +1451,13 @@ function wrapInPlace(owner, key, call) {
1344
1451
  });
1345
1452
  }
1346
1453
  function runWithSpan(tool, run, thisArg, args, options) {
1347
- const { recordInputs, recordOutputs } = resolveAIRecordingOptions(options);
1348
1454
  const [input, context] = args;
1455
+ const call = {
1456
+ operation: "execute_tool",
1457
+ tool,
1458
+ input
1459
+ };
1460
+ const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);
1349
1461
  const callId = (context?.toolUse ?? context?.toolUseBlock)?.id;
1350
1462
  return (0, _sentry_core.startSpan)({
1351
1463
  name: `execute_tool ${tool.name}`,
@@ -1358,7 +1470,16 @@ function runWithSpan(tool, run, thisArg, args, options) {
1358
1470
  ...typeof callId === "string" ? { [GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: callId } : {},
1359
1471
  ...recordInputs ? { [_sentry_conventions_attributes.GEN_AI_TOOL_CALL_ARGUMENTS]: (0, _sentry_core.stringify)(input) } : {}
1360
1472
  }
1361
- }, (span) => (0, _sentry_core.handleCallbackErrors)(() => run.apply(thisArg, args), (error) => handleToolError(span, error, context), void 0, (result) => recordOutputs && span.setAttribute(_sentry_conventions_attributes.GEN_AI_TOOL_CALL_RESULT, (0, _sentry_core.stringify)(result))));
1473
+ }, (span) => {
1474
+ runGenAiSpanStart(options, span, call);
1475
+ return (0, _sentry_core.handleCallbackErrors)(() => run.apply(thisArg, args), (error) => {
1476
+ handleToolError(span, error, context);
1477
+ runGenAiSpanEnd(options, span, call, { error });
1478
+ }, void 0, (result) => {
1479
+ if (recordOutputs) span.setAttribute(_sentry_conventions_attributes.GEN_AI_TOOL_CALL_RESULT, (0, _sentry_core.stringify)(result));
1480
+ runGenAiSpanEnd(options, span, call, { response: result });
1481
+ });
1482
+ });
1362
1483
  }
1363
1484
  function handleToolError(span, error, context) {
1364
1485
  span.setStatus(getErrorStatus(context?.signal));
@@ -1402,49 +1523,12 @@ function addPrivateRequestAttributes$1(span, params) {
1402
1523
  span.setAttributes(getMessagesAttributes(messages));
1403
1524
  }
1404
1525
  /**
1405
- * Add content attributes when recordOutputs is enabled
1406
- */
1407
- function addContentAttributes(span, response) {
1408
- if ("content" in response) {
1409
- if (Array.isArray(response.content)) {
1410
- span.setAttributes({ [_sentry_conventions_attributes.GEN_AI_RESPONSE_TEXT]: response.content.map((item) => item.text).filter((text) => !!text).join("") });
1411
- const toolCalls = [];
1412
- for (const item of response.content) if (item.type === "tool_use" || item.type === "server_tool_use") toolCalls.push(item);
1413
- if (toolCalls.length > 0) span.setAttributes({ [_sentry_conventions_attributes.GEN_AI_RESPONSE_TOOL_CALLS]: JSON.stringify(toolCalls) });
1414
- }
1415
- }
1416
- if ("completion" in response) span.setAttributes({ [_sentry_conventions_attributes.GEN_AI_RESPONSE_TEXT]: response.completion });
1417
- }
1418
- /**
1419
- * Add basic metadata attributes from the response
1420
- */
1421
- function addMetadataAttributes(span, response) {
1422
- if ("id" in response && "model" in response) {
1423
- span.setAttributes({
1424
- [_sentry_conventions_attributes.GEN_AI_RESPONSE_ID]: response.id,
1425
- [_sentry_conventions_attributes.GEN_AI_RESPONSE_MODEL]: response.model
1426
- });
1427
- if ("usage" in response && response.usage) span.setAttributes(getTokenUsageAttributes(response.usage.input_tokens + (response.usage.cache_creation_input_tokens ?? 0) + (response.usage.cache_read_input_tokens ?? 0), response.usage.output_tokens, response.usage.cache_creation_input_tokens, response.usage.cache_read_input_tokens));
1428
- }
1429
- }
1430
- /**
1431
- * Add response attributes to spans
1432
- */
1433
- function addResponseAttributes$4(span, response, recordOutputs) {
1434
- if (!response || typeof response !== "object") return;
1435
- if ("type" in response && response.type === "error") {
1436
- handleResponseError(span, response);
1437
- return;
1438
- }
1439
- if (recordOutputs) addContentAttributes(span, response);
1440
- addMetadataAttributes(span, response);
1441
- }
1442
- /**
1443
1526
  * Handle common error catching and reporting for streaming requests
1444
1527
  */
1445
- function handleStreamingError(error, span, abortSignal) {
1528
+ function handleStreamingError(error, span, abortSignal, onSpanEnd) {
1446
1529
  if (span.isRecording()) {
1447
1530
  span.setStatus(getErrorStatus(abortSignal));
1531
+ onSpanEnd({ error });
1448
1532
  span.end();
1449
1533
  }
1450
1534
  throw error;
@@ -1452,32 +1536,36 @@ function handleStreamingError(error, span, abortSignal) {
1452
1536
  /**
1453
1537
  * Handle streaming cases with common logic
1454
1538
  */
1455
- function handleStreamingRequest(target, invocationThis, args, spanConfig, params, options, isStreamRequested, isStreamingMethod) {
1539
+ function handleStreamingRequest(target, invocationThis, args, spanConfig, params, { recordInputs, recordOutputs }, isStreamRequested, isStreamingMethod, options, call) {
1456
1540
  const abortSignal = getRequestSignal(args[1]);
1457
1541
  if (isStreamRequested && !isStreamingMethod) {
1458
1542
  let originalResult;
1459
1543
  const instrumentedPromise = (0, _sentry_core.startSpanManual)(spanConfig, (span) => {
1460
1544
  originalResult = target.apply(invocationThis, args);
1461
- if (options.recordInputs && params) addPrivateRequestAttributes$1(span, params);
1545
+ if (recordInputs && params) addPrivateRequestAttributes$1(span, params);
1546
+ runGenAiSpanStart(options, span, call);
1547
+ const onSpanEnd = (result) => runGenAiSpanEnd(options, span, call, result);
1462
1548
  return (async () => {
1463
1549
  try {
1464
- return instrumentAsyncIterableStream(await originalResult, span, options.recordOutputs ?? false);
1550
+ return instrumentAsyncIterableStream(await originalResult, span, recordOutputs, onSpanEnd);
1465
1551
  } catch (error) {
1466
- return handleStreamingError(error, span, abortSignal);
1552
+ return handleStreamingError(error, span, abortSignal, onSpanEnd);
1467
1553
  }
1468
1554
  })();
1469
1555
  });
1470
1556
  return wrapPromiseWithMethods(originalResult, instrumentedPromise);
1471
1557
  } else return (0, _sentry_core.startSpanManual)(spanConfig, (span) => {
1558
+ const onSpanEnd = (result) => runGenAiSpanEnd(options, span, call, result);
1472
1559
  try {
1473
- if (options.recordInputs && params) addPrivateRequestAttributes$1(span, params);
1560
+ if (recordInputs && params) addPrivateRequestAttributes$1(span, params);
1561
+ runGenAiSpanStart(options, span, call);
1474
1562
  suppressDelegatedCreate = true;
1475
1563
  const messageStream = target.apply(invocationThis, args);
1476
1564
  suppressDelegatedCreate = false;
1477
- return instrumentMessageStream(messageStream, span, options.recordOutputs ?? false, abortSignal);
1565
+ return instrumentMessageStream(messageStream, span, recordOutputs, abortSignal, onSpanEnd);
1478
1566
  } catch (error) {
1479
1567
  suppressDelegatedCreate = false;
1480
- return handleStreamingError(error, span, abortSignal);
1568
+ return handleStreamingError(error, span, abortSignal, onSpanEnd);
1481
1569
  }
1482
1570
  });
1483
1571
  }
@@ -1492,7 +1580,13 @@ function instrumentMethod$2(originalMethod, methodPath, instrumentedMethod, cont
1492
1580
  const isStreamingMethod = instrumentedMethod.streaming === true;
1493
1581
  if (!isStreamingMethod && suppressDelegatedCreate) return target.apply(invocationThis, args);
1494
1582
  const operationName = instrumentedMethod.operation || "unknown";
1495
- const requestAttributes = extractRequestAttributes$3(args, operationName, !!options.recordInputs, getProviderName(invocationThis));
1583
+ const params = typeof args[0] === "object" && args[0] !== null ? args[0] : void 0;
1584
+ const call = {
1585
+ operation: "chat",
1586
+ request: params
1587
+ };
1588
+ const recording = resolveGenAiCallRecording(options, call);
1589
+ const requestAttributes = extractRequestAttributes$3(args, operationName, recording.recordInputs, getProviderName(invocationThis));
1496
1590
  const model = requestAttributes[_sentry_conventions_attributes.GEN_AI_REQUEST_MODEL] || "unknown";
1497
1591
  const client = (0, _sentry_core.getClient)();
1498
1592
  const spanConfig = {
@@ -1500,19 +1594,21 @@ function instrumentMethod$2(originalMethod, methodPath, instrumentedMethod, cont
1500
1594
  op: getGenAiSpanOp(operationName),
1501
1595
  attributes: requestAttributes
1502
1596
  };
1503
- const params = typeof args[0] === "object" ? args[0] : void 0;
1504
1597
  const isStreamRequested = Boolean(params?.stream);
1505
- if (isStreamRequested || isStreamingMethod) return handleStreamingRequest(target, invocationThis, args, spanConfig, params, options, isStreamRequested, isStreamingMethod);
1598
+ if (isStreamRequested || isStreamingMethod) return handleStreamingRequest(target, invocationThis, args, spanConfig, params, recording, isStreamRequested, isStreamingMethod, options, call);
1506
1599
  const abortSignal = getRequestSignal(args[1]);
1507
1600
  let originalResult;
1508
1601
  const instrumentedPromise = (0, _sentry_core.startSpan)(spanConfig, (span) => {
1509
1602
  originalResult = target.apply(invocationThis, args);
1510
- if (options.recordInputs && params) addPrivateRequestAttributes$1(span, params);
1603
+ if (recording.recordInputs && params) addPrivateRequestAttributes$1(span, params);
1604
+ runGenAiSpanStart(options, span, call);
1511
1605
  return originalResult.then((result) => {
1512
- addResponseAttributes$4(span, result, options.recordOutputs);
1606
+ addResponseAttributes$4(span, result, recording.recordOutputs);
1607
+ runGenAiSpanEnd(options, span, call, { response: result });
1513
1608
  return result;
1514
1609
  }, (error) => {
1515
1610
  span.setStatus(getErrorStatus(abortSignal));
1611
+ runGenAiSpanEnd(options, span, call, { error });
1516
1612
  throw error;
1517
1613
  });
1518
1614
  });
@@ -1558,7 +1654,7 @@ function instrumentClientInPlace(client, options) {
1558
1654
  * @returns The instrumented client with the same type as the input
1559
1655
  */
1560
1656
  function instrumentAnthropicAiClient(anthropicAiClient, options) {
1561
- return instrumentClientInPlace(anthropicAiClient, resolveAIRecordingOptions(options));
1657
+ return instrumentClientInPlace(anthropicAiClient, options ?? {});
1562
1658
  }
1563
1659
  // src/ai/google-genai/constants.ts
1564
1660
  const GOOGLE_GENAI_INTEGRATION_NAME = "Google_GenAI";
@@ -1574,9 +1670,29 @@ const GOOGLE_GENAI_METHOD_REGISTRY = {
1574
1670
  "chat.sendMessageStream": {
1575
1671
  operation: "chat",
1576
1672
  streaming: true
1577
- }
1673
+ },
1674
+ "decisions.create": { operation: "decide" }
1578
1675
  };
1579
1676
  const GOOGLE_GENAI_SYSTEM_NAME = "google_genai";
1677
+ // src/ai/google-genai/decisions.ts
1678
+ /**
1679
+ * Serialize a decisions request. Its evidence is `input` where Jev's is `state`; it is recorded as `state`
1680
+ * so both render the same.
1681
+ */
1682
+ function getDecisionInputMessages(params) {
1683
+ return getEvaluationInputMessages({
1684
+ state: params.input,
1685
+ questions: params.questions
1686
+ });
1687
+ }
1688
+ function addDecisionResponseAttributes(span, response, recordOutputs) {
1689
+ if (!(0, _sentry_core.isObjectLike)(response)) return;
1690
+ if ((0, _sentry_core.isObjectLike)(response.usage)) {
1691
+ const usage = response.usage;
1692
+ span.setAttributes(getTokenUsageAttributes(usage.total_input_tokens, usage.total_output_tokens, void 0, usage.total_cached_tokens, usage.total_tokens));
1693
+ }
1694
+ if (recordOutputs && response.answers !== void 0) span.setAttribute(_sentry_conventions_attributes.GEN_AI_OUTPUT_MESSAGES, getEvaluationOutputMessages(response.answers));
1695
+ }
1580
1696
  // src/ai/google-genai/utils.ts
1581
1697
  function normalizeRole(role) {
1582
1698
  return role === "model" ? "assistant" : role;
@@ -1775,6 +1891,7 @@ function handleCandidateContent(chunk, state, recordOutputs) {
1775
1891
  */
1776
1892
  function processChunk$1(chunk, state, recordOutputs, span) {
1777
1893
  if (!chunk || isErrorChunk(chunk, span)) return;
1894
+ recordTimeToFirstChunk(span);
1778
1895
  handleResponseMetadata(chunk, state);
1779
1896
  handleCandidateContent(chunk, state, recordOutputs);
1780
1897
  }
@@ -1783,13 +1900,14 @@ function processChunk$1(chunk, state, recordOutputs, span) {
1783
1900
  * streaming attributes and (optionally) the aggregated output text, and yields
1784
1901
  * each chunk from the input stream unchanged.
1785
1902
  */
1786
- async function* instrumentStream(stream, span, recordOutputs, abortSignal) {
1903
+ async function* instrumentStream(stream, span, recordOutputs, abortSignal, beforeSpanEnd) {
1787
1904
  const state = {
1788
1905
  responseTexts: [],
1789
1906
  finishReasons: [],
1790
1907
  toolCalls: [],
1791
1908
  outputParts: []
1792
1909
  };
1910
+ const result = {};
1793
1911
  try {
1794
1912
  for await (const chunk of stream) {
1795
1913
  processChunk$1(chunk, state, recordOutputs, span);
@@ -1797,11 +1915,12 @@ async function* instrumentStream(stream, span, recordOutputs, abortSignal) {
1797
1915
  }
1798
1916
  } catch (error) {
1799
1917
  span.setStatus(getErrorStatus(abortSignal));
1918
+ result.error = error;
1800
1919
  throw error;
1801
1920
  } finally {
1802
1921
  if (recordOutputs) setOutputMessagesAttribute(span, state.outputParts);
1803
1922
  if (typeof state.promptTokens === "number") state.promptTokens += state.toolUsePromptTokens ?? 0;
1804
- endStreamSpan(span, state, recordOutputs);
1923
+ endStreamSpan(span, state, recordOutputs, () => beforeSpanEnd?.(result));
1805
1924
  }
1806
1925
  }
1807
1926
  // src/ai/google-genai/index.ts
@@ -1851,6 +1970,8 @@ function extractRequestAttributes$2(operationName, params, context, recordInputs
1851
1970
  attributes[_sentry_conventions_attributes.GEN_AI_TOOL_DEFINITIONS] = JSON.stringify(functionDeclarations);
1852
1971
  }
1853
1972
  }
1973
+ const decisionInput = recordInputs && operationName === "decide" ? getDecisionInputMessages(params) : void 0;
1974
+ if (decisionInput) attributes[_sentry_conventions_attributes.GEN_AI_INPUT_MESSAGES] = decisionInput;
1854
1975
  } else attributes[_sentry_conventions_attributes.GEN_AI_REQUEST_MODEL] = extractModel({}, context);
1855
1976
  return attributes;
1856
1977
  }
@@ -1882,8 +2003,12 @@ function addPrivateRequestAttributes(span, params, operationName) {
1882
2003
  * Add response attributes from the Google GenAI response
1883
2004
  * @see https://github.com/googleapis/js-genai/blob/v1.19.0/src/types.ts#L2313
1884
2005
  */
1885
- function addResponseAttributes$3(span, response, recordOutputs) {
2006
+ function addResponseAttributes$3(span, response, recordOutputs, operationName) {
1886
2007
  if (!response || typeof response !== "object") return;
2008
+ if (operationName === "decide") {
2009
+ addDecisionResponseAttributes(span, response, !!recordOutputs);
2010
+ return;
2011
+ }
1887
2012
  if (response.modelVersion) span.setAttribute(_sentry_conventions_attributes.GEN_AI_RESPONSE_MODEL, response.modelVersion);
1888
2013
  if (response.usageMetadata && typeof response.usageMetadata === "object") {
1889
2014
  const usage = response.usageMetadata;
@@ -1932,6 +2057,10 @@ function resolveChatParams(operationName, params, context) {
1932
2057
  function getAbortSignal(params) {
1933
2058
  return (params?.config)?.abortSignal;
1934
2059
  }
2060
+ /** `decisions.create` takes its abort signal in its request options, not in a `config`. */
2061
+ function getCallAbortSignal(operationName, params, requestOptions) {
2062
+ return operationName === "decide" ? getRequestSignal(requestOptions) : getAbortSignal(params);
2063
+ }
1935
2064
  /**
1936
2065
  * Instrument any async or synchronous genai method with Sentry spans
1937
2066
  * Handles operations like models.generateContent and chat.sendMessage and chats.create
@@ -1942,9 +2071,14 @@ function instrumentMethod$1(originalMethod, methodPath, instrumentedMethod, cont
1942
2071
  return new Proxy(originalMethod, { apply(target, _, args) {
1943
2072
  const operationName = instrumentedMethod.operation || "unknown";
1944
2073
  const params = args[0];
2074
+ const call = {
2075
+ operation: operationName,
2076
+ request: params
2077
+ };
2078
+ const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);
1945
2079
  const attributeParams = resolveChatParams(operationName, params, context);
1946
- const abortSignal = getAbortSignal(attributeParams);
1947
- const requestAttributes = extractRequestAttributes$2(operationName, attributeParams, context, !!options.recordInputs);
2080
+ const abortSignal = getCallAbortSignal(operationName, attributeParams, args[1]);
2081
+ const requestAttributes = extractRequestAttributes$2(operationName, attributeParams, context, recordInputs);
1948
2082
  const model = requestAttributes[_sentry_conventions_attributes.GEN_AI_REQUEST_MODEL] || "unknown";
1949
2083
  const client = (0, _sentry_core.getClient)();
1950
2084
  const spanName = typeof model === "string" && model !== "unknown" || !(client && (0, _sentry_core.hasSpanStreamingEnabled)(client)) ? `${operationName} ${model}` : operationName;
@@ -1954,10 +2088,12 @@ function instrumentMethod$1(originalMethod, methodPath, instrumentedMethod, cont
1954
2088
  attributes: requestAttributes
1955
2089
  }, async (span) => {
1956
2090
  try {
1957
- if (options.recordInputs && attributeParams) addPrivateRequestAttributes(span, attributeParams, operationName);
1958
- return instrumentStream(await target.apply(context, args), span, Boolean(options.recordOutputs), abortSignal);
2091
+ if (recordInputs && attributeParams) addPrivateRequestAttributes(span, attributeParams, operationName);
2092
+ runGenAiSpanStart(options, span, call);
2093
+ return instrumentStream(await target.apply(context, args), span, recordOutputs, abortSignal, (result) => runGenAiSpanEnd(options, span, call, result));
1959
2094
  } catch (error) {
1960
2095
  span.setStatus(getErrorStatus(abortSignal));
2096
+ runGenAiSpanEnd(options, span, call, { error });
1961
2097
  span.end();
1962
2098
  throw error;
1963
2099
  }
@@ -1967,9 +2103,14 @@ function instrumentMethod$1(originalMethod, methodPath, instrumentedMethod, cont
1967
2103
  op: getGenAiSpanOp(operationName),
1968
2104
  attributes: requestAttributes
1969
2105
  }, (span) => {
1970
- if (options.recordInputs && attributeParams) addPrivateRequestAttributes(span, attributeParams, operationName);
1971
- return (0, _sentry_core.handleCallbackErrors)(() => target.apply(context, args), () => span.setStatus(getErrorStatus(abortSignal)), () => {}, (result) => {
1972
- if (!isEmbeddings) addResponseAttributes$3(span, result, options.recordOutputs);
2106
+ if (recordInputs && attributeParams) addPrivateRequestAttributes(span, attributeParams, operationName);
2107
+ runGenAiSpanStart(options, span, call);
2108
+ return (0, _sentry_core.handleCallbackErrors)(() => target.apply(context, args), (error) => {
2109
+ span.setStatus(getErrorStatus(abortSignal));
2110
+ runGenAiSpanEnd(options, span, call, { error });
2111
+ }, () => {}, (result) => {
2112
+ if (!isEmbeddings) addResponseAttributes$3(span, result, recordOutputs, operationName);
2113
+ runGenAiSpanEnd(options, span, call, { response: result });
1973
2114
  });
1974
2115
  });
1975
2116
  } });
@@ -2051,7 +2192,7 @@ function createDeepProxy$1(target, currentPath = "", options) {
2051
2192
  * ```
2052
2193
  */
2053
2194
  function instrumentGoogleGenAIClient(client, options) {
2054
- return createDeepProxy$1(client, "", resolveAIRecordingOptions(options));
2195
+ return createDeepProxy$1(client, "", options ?? {});
2055
2196
  }
2056
2197
  // src/ai/mistral/constants.ts
2057
2198
  const MISTRAL_INTEGRATION_NAME = "Mistral";
@@ -2094,6 +2235,14 @@ function getSpanName$1(operationName, attributes) {
2094
2235
  return `${operationName} ${model}`;
2095
2236
  }
2096
2237
  /**
2238
+ * Reads the caller's signal from Mistral's request options. The SDK spreads `options` over
2239
+ * `options.fetchOptions`, so a top-level `signal` wins.
2240
+ */
2241
+ function getMistralRequestSignal(requestOptions) {
2242
+ const options = requestOptions;
2243
+ return options?.signal ?? options?.fetchOptions?.signal;
2244
+ }
2245
+ /**
2097
2246
  * Extract request parameters. Mistral request fields are camelCase.
2098
2247
  */
2099
2248
  function extractRequestParameters(params) {
@@ -2286,13 +2435,14 @@ function instrumentedSource(readable) {
2286
2435
  *
2287
2436
  * Returns `false` for a value that is not a stream, leaving it untouched.
2288
2437
  */
2289
- function instrumentEventStream(stream, span, recordOutputs) {
2438
+ function instrumentEventStream(stream, span, recordOutputs, abortSignal, beforeSpanEnd) {
2290
2439
  if (!isAsyncIterable(stream)) return false;
2291
2440
  const state = createStreamingState();
2292
2441
  let consumer;
2293
2442
  let settled = false;
2294
2443
  let cancelled = false;
2295
2444
  const claim = (candidate) => {
2445
+ recordTimeToFirstChunk(span);
2296
2446
  consumer ?? (consumer = candidate);
2297
2447
  return consumer === candidate;
2298
2448
  };
@@ -2302,10 +2452,7 @@ function instrumentEventStream(stream, span, recordOutputs) {
2302
2452
  const settle = (error) => {
2303
2453
  if (settled) return;
2304
2454
  settled = true;
2305
- if (error !== void 0 && !cancelled) span.setStatus({
2306
- code: _sentry_core.SPAN_STATUS_ERROR,
2307
- message: "internal_error"
2308
- });
2455
+ if (error !== void 0 && !cancelled) span.setStatus(getErrorStatus(abortSignal));
2309
2456
  const toolCalls = Object.values(state.toolCalls);
2310
2457
  if (recordOutputs) setOutputMessagesAttribute$1(span, {
2311
2458
  responseText: state.responseTexts.join(""),
@@ -2315,7 +2462,7 @@ function instrumentEventStream(stream, span, recordOutputs) {
2315
2462
  endStreamSpan(span, {
2316
2463
  ...state,
2317
2464
  toolCalls
2318
- }, recordOutputs);
2465
+ }, recordOutputs, () => beforeSpanEnd?.(error !== void 0 && !cancelled ? { error } : {}));
2319
2466
  };
2320
2467
  const instrumented = instrumentIterator(stream[Symbol.asyncIterator].bind(stream), state, recordOutputs, claim, settle);
2321
2468
  stream[Symbol.asyncIterator] = () => instrumented;
@@ -2397,8 +2544,14 @@ function instrumentMethod(originalMethod, instrumentedMethod, context, options)
2397
2544
  return function instrumentedCall(...args) {
2398
2545
  const operationName = instrumentedMethod.operation || "unknown";
2399
2546
  const isStreamRequested = !!instrumentedMethod.streaming;
2400
- const requestAttributes = extractRequestAttributes$1(args, operationName, !!options.recordInputs, isStreamRequested);
2401
2547
  const params = args[0];
2548
+ const abortSignal = getMistralRequestSignal(args[1]);
2549
+ const call = {
2550
+ operation: operationName,
2551
+ request: params
2552
+ };
2553
+ const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);
2554
+ const requestAttributes = extractRequestAttributes$1(args, operationName, recordInputs, isStreamRequested);
2402
2555
  const spanConfig = {
2403
2556
  name: getSpanName$1(operationName, requestAttributes),
2404
2557
  op: getGenAiSpanOp(operationName),
@@ -2408,15 +2561,17 @@ function instrumentMethod(originalMethod, instrumentedMethod, context, options)
2408
2561
  let originalResult;
2409
2562
  const instrumentedPromise = (0, _sentry_core.startSpanManual)(spanConfig, (span) => {
2410
2563
  originalResult = originalMethod.apply(context, args);
2411
- if (options.recordInputs && params) addRequestAttributes$1(span, params, operationName);
2564
+ if (recordInputs && params) addRequestAttributes$1(span, params, operationName);
2565
+ runGenAiSpanStart(options, span, call);
2412
2566
  return originalResult.then((result) => {
2413
- if (!instrumentEventStream(result, span, options.recordOutputs ?? false)) span.end();
2567
+ if (!instrumentEventStream(result, span, recordOutputs, abortSignal, (streamResult) => runGenAiSpanEnd(options, span, call, streamResult))) {
2568
+ runGenAiSpanEnd(options, span, call, { response: result });
2569
+ span.end();
2570
+ }
2414
2571
  return result;
2415
2572
  }, (error) => {
2416
- span.setStatus({
2417
- code: _sentry_core.SPAN_STATUS_ERROR,
2418
- message: "internal_error"
2419
- });
2573
+ span.setStatus(getErrorStatus(abortSignal));
2574
+ runGenAiSpanEnd(options, span, call, { error });
2420
2575
  span.end();
2421
2576
  throw error;
2422
2577
  });
@@ -2426,10 +2581,16 @@ function instrumentMethod(originalMethod, instrumentedMethod, context, options)
2426
2581
  let originalResult;
2427
2582
  const instrumentedPromise = (0, _sentry_core.startSpan)(spanConfig, (span) => {
2428
2583
  originalResult = originalMethod.apply(context, args);
2429
- if (options.recordInputs && params) addRequestAttributes$1(span, params, operationName);
2584
+ if (recordInputs && params) addRequestAttributes$1(span, params, operationName);
2585
+ runGenAiSpanStart(options, span, call);
2430
2586
  return originalResult.then((result) => {
2431
- addResponseAttributes$2(span, result, options.recordOutputs);
2587
+ addResponseAttributes$2(span, result, recordOutputs);
2588
+ runGenAiSpanEnd(options, span, call, { response: result });
2432
2589
  return result;
2590
+ }, (error) => {
2591
+ span.setStatus(getErrorStatus(abortSignal));
2592
+ runGenAiSpanEnd(options, span, call, { error });
2593
+ throw error;
2433
2594
  });
2434
2595
  });
2435
2596
  return wrapPromiseWithMethods(originalResult, instrumentedPromise);
@@ -2454,7 +2615,7 @@ function createDeepProxy(target, currentPath = "", options) {
2454
2615
  * Can be used across Node.js, Cloudflare Workers, and Vercel Edge.
2455
2616
  */
2456
2617
  function instrumentMistralAiClient(client, options) {
2457
- return createDeepProxy(client, "", resolveAIRecordingOptions(options));
2618
+ return createDeepProxy(client, "", options ?? {});
2458
2619
  }
2459
2620
  // src/ai/typesafe/constants.ts
2460
2621
  const TYPESAFE_INTEGRATION_NAME = "TypeSafe";
@@ -2520,31 +2681,38 @@ function instrumentTypeSafeClient(client, options) {
2520
2681
  return new Proxy(client, { get(target, prop) {
2521
2682
  const value = Reflect.get(target, prop, target);
2522
2683
  if (typeof value !== "function") return value;
2523
- if (prop === "systemOne") return (...args) => instrumentSystemOne(value, target, args, options);
2684
+ if (prop === "systemOne") return (...args) => instrumentSystemOne(value, target, args, options ?? {});
2524
2685
  return value.bind(target);
2525
2686
  } });
2526
2687
  }
2527
2688
  function instrumentSystemOne(systemOne, client, args, options) {
2528
- const { recordInputs, recordOutputs } = resolveAIRecordingOptions(options);
2689
+ const call = { request: args[0] };
2690
+ const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);
2529
2691
  const span = startDecideSpan(args[0], client, recordInputs);
2530
- const endWithError = () => {
2692
+ runGenAiSpanStart(options, span, call);
2693
+ const endWithError = (error) => {
2531
2694
  span.setStatus({
2532
2695
  code: _sentry_core.SPAN_STATUS_ERROR,
2533
2696
  message: "internal_error"
2534
2697
  });
2698
+ runGenAiSpanEnd(options, span, call, { error });
2535
2699
  span.end();
2536
2700
  };
2537
2701
  let result;
2538
2702
  try {
2539
2703
  result = (0, _sentry_core.withActiveSpan)(span, () => systemOne.apply(client, args));
2540
2704
  } catch (error) {
2541
- endWithError();
2705
+ endWithError(error);
2542
2706
  throw error;
2543
2707
  }
2544
2708
  if (!onSystemOneResponse(result, (body) => {
2545
2709
  addResponseAttributes$1(span, body, recordOutputs);
2710
+ runGenAiSpanEnd(options, span, call, { response: body });
2546
2711
  span.end();
2547
- }, endWithError)) span.end();
2712
+ }, endWithError)) {
2713
+ runGenAiSpanEnd(options, span, call, { response: result });
2714
+ span.end();
2715
+ }
2548
2716
  return result;
2549
2717
  }
2550
2718
  // src/ai/pi-ai/constants.ts
@@ -2787,7 +2955,7 @@ function processLine(line, state, recordOutputs, toolCallAccumulator) {
2787
2955
  *
2788
2956
  * The span is ended once the consumer finishes reading (or cancels) the stream.
2789
2957
  */
2790
- function instrumentWorkersAiStream(stream, span, recordOutputs) {
2958
+ function instrumentWorkersAiStream(stream, span, recordOutputs, abortSignal, beforeSpanEnd) {
2791
2959
  const reader = stream.getReader();
2792
2960
  const decoder = new TextDecoder();
2793
2961
  const state = {
@@ -2806,7 +2974,7 @@ function instrumentWorkersAiStream(stream, span, recordOutputs) {
2806
2974
  };
2807
2975
  let buffer = "";
2808
2976
  let spanEnded = false;
2809
- const finish = () => {
2977
+ const finish = (result = {}) => {
2810
2978
  if (spanEnded) return;
2811
2979
  spanEnded = true;
2812
2980
  if (recordOutputs) {
@@ -2818,7 +2986,7 @@ function instrumentWorkersAiStream(stream, span, recordOutputs) {
2818
2986
  finishReason: state.finishReasons[0]
2819
2987
  });
2820
2988
  }
2821
- endStreamSpan(span, state, recordOutputs);
2989
+ endStreamSpan(span, state, recordOutputs, () => beforeSpanEnd?.(result));
2822
2990
  };
2823
2991
  const flushBuffer = (isDone) => {
2824
2992
  const lines = buffer.split("\n");
@@ -2836,15 +3004,13 @@ function instrumentWorkersAiStream(stream, span, recordOutputs) {
2836
3004
  controller.close();
2837
3005
  return;
2838
3006
  }
3007
+ recordTimeToFirstChunk(span);
2839
3008
  buffer += decoder.decode(value, { stream: true });
2840
3009
  flushBuffer(false);
2841
3010
  controller.enqueue(value);
2842
3011
  } catch (error) {
2843
- span.setStatus({
2844
- code: _sentry_core.SPAN_STATUS_ERROR,
2845
- message: "internal_error"
2846
- });
2847
- finish();
3012
+ span.setStatus(getErrorStatus(abortSignal));
3013
+ finish({ error });
2848
3014
  controller.error(error);
2849
3015
  }
2850
3016
  },
@@ -2855,6 +3021,7 @@ function instrumentWorkersAiStream(stream, span, recordOutputs) {
2855
3021
  });
2856
3022
  }
2857
3023
  // src/ai/workers-ai/index.ts
3024
+ const originalClients = /* @__PURE__ */ new WeakMap();
2858
3025
  /**
2859
3026
  * Wrap the `run` method of the Workers AI binding with Sentry tracing.
2860
3027
  */
@@ -2863,8 +3030,16 @@ function instrumentRun(originalRun, context, options) {
2863
3030
  if (shouldSkipAiProviderSpan("WorkersAI")) return originalRun.apply(context, args);
2864
3031
  const [model, inputs, runOptions] = args;
2865
3032
  const operationName = getOperationName(model, inputs);
3033
+ const call = {
3034
+ operation: operationName,
3035
+ model,
3036
+ inputs,
3037
+ options: runOptions
3038
+ };
3039
+ const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);
2866
3040
  const requestAttributes = extractRequestAttributes(model, inputs, operationName);
2867
3041
  const modelName = typeof model === "string" && model ? model : "unknown";
3042
+ const abortSignal = getRequestSignal(runOptions);
2868
3043
  const client = (0, _sentry_core.getClient)();
2869
3044
  const isStreamRequested = !!inputs && typeof inputs === "object" && inputs.stream === true;
2870
3045
  const returnsRawResponse = !!runOptions && typeof runOptions === "object" && (runOptions.returnRawResponse === true || runOptions.websocket === true);
@@ -2877,10 +3052,8 @@ function instrumentRun(originalRun, context, options) {
2877
3052
  };
2878
3053
  if (isStreamRequested && !returnsRawResponse) return (0, _sentry_core.startSpanManual)(spanConfig, (span) => {
2879
3054
  const handleError = (error) => {
2880
- span.setStatus({
2881
- code: _sentry_core.SPAN_STATUS_ERROR,
2882
- message: "internal_error"
2883
- });
3055
+ span.setStatus(getErrorStatus(abortSignal));
3056
+ runGenAiSpanEnd(options, span, call, { error });
2884
3057
  span.end();
2885
3058
  throw error;
2886
3059
  };
@@ -2890,20 +3063,28 @@ function instrumentRun(originalRun, context, options) {
2890
3063
  } catch (error) {
2891
3064
  return handleError(error);
2892
3065
  }
2893
- if (options.recordInputs) addRequestAttributes(span, inputs, operationName);
3066
+ if (recordInputs) addRequestAttributes(span, inputs, operationName);
3067
+ runGenAiSpanStart(options, span, call);
2894
3068
  return originalResult.then((result) => {
2895
- if (isReadableStream(result)) return instrumentWorkersAiStream(result, span, options.recordOutputs);
2896
- addResponseAttributes(span, result, options.recordOutputs, operationName);
3069
+ if (isReadableStream(result)) return instrumentWorkersAiStream(result, span, recordOutputs, abortSignal, (streamResult) => runGenAiSpanEnd(options, span, call, streamResult));
3070
+ addResponseAttributes(span, result, recordOutputs, operationName);
3071
+ runGenAiSpanEnd(options, span, call, { response: result });
2897
3072
  span.end();
2898
3073
  return result;
2899
3074
  }, handleError);
2900
3075
  });
2901
3076
  return (0, _sentry_core.startSpan)(spanConfig, (span) => {
2902
3077
  const originalResult = originalRun.apply(context, args);
2903
- if (options.recordInputs) addRequestAttributes(span, inputs, operationName);
3078
+ if (recordInputs) addRequestAttributes(span, inputs, operationName);
3079
+ runGenAiSpanStart(options, span, call);
2904
3080
  return originalResult.then((result) => {
2905
- if (!returnsRawResponse) addResponseAttributes(span, result, options.recordOutputs, operationName);
3081
+ if (!returnsRawResponse) addResponseAttributes(span, result, recordOutputs, operationName);
3082
+ runGenAiSpanEnd(options, span, call, { response: result });
2906
3083
  return result;
3084
+ }, (error) => {
3085
+ span.setStatus(getErrorStatus(abortSignal));
3086
+ runGenAiSpanEnd(options, span, call, { error });
3087
+ throw error;
2907
3088
  });
2908
3089
  });
2909
3090
  };
@@ -2924,12 +3105,14 @@ function instrumentRun(originalRun, context, options) {
2924
3105
  * ```
2925
3106
  */
2926
3107
  function instrumentWorkersAiClient(client, options) {
2927
- const resolvedOptions = resolveAIRecordingOptions(options);
2928
- return new Proxy(client, { get(target, prop, receiver) {
3108
+ const original = originalClients.get(client) ?? client;
3109
+ const instrumented = new Proxy(original, { get(target, prop, receiver) {
2929
3110
  const value = Reflect.get(target, prop, receiver);
2930
- if (prop === "run" && typeof value === "function") return instrumentRun(value, target, resolvedOptions);
3111
+ if (prop === "run" && typeof value === "function") return instrumentRun(value, target, options ?? {});
2931
3112
  return typeof value === "function" ? value.bind(target) : value;
2932
3113
  } });
3114
+ originalClients.set(instrumented, original);
3115
+ return instrumented;
2933
3116
  }
2934
3117
  // src/ai/langchain/constants.ts
2935
3118
  const LANGCHAIN_INTEGRATION_NAME = "LangChain";
@@ -3236,6 +3419,14 @@ function findConversationIdEntry(source) {
3236
3419
  }
3237
3420
  }
3238
3421
  /**
3422
+ * The recording decision of the LangGraph graph run that `metadata` belongs to. The graph's `invoke()`/`stream()`
3423
+ * call decides once, and child runs inherit the decision through their metadata.
3424
+ */
3425
+ function getLangGraphRunRecording(metadata) {
3426
+ const recording = metadata?.__sentry_langgraph__;
3427
+ return (0, _sentry_core.isObjectLike)(recording) ? recording : void 0;
3428
+ }
3429
+ /**
3239
3430
  * Derive `gen_ai.conversation.id` from run metadata, which child runs inherit from their parent.
3240
3431
  * An id from `Sentry.setConversationId()` still wins, since `conversationIdIntegration` applies it on `spanStart`.
3241
3432
  */
@@ -3397,7 +3588,10 @@ function extractEmbeddingAttributes(instance) {
3397
3588
  * span as the prototype-patching path below.
3398
3589
  */
3399
3590
  function _INTERNAL_getLangChainEmbeddingsSpanOptions(instance, input, options = {}) {
3400
- const { recordInputs } = resolveAIRecordingOptions(options);
3591
+ const { recordInputs } = resolveGenAiCallRecording(options, {
3592
+ operation: "embeddings",
3593
+ input
3594
+ });
3401
3595
  const attributes = extractEmbeddingAttributes(instance);
3402
3596
  const modelName = attributes[_sentry_conventions_attributes.GEN_AI_REQUEST_MODEL] || "unknown";
3403
3597
  const client = (0, _sentry_core.getClient)();
@@ -3451,7 +3645,7 @@ function instrumentLangChainEmbeddings(instance, options) {
3451
3645
  * This is a stateful handler that tracks spans across multiple LangChain executions.
3452
3646
  */
3453
3647
  function createLangChainCallbackHandler(options = {}) {
3454
- const { recordInputs, recordOutputs } = resolveAIRecordingOptions(options);
3648
+ const resolveRecording = (call) => getLangGraphRunRecording(call.metadata) ?? resolveGenAiCallRecording(options, call);
3455
3649
  const runs = new _sentry_core.LRUMap(MAX_TRACKED_LANGCHAIN_RUNS);
3456
3650
  const getRun = (runId) => runId ? runs.get(runId) : void 0;
3457
3651
  /**
@@ -3484,7 +3678,7 @@ function createLangChainCallbackHandler(options = {}) {
3484
3678
  if (!(0, _sentry_core.spanIsIgnored)(run.span) || (0, _sentry_core.getRootSpan)(run.span) === run.span) return run.span;
3485
3679
  }
3486
3680
  };
3487
- const startRunSpan = (runId, parentRunId, start) => {
3681
+ const startRunSpan = (runId, parentRunId, recordOutputs, start) => {
3488
3682
  const ancestors = getAncestors(parentRunId);
3489
3683
  const activeSpan = (0, _sentry_core.getActiveSpan)();
3490
3684
  const parentSpan = getParentRunSpan(ancestors, activeSpan);
@@ -3496,7 +3690,8 @@ function createLangChainCallbackHandler(options = {}) {
3496
3690
  span,
3497
3691
  parentRunId,
3498
3692
  activeSpan,
3499
- conversationId
3693
+ conversationId,
3694
+ recordOutputs
3500
3695
  };
3501
3696
  trackRun(runId, run);
3502
3697
  if (conversationId) for (const ancestor of ancestors) {
@@ -3535,13 +3730,23 @@ function createLangChainCallbackHandler(options = {}) {
3535
3730
  ignoreCustomEvent: false,
3536
3731
  raiseError: false,
3537
3732
  awaitHandlers: true,
3538
- handleLLMStart(llm, prompts, runId, parentRunId, _extraParams, tags, metadata, _runName) {
3539
- const invocationParams = getInvocationParams(tags);
3540
- const attributes = extractLLMRequestAttributes(llm, prompts, recordInputs, invocationParams, metadata);
3733
+ handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, _runName) {
3734
+ const serialized = llm;
3735
+ const { recordInputs, recordOutputs } = resolveRecording({
3736
+ operation: "chat",
3737
+ serialized,
3738
+ prompts,
3739
+ runId,
3740
+ parentRunId,
3741
+ extraParams,
3742
+ tags,
3743
+ metadata
3744
+ });
3745
+ const attributes = extractLLMRequestAttributes(serialized, prompts, recordInputs, getInvocationParams(tags), metadata);
3541
3746
  const modelName = attributes[_sentry_conventions_attributes.GEN_AI_REQUEST_MODEL] || "unknown";
3542
3747
  const operationName = typeof attributes[_sentry_conventions_attributes.GEN_AI_OPERATION_NAME] === "string" ? attributes[_sentry_conventions_attributes.GEN_AI_OPERATION_NAME] : "unknown";
3543
3748
  const client = (0, _sentry_core.getClient)();
3544
- startRunSpan(runId, parentRunId, () => (0, _sentry_core.startInactiveSpan)({
3749
+ startRunSpan(runId, parentRunId, recordOutputs, () => (0, _sentry_core.startInactiveSpan)({
3545
3750
  name: typeof modelName === "string" && modelName !== "unknown" || !(client && (0, _sentry_core.hasSpanStreamingEnabled)(client)) ? `${operationName} ${modelName}` : operationName,
3546
3751
  attributes: {
3547
3752
  ...getAgentNameFromMetadata(metadata),
@@ -3552,14 +3757,25 @@ function createLangChainCallbackHandler(options = {}) {
3552
3757
  }));
3553
3758
  },
3554
3759
  handleChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, _runName) {
3555
- const invocationParams = getInvocationParams(tags);
3556
- const attributes = extractChatModelRequestAttributes(llm, messages, recordInputs, invocationParams, metadata);
3760
+ const serialized = llm;
3761
+ const chatMessages = messages;
3762
+ const { recordInputs, recordOutputs } = resolveRecording({
3763
+ operation: "chat",
3764
+ serialized,
3765
+ messages: chatMessages,
3766
+ runId,
3767
+ parentRunId,
3768
+ extraParams,
3769
+ tags,
3770
+ metadata
3771
+ });
3772
+ const attributes = extractChatModelRequestAttributes(serialized, chatMessages, recordInputs, getInvocationParams(tags), metadata);
3557
3773
  const toolDefsJson = recordInputs ? extractToolDefinitions(extraParams) : void 0;
3558
3774
  if (toolDefsJson) attributes[_sentry_conventions_attributes.GEN_AI_TOOL_DEFINITIONS] = toolDefsJson;
3559
3775
  const modelName = attributes[_sentry_conventions_attributes.GEN_AI_REQUEST_MODEL] || "unknown";
3560
3776
  const operationName = typeof attributes[_sentry_conventions_attributes.GEN_AI_OPERATION_NAME] === "string" ? attributes[_sentry_conventions_attributes.GEN_AI_OPERATION_NAME] : "unknown";
3561
3777
  const client = (0, _sentry_core.getClient)();
3562
- startRunSpan(runId, parentRunId, () => (0, _sentry_core.startInactiveSpan)({
3778
+ startRunSpan(runId, parentRunId, recordOutputs, () => (0, _sentry_core.startInactiveSpan)({
3563
3779
  name: typeof modelName === "string" && modelName !== "unknown" || !(client && (0, _sentry_core.hasSpanStreamingEnabled)(client)) ? `${operationName} ${modelName}` : operationName,
3564
3780
  attributes: {
3565
3781
  ...getAgentNameFromMetadata(metadata),
@@ -3569,10 +3785,15 @@ function createLangChainCallbackHandler(options = {}) {
3569
3785
  }
3570
3786
  }));
3571
3787
  },
3572
- handleLLMEnd(output, runId, _parentRunId, _tags, _extraParams) {
3788
+ handleLLMNewToken(_token, _idx, runId) {
3573
3789
  const span = runs.get(runId)?.span;
3574
- if (span?.isRecording()) {
3575
- const attributes = extractLlmResponseAttributes(output, recordOutputs);
3790
+ if (span) recordTimeToFirstChunk(span);
3791
+ },
3792
+ handleLLMEnd(output, runId, _parentRunId, _tags, _extraParams) {
3793
+ const run = runs.get(runId);
3794
+ const span = run?.span;
3795
+ if (run && span?.isRecording()) {
3796
+ const attributes = extractLlmResponseAttributes(output, run.recordOutputs);
3576
3797
  if (attributes) span.setAttributes(attributes);
3577
3798
  }
3578
3799
  exitSpan(runId);
@@ -3585,12 +3806,30 @@ function createLangChainCallbackHandler(options = {}) {
3585
3806
  });
3586
3807
  exitSpan(runId);
3587
3808
  },
3588
- handleChainStart(chain, inputs, runId, parentRunId, _tags, metadata, _runType, runName) {
3809
+ handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, _runType, runName) {
3589
3810
  if (isTypeSafeClassifier(chain)) {
3590
- startRunSpan(runId, parentRunId, () => startTypeSafeClassifierSpan(chain, inputs, metadata, recordInputs)).decide = true;
3811
+ const { recordInputs, recordOutputs } = resolveRecording({
3812
+ operation: "decide",
3813
+ serialized: chain,
3814
+ inputs,
3815
+ runId,
3816
+ parentRunId,
3817
+ tags,
3818
+ metadata
3819
+ });
3820
+ startRunSpan(runId, parentRunId, recordOutputs, () => startTypeSafeClassifierSpan(chain, inputs, metadata, recordInputs)).decide = true;
3591
3821
  return;
3592
3822
  }
3593
3823
  if (metadata?.__sentry_langgraph__) return;
3824
+ const { recordInputs, recordOutputs } = resolveRecording({
3825
+ operation: "invoke_agent",
3826
+ serialized: chain,
3827
+ inputs,
3828
+ runId,
3829
+ parentRunId,
3830
+ tags,
3831
+ metadata
3832
+ });
3594
3833
  const chainName = runName || chain.name;
3595
3834
  const attributes = {
3596
3835
  ...getConversationIdFromMetadata(metadata),
@@ -3600,7 +3839,7 @@ function createLangChainCallbackHandler(options = {}) {
3600
3839
  if (chainName) attributes[_sentry_conventions_attributes.GEN_AI_PIPELINE_NAME] = chainName;
3601
3840
  if (recordInputs) attributes["langchain.chain.inputs"] = JSON.stringify(inputs);
3602
3841
  const client = (0, _sentry_core.getClient)();
3603
- startRunSpan(runId, parentRunId, () => (0, _sentry_core.startInactiveSpan)({
3842
+ startRunSpan(runId, parentRunId, recordOutputs, () => (0, _sentry_core.startInactiveSpan)({
3604
3843
  name: !(client && (0, _sentry_core.hasSpanStreamingEnabled)(client)) ? `chain ${chainName || "unknown_chain"}` : chainName ? `invoke_agent ${chainName}` : "invoke_agent",
3605
3844
  attributes: {
3606
3845
  ...attributes,
@@ -3611,9 +3850,9 @@ function createLangChainCallbackHandler(options = {}) {
3611
3850
  handleChainEnd(outputs, runId) {
3612
3851
  const run = runs.get(runId);
3613
3852
  const span = run?.span;
3614
- if (span?.isRecording()) {
3615
- if (run?.decide) addTypeSafeClassifierResponseAttributes(span, outputs, recordOutputs);
3616
- else if (recordOutputs) span.setAttributes({ "langchain.chain.outputs": JSON.stringify(outputs) });
3853
+ if (run && span?.isRecording()) {
3854
+ if (run.decide) addTypeSafeClassifierResponseAttributes(span, outputs, run.recordOutputs);
3855
+ else if (run.recordOutputs) span.setAttributes({ "langchain.chain.outputs": JSON.stringify(outputs) });
3617
3856
  }
3618
3857
  exitSpan(runId);
3619
3858
  },
@@ -3625,8 +3864,17 @@ function createLangChainCallbackHandler(options = {}) {
3625
3864
  });
3626
3865
  exitSpan(runId);
3627
3866
  },
3628
- handleToolStart(tool, input, runId, parentRunId, _tags, metadata, runName) {
3867
+ handleToolStart(tool, input, runId, parentRunId, tags, metadata, runName) {
3629
3868
  if (metadata?.__sentry_langgraph__) return;
3869
+ const { recordInputs, recordOutputs } = resolveRecording({
3870
+ operation: "execute_tool",
3871
+ serialized: tool,
3872
+ input,
3873
+ runId,
3874
+ parentRunId,
3875
+ tags,
3876
+ metadata
3877
+ });
3630
3878
  const toolName = runName || tool.name || "unknown_tool";
3631
3879
  const attributes = {
3632
3880
  ...getAgentNameFromMetadata(metadata),
@@ -3636,7 +3884,7 @@ function createLangChainCallbackHandler(options = {}) {
3636
3884
  [_sentry_conventions_attributes.GEN_AI_TOOL_NAME]: toolName
3637
3885
  };
3638
3886
  if (recordInputs) attributes[_sentry_conventions_attributes.GEN_AI_TOOL_CALL_ARGUMENTS] = input;
3639
- startRunSpan(runId, parentRunId, () => (0, _sentry_core.startInactiveSpan)({
3887
+ startRunSpan(runId, parentRunId, recordOutputs, () => (0, _sentry_core.startInactiveSpan)({
3640
3888
  name: `execute_tool ${toolName}`,
3641
3889
  attributes: {
3642
3890
  ...attributes,
@@ -3645,9 +3893,10 @@ function createLangChainCallbackHandler(options = {}) {
3645
3893
  }));
3646
3894
  },
3647
3895
  handleToolEnd(output, runId) {
3648
- const span = runs.get(runId)?.span;
3649
- if (span?.isRecording()) {
3650
- if (recordOutputs) {
3896
+ const run = runs.get(runId);
3897
+ const span = run?.span;
3898
+ if (run && span?.isRecording()) {
3899
+ if (run.recordOutputs) {
3651
3900
  const outputObj = output;
3652
3901
  const content = outputObj && typeof outputObj === "object" && "content" in outputObj ? outputObj.content : output;
3653
3902
  span.setAttributes({ [_sentry_conventions_attributes.GEN_AI_TOOL_CALL_RESULT]: (0, _sentry_core.stringify)(content, String) });
@@ -3705,6 +3954,14 @@ function extractAgentNameFromParams(args) {
3705
3954
  if (typeof arg === "object" && !!arg && "name" in arg && typeof arg.name === "string") return arg.name;
3706
3955
  return null;
3707
3956
  }
3957
+ /** The options that hold outside a graph run, where no `invoke()`/`stream()` call decided: a function needs the graph input. */
3958
+ function getBooleanRecordingOptions(options) {
3959
+ const { recordInputs, recordOutputs } = options;
3960
+ return {
3961
+ recordInputs: typeof recordInputs === "boolean" ? recordInputs : void 0,
3962
+ recordOutputs: typeof recordOutputs === "boolean" ? recordOutputs : void 0
3963
+ };
3964
+ }
3708
3965
  /**
3709
3966
  * Wraps an array of LangChain tools so each invocation creates a gen_ai.execute_tool span.
3710
3967
  *
@@ -3726,15 +3983,16 @@ function wrapToolsWithSpans(tools, options, agentName) {
3726
3983
  [_sentry_conventions_attributes.GEN_AI_OPERATION_NAME]: "execute_tool",
3727
3984
  [_sentry_conventions_attributes.GEN_AI_TOOL_NAME]: toolName
3728
3985
  };
3729
- const callConfig = args[1];
3730
- const callAgentName = (callConfig?.metadata)?.lc_agent_name ?? agentName;
3986
+ const metadata = args[1]?.metadata;
3987
+ const { recordInputs, recordOutputs } = getLangGraphRunRecording(metadata) ?? resolveAIRecordingOptions(getBooleanRecordingOptions(options));
3988
+ const callAgentName = metadata?.lc_agent_name ?? agentName;
3731
3989
  if (typeof callAgentName === "string") spanAttributes[_sentry_conventions_attributes.GEN_AI_AGENT_NAME] = callAgentName;
3732
- Object.assign(spanAttributes, getConversationIdFromMetadata(callConfig?.metadata));
3990
+ Object.assign(spanAttributes, getConversationIdFromMetadata(metadata));
3733
3991
  if (toolDescription) spanAttributes[_sentry_conventions_attributes.GEN_AI_TOOL_DESCRIPTION] = toolDescription;
3734
3992
  const input = args[0];
3735
3993
  if (typeof input === "object" && !!input) {
3736
3994
  if ("id" in input && typeof input.id === "string") spanAttributes[GEN_AI_TOOL_CALL_ID_ATTRIBUTE] = input.id;
3737
- if (options.recordInputs) {
3995
+ if (recordInputs) {
3738
3996
  const toolArgs = "args" in input && typeof input.args === "object" ? input.args : input;
3739
3997
  try {
3740
3998
  spanAttributes[_sentry_conventions_attributes.GEN_AI_TOOL_CALL_ARGUMENTS] = JSON.stringify(toolArgs);
@@ -3747,7 +4005,7 @@ function wrapToolsWithSpans(tools, options, agentName) {
3747
4005
  }, async (span) => {
3748
4006
  try {
3749
4007
  const result = await Reflect.apply(target, thisArg, args);
3750
- if (options.recordOutputs) try {
4008
+ if (recordOutputs) try {
3751
4009
  const resultObj = result;
3752
4010
  const content = resultObj && typeof resultObj === "object" && "content" in resultObj ? resultObj.content : result;
3753
4011
  span.setAttribute(_sentry_conventions_attributes.GEN_AI_TOOL_CALL_RESULT, typeof content === "string" ? content : JSON.stringify(content));
@@ -3893,8 +4151,16 @@ function getAgentSpanOptions(args, extraAttributes) {
3893
4151
  }
3894
4152
  };
3895
4153
  }
4154
+ /** Decides for one `invoke()`/`stream()` call, from its arguments as passed. */
4155
+ function resolveGraphCallRecording(options, args) {
4156
+ return resolveGenAiCallRecording(options, {
4157
+ operation: "invoke_agent",
4158
+ input: args[0],
4159
+ config: args[1]
4160
+ });
4161
+ }
3896
4162
  /** Sets the request attributes on an agent span and injects the callback handler into the call's config. */
3897
- function prepareAgentSpan(span, args, graphInstance, compileOptions, options, llm, sentryCallbackHandler) {
4163
+ function prepareAgentSpan(span, args, graphInstance, compileOptions, recording, llm, sentryCallbackHandler) {
3898
4164
  const graphName = compileOptions?.name;
3899
4165
  if (graphName && typeof graphName === "string") {
3900
4166
  span.setAttribute(_sentry_conventions_attributes.GEN_AI_PIPELINE_NAME, graphName);
@@ -3912,12 +4178,12 @@ function prepareAgentSpan(span, args, graphInstance, compileOptions, options, ll
3912
4178
  config.metadata = {
3913
4179
  ...getConversationIdMetadataFromConfig(config),
3914
4180
  ...existingMetadata,
3915
- __sentry_langgraph__: true,
4181
+ __sentry_langgraph__: recording,
3916
4182
  ...typeof graphName === "string" ? { lc_agent_name: graphName } : {}
3917
4183
  };
3918
4184
  config.callbacks = _INTERNAL_mergeLangChainCallbackHandler(config.callbacks, sentryCallbackHandler);
3919
4185
  }
3920
- const recordInputs = options.recordInputs;
4186
+ const { recordInputs } = recording;
3921
4187
  const tools = recordInputs ? extractToolsFromCompiledGraph(graphInstance) : null;
3922
4188
  if (tools) span.setAttribute(_sentry_conventions_attributes.GEN_AI_TOOL_DEFINITIONS, JSON.stringify(tools));
3923
4189
  const inputState = args[0];
@@ -3945,6 +4211,7 @@ function prepareAgentSpan(span, args, graphInstance, compileOptions, options, ll
3945
4211
  function instrumentCompiledGraphStream(originalStream, graphInstance, compileOptions, options, llm, sentryCallbackHandler) {
3946
4212
  return new Proxy(originalStream, { apply(target, thisArg, args) {
3947
4213
  if (isInvokeInternalStream(graphInstance)) return Reflect.apply(target, thisArg, args);
4214
+ const recording = resolveGraphCallRecording(options, args);
3948
4215
  return (0, _sentry_core.startSpanManual)(getAgentSpanOptions(args, { [_sentry_conventions_attributes.GEN_AI_RESPONSE_STREAMING]: true }), async (span) => {
3949
4216
  let inputMessages = null;
3950
4217
  let stream;
@@ -3958,7 +4225,7 @@ function instrumentCompiledGraphStream(originalStream, graphInstance, compileOpt
3958
4225
  code: _sentry_core.SPAN_STATUS_ERROR,
3959
4226
  message: "internal_error"
3960
4227
  });
3961
- } else if (outcome && options.recordOutputs) setResponseAttributes(span, inputMessages, outcome.outputs);
4228
+ } else if (outcome && recording.recordOutputs) setResponseAttributes(span, inputMessages, outcome.outputs);
3962
4229
  } catch {}
3963
4230
  span.end();
3964
4231
  inputMessages = null;
@@ -3981,7 +4248,7 @@ function instrumentCompiledGraphStream(originalStream, graphInstance, compileOpt
3981
4248
  }
3982
4249
  };
3983
4250
  try {
3984
- inputMessages = prepareAgentSpan(span, args, graphInstance, compileOptions, options, llm, sentryCallbackHandler);
4251
+ inputMessages = prepareAgentSpan(span, args, graphInstance, compileOptions, recording, llm, sentryCallbackHandler);
3985
4252
  const config = args[1];
3986
4253
  config.callbacks = _INTERNAL_addLangChainCallbackHandler(config.callbacks, listener);
3987
4254
  stream = await Reflect.apply(target, thisArg, args);
@@ -4037,10 +4304,9 @@ function runManually(callback) {
4037
4304
  * Instruments StateGraph's compile method to wrap the returned compiled graph's invoke() and stream() with a
4038
4305
  * `gen_ai.invoke_agent` span.
4039
4306
  */
4040
- function instrumentStateGraphCompile(originalCompile, rawOptions) {
4307
+ function instrumentStateGraphCompile(originalCompile, options) {
4041
4308
  if (Object.prototype.hasOwnProperty.call(originalCompile, SENTRY_PATCHED)) return originalCompile;
4042
- const options = resolveAIRecordingOptions(rawOptions);
4043
- const sentryHandler = createLangChainCallbackHandler(options);
4309
+ const sentryHandler = createLangChainCallbackHandler(getBooleanRecordingOptions(options));
4044
4310
  const wrapped = new Proxy(originalCompile, { apply(target, thisArg, args) {
4045
4311
  if (_insideManualInstrumentation) return Reflect.apply(target, thisArg, args);
4046
4312
  const compiledGraph = runManually(() => Reflect.apply(target, thisArg, args));
@@ -4071,11 +4337,12 @@ function instrumentCompiledGraph(graph, compileOptions, options, llm, sentryCall
4071
4337
  */
4072
4338
  function instrumentCompiledGraphInvoke(originalInvoke, graphInstance, compileOptions, options, llm, sentryCallbackHandler) {
4073
4339
  return new Proxy(originalInvoke, { apply(target, thisArg, args) {
4340
+ const recording = resolveGraphCallRecording(options, args);
4074
4341
  return (0, _sentry_core.startSpan)(getAgentSpanOptions(args), async (span) => {
4075
4342
  try {
4076
- const inputMessages = prepareAgentSpan(span, args, graphInstance, compileOptions, options, llm, sentryCallbackHandler);
4343
+ const inputMessages = prepareAgentSpan(span, args, graphInstance, compileOptions, recording, llm, sentryCallbackHandler);
4077
4344
  const result = await callInvoke(graphInstance, () => Reflect.apply(target, thisArg, args));
4078
- if (options.recordOutputs) setResponseAttributes(span, inputMessages, result);
4345
+ if (recording.recordOutputs) setResponseAttributes(span, inputMessages, result);
4079
4346
  return result;
4080
4347
  } catch (error) {
4081
4348
  span.setStatus({
@@ -4090,17 +4357,16 @@ function instrumentCompiledGraphInvoke(originalInvoke, graphInstance, compileOpt
4090
4357
  /**
4091
4358
  * Instruments createReactAgent to create invoke_agent and execute_tool spans.
4092
4359
  */
4093
- function instrumentCreateReactAgent(originalCreateReactAgent, options) {
4360
+ function instrumentCreateReactAgent(originalCreateReactAgent, options = {}) {
4094
4361
  if (Object.prototype.hasOwnProperty.call(originalCreateReactAgent, SENTRY_PATCHED)) return originalCreateReactAgent;
4095
- const resolvedOptions = resolveAIRecordingOptions(options);
4096
- const sentryHandler = createLangChainCallbackHandler(resolvedOptions);
4362
+ const sentryHandler = createLangChainCallbackHandler(getBooleanRecordingOptions(options));
4097
4363
  const wrapped = new Proxy(originalCreateReactAgent, { apply(target, thisArg, args) {
4098
4364
  const llm = extractLLMFromParams(args);
4099
4365
  const agentName = extractAgentNameFromParams(args);
4100
4366
  const params = args[0];
4101
- if (params && Array.isArray(params.tools) && params.tools.length > 0) wrapToolsWithSpans(params.tools, resolvedOptions, agentName ?? void 0);
4367
+ if (params && Array.isArray(params.tools) && params.tools.length > 0) wrapToolsWithSpans(params.tools, options, agentName ?? void 0);
4102
4368
  const compiledGraph = runManually(() => Reflect.apply(target, thisArg, args));
4103
- instrumentCompiledGraph(compiledGraph, agentName ? { name: agentName } : {}, resolvedOptions, llm, sentryHandler);
4369
+ instrumentCompiledGraph(compiledGraph, agentName ? { name: agentName } : {}, options, llm, sentryHandler);
4104
4370
  return compiledGraph;
4105
4371
  } });
4106
4372
  Object.defineProperty(wrapped, SENTRY_PATCHED, {
@@ -4132,8 +4398,8 @@ function instrumentCreateReactAgent(originalCreateReactAgent, options) {
4132
4398
  * const compiled = graph.compile({ name: 'my_agent' });
4133
4399
  * ```
4134
4400
  */
4135
- function instrumentStateGraph(stateGraph, options) {
4136
- stateGraph.compile = instrumentStateGraphCompile(stateGraph.compile, resolveAIRecordingOptions(options));
4401
+ function instrumentStateGraph(stateGraph, options = {}) {
4402
+ stateGraph.compile = instrumentStateGraphCompile(stateGraph.compile, options);
4137
4403
  return stateGraph;
4138
4404
  }
4139
4405
  // src/ai/mastra/constants.ts
@@ -4275,10 +4541,7 @@ function mergeUsageAttributes(existing, incoming) {
4275
4541
  /** Convention attributes only. Called on start and end — Mastra fills fields progressively. */
4276
4542
  function getSpanAttributes(span, options) {
4277
4543
  const operationName = getOperation(span.type)?.operationName;
4278
- const attributes = {
4279
- [_sentry_conventions_attributes.GEN_AI_OPERATION_NAME]: operationName,
4280
- [_sentry_conventions_attributes.GEN_AI_CONVERSATION_ID]: span.attributes?.conversationId ?? span.metadata?.threadId
4281
- };
4544
+ const attributes = { [_sentry_conventions_attributes.GEN_AI_OPERATION_NAME]: operationName };
4282
4545
  if (AGENT_SPAN_TYPES.has(span.type)) addAgentAttributes(attributes, span, options);
4283
4546
  if (MODEL_SPAN_TYPES.has(span.type) || span.type === "rag_embedding") addModelAttributes(attributes, span, options);
4284
4547
  if (TOOL_SPAN_TYPES.has(span.type)) addToolAttributes(attributes, span, options);
@@ -4309,6 +4572,7 @@ function addModelAttributes(attributes, span, options) {
4309
4572
  attributes[_sentry_conventions_attributes.GEN_AI_RESPONSE_MODEL] = attrs.responseModel;
4310
4573
  attributes[_sentry_conventions_attributes.GEN_AI_RESPONSE_ID] = attrs.responseId;
4311
4574
  attributes[_sentry_conventions_attributes.GEN_AI_RESPONSE_STREAMING] = attrs.streaming;
4575
+ attributes[_sentry_conventions_attributes.GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK] = attrs.completionStartTime ? (attrs.completionStartTime.getTime() - span.startTime.getTime()) / 1e3 : void 0;
4312
4576
  attributes[_sentry_conventions_attributes.GEN_AI_RESPONSE_FINISH_REASONS] = attrs.finishReason ? JSON.stringify([attrs.finishReason]) : void 0;
4313
4577
  attributes[_sentry_conventions_attributes.GEN_AI_AGENT_NAME] = span.entityName;
4314
4578
  attributes[_sentry_conventions_attributes.GEN_AI_REQUEST_TEMPERATURE] = parameters.temperature;
@@ -4433,7 +4697,7 @@ var SentryMastraExporter = class {
4433
4697
  /** End open spans, then flush. Does not close the Sentry client. */
4434
4698
  async shutdown() {
4435
4699
  for (const id of this._spans.keys()) unregisterMastraSpan(id);
4436
- for (const { span } of this._spans.values()) span.end();
4700
+ for (const tracked of this._spans.values()) this._endSpan(tracked, {});
4437
4701
  this._spans.clear();
4438
4702
  this._skipped.clear();
4439
4703
  await this.flush();
@@ -4446,18 +4710,19 @@ var SentryMastraExporter = class {
4446
4710
  else if (event.type === "span_ended") this._skipped.remove(span.id);
4447
4711
  return;
4448
4712
  }
4449
- const recordingOptions = resolveAIRecordingOptions(this._options);
4450
4713
  switch (event.type) {
4451
4714
  case "span_started":
4452
- this._onSpanStarted(span, recordingOptions);
4715
+ this._onSpanStarted(span);
4453
4716
  break;
4454
4717
  case "span_updated":
4455
- this._onSpanUpdated(span, recordingOptions);
4718
+ this._onSpanUpdated(span);
4456
4719
  break;
4457
- case "span_ended": this._onSpanEnded(span, recordingOptions);
4720
+ case "span_ended": this._onSpanEnded(span);
4458
4721
  }
4459
4722
  }
4460
- _onSpanStarted(span, recordingOptions) {
4723
+ _onSpanStarted(span) {
4724
+ const call = { span };
4725
+ const recordingOptions = resolveGenAiCallRecording(this._options, call);
4461
4726
  const parentId = this._resolveParentId(span.parentSpanId);
4462
4727
  const parentSpan = parentId ? this._spans.get(parentId)?.span : void 0;
4463
4728
  const activeSpan = (0, _sentry_core.getActiveSpan)();
@@ -4467,10 +4732,12 @@ var SentryMastraExporter = class {
4467
4732
  parentSpan: parentSpan ?? activeSpan,
4468
4733
  attributes: {
4469
4734
  ...getSpanAttributes(span, recordingOptions),
4735
+ [_sentry_conventions_attributes.GEN_AI_CONVERSATION_ID]: span.attributes?.conversationId ?? span.metadata?.threadId,
4470
4736
  [_sentry_conventions_attributes.SENTRY_OP]: getOperation(span.type)?.op,
4471
4737
  [_sentry_conventions_attributes.SENTRY_ORIGIN]: MASTRA_ORIGIN
4472
4738
  }
4473
4739
  });
4740
+ runGenAiSpanStart(this._options, sentrySpan, call);
4474
4741
  const evaluation = span.type === "classifier_evaluation" ? takeStartingClassifierEvaluation() : void 0;
4475
4742
  if (evaluation) Object.assign(evaluation, {
4476
4743
  span: sentrySpan,
@@ -4481,37 +4748,47 @@ var SentryMastraExporter = class {
4481
4748
  });
4482
4749
  this._trackSpan(span.id, {
4483
4750
  span: sentrySpan,
4751
+ call,
4484
4752
  spanType: span.type,
4485
4753
  usage: {},
4754
+ recordingOptions,
4486
4755
  evaluation
4487
4756
  });
4488
4757
  }
4489
4758
  /** Track a started span, ending any Sentry span that would otherwise be dropped without `end()`. */
4490
4759
  _trackSpan(id, tracked) {
4491
- this._removeTracked(id)?.span.end();
4760
+ this._endTracked(id);
4492
4761
  if (this._spans.size >= 1e3) {
4493
4762
  const oldestId = this._spans.keys()[0];
4494
- if (oldestId !== void 0) this._removeTracked(oldestId)?.span.end();
4763
+ if (oldestId !== void 0) this._endTracked(oldestId);
4495
4764
  }
4496
4765
  this._spans.set(id, tracked);
4497
4766
  registerMastraSpan(id, tracked.span);
4498
4767
  }
4768
+ _endTracked(id) {
4769
+ const tracked = this._removeTracked(id);
4770
+ if (tracked) this._endSpan(tracked, {});
4771
+ }
4772
+ _endSpan(tracked, result, endTime) {
4773
+ runGenAiSpanEnd(this._options, tracked.span, tracked.call, result);
4774
+ tracked.span.end(endTime);
4775
+ }
4499
4776
  /** Remove a tracked span and keep the id→span registry in lockstep. */
4500
4777
  _removeTracked(id) {
4501
4778
  unregisterMastraSpan(id);
4502
4779
  return this._spans.remove(id);
4503
4780
  }
4504
- _onSpanUpdated(span, recordingOptions) {
4781
+ _onSpanUpdated(span) {
4505
4782
  const tracked = this._spans.get(span.id);
4506
- if (tracked) tracked.span.setAttributes(getSpanAttributes(span, recordingOptions));
4783
+ if (tracked) tracked.span.setAttributes(getSpanAttributes(span, tracked.recordingOptions));
4507
4784
  }
4508
- _onSpanEnded(span, recordingOptions) {
4785
+ _onSpanEnded(span) {
4509
4786
  const tracked = this._spans.get(span.id);
4510
4787
  if (!tracked) {
4511
4788
  require_debug_build.DEBUG_BUILD && _sentry_core.debug.warn(`[Mastra] no Sentry span open for ended span ${span.id} (${span.name})`);
4512
4789
  return;
4513
4790
  }
4514
- const { span: sentrySpan } = tracked;
4791
+ const { span: sentrySpan, recordingOptions } = tracked;
4515
4792
  sentrySpan.setAttributes(getSpanAttributes(span, recordingOptions));
4516
4793
  sentrySpan.updateName(getSpanName(span));
4517
4794
  if (MODEL_SPAN_TYPES.has(span.type)) this._rollUpToParentAgent(span);
@@ -4519,9 +4796,12 @@ var SentryMastraExporter = class {
4519
4796
  code: _sentry_core.SPAN_STATUS_ERROR,
4520
4797
  message: span.errorInfo.message
4521
4798
  });
4799
+ const result = span.errorInfo ? { error: span.errorInfo } : { response: span };
4522
4800
  const { evaluation } = tracked;
4523
- if (evaluation && !evaluation.settled) evaluation.endTime = span.endTime ?? (0, _sentry_core.timestampInSeconds)();
4524
- else sentrySpan.end(span.endTime);
4801
+ if (evaluation && !evaluation.settled) {
4802
+ const endTime = span.endTime ?? (0, _sentry_core.timestampInSeconds)();
4803
+ evaluation.end = () => this._endSpan(tracked, result, endTime);
4804
+ } else this._endSpan(tracked, result, span.endTime);
4525
4805
  this._removeTracked(span.id);
4526
4806
  }
4527
4807
  /** Copy model/usage onto the parent agent so the AI Agents view shows totals. */
@@ -4602,7 +4882,7 @@ function detectOrchestrionSetup() {
4602
4882
  if (!marker.warnedBunRunNotInjected) {
4603
4883
  marker.warnedBunRunNotInjected = true;
4604
4884
  (0, _sentry_core.consoleSandbox)(() => {
4605
- console.warn("[Sentry] No diagnostics-channel injection detected. Channel-based integrations will not record spans or capture errors, because Bun cannot instrument modules at runtime. Build your app with `@sentry/bun/plugin` to enable them.");
4885
+ console.warn("[Sentry] No diagnostics-channel injection detected. Channel-based integrations will not record spans or capture errors. On Bun 1.4.6 or later, run your app with `bun --preload @sentry/bun/import`. Or build your app with `@sentry/bun/plugin`.");
4606
4886
  });
4607
4887
  }
4608
4888
  return;
@@ -4614,26 +4894,44 @@ function detectOrchestrionSetup() {
4614
4894
  _sentry_core.debug.log(bundler ? `[Sentry] Bundler plugin ran, injected libraries=${JSON.stringify(bundler instanceof Set ? [...bundler] : bundler)}` : "[Sentry] Bundler plugin did not run");
4615
4895
  }
4616
4896
  // src/ai/pi-ai/recording.ts
4617
- const RECORDING_OPTIONS_KEY = "piAiRecordingOptions";
4618
- /**
4619
- * Apply the recording options of an integration that sends its model calls through pi-ai, such as
4620
- * Flue, to the `gen_ai.chat` spans of the requests sent under `scope`.
4621
- */
4622
- function setPiAiRecordingOptions(scope, options) {
4623
- scope.setSDKProcessingMetadata({ [RECORDING_OPTIONS_KEY]: options });
4897
+ const DRIVER_KEY = "piAiDriver";
4898
+ /**
4899
+ * Apply the recording options and span hooks of an integration that sends its model calls through
4900
+ * pi-ai, such as Flue, to the `gen_ai.chat` spans of the requests sent under `scope`. Options and
4901
+ * hooks that are functions get `call`.
4902
+ */
4903
+ function setPiAiDriverOptions(scope, options, call) {
4904
+ const driver = {
4905
+ recording: () => ({
4906
+ recordInputs: resolveRecordingOption(options.recordInputs, call),
4907
+ recordOutputs: resolveRecordingOption(options.recordOutputs, call)
4908
+ }),
4909
+ onSpanStart: (span) => runGenAiSpanStart(options, span, call),
4910
+ onSpanEnd: (span, result) => runGenAiSpanEnd(options, span, call, result)
4911
+ };
4912
+ scope.setSDKProcessingMetadata({ [DRIVER_KEY]: driver });
4913
+ }
4914
+ /** The integration driving the pi-ai requests sent from the current scope, if any. */
4915
+ function getPiAiDriver() {
4916
+ return (0, _sentry_core.getCurrentScope)().getScopeData().sdkProcessingMetadata[DRIVER_KEY];
4624
4917
  }
4625
4918
  /**
4626
4919
  * The recording options of a pi-ai request, read when it starts: its response can settle outside the
4627
- * scope it was sent from. An explicit `false` on either integration keeps the content out, since an
4628
- * opt-out must not depend on which integration it was set on. Otherwise the integration driving
4629
- * pi-ai comes first, then `piAiIntegration`, then `dataCollection.genAI`.
4630
- */
4631
- function resolvePiAiRecordingOptions(options) {
4632
- const driver = (0, _sentry_core.getCurrentScope)().getScopeData().sdkProcessingMetadata[RECORDING_OPTIONS_KEY];
4633
- const { recordInputs, recordOutputs } = resolveAIRecordingOptions(options);
4920
+ * scope it was sent from. An explicit `false` on either integration, or from either one's function,
4921
+ * keeps the content out, since an opt-out must not depend on which integration it was set on.
4922
+ * Otherwise the integration driving pi-ai comes first, then `piAiIntegration`, then
4923
+ * `dataCollection.genAI`.
4924
+ */
4925
+ function resolvePiAiRecordingOptions(options, call, driver = getPiAiDriver()) {
4926
+ const driverRecording = driver?.recording();
4927
+ const own = {
4928
+ recordInputs: resolveRecordingOption(options.recordInputs, call),
4929
+ recordOutputs: resolveRecordingOption(options.recordOutputs, call)
4930
+ };
4931
+ const { recordInputs, recordOutputs } = resolveGenAiCallRecording(own, call);
4634
4932
  return {
4635
- recordInputs: options.recordInputs !== false && (driver?.recordInputs ?? recordInputs),
4636
- recordOutputs: options.recordOutputs !== false && (driver?.recordOutputs ?? recordOutputs)
4933
+ recordInputs: own.recordInputs !== false && (driverRecording?.recordInputs ?? recordInputs),
4934
+ recordOutputs: own.recordOutputs !== false && (driverRecording?.recordOutputs ?? recordOutputs)
4637
4935
  };
4638
4936
  }
4639
4937
  // src/ai/flue/constants.ts
@@ -4803,16 +5101,8 @@ function piAiPartToGenAiPart(part) {
4803
5101
  }
4804
5102
  }
4805
5103
  // src/ai/flue/utils.ts
4806
- /**
4807
- * Flue persists the incoming W3C `traceparent` at admission and replays it on the agent operation.
4808
- * Sentry's own propagation uses `sentry-trace`, so the carrier has to be converted before it can
4809
- * continue the trace. Kept local until something else needs a W3C parser.
4810
- */
4811
- function sentryTraceFromTraceparent(traceparent) {
4812
- const [version, traceId, spanId, flags] = traceparent.split("-");
4813
- if (version !== "00" || !traceId || !spanId || !flags) return;
4814
- return `${traceId}-${spanId}-${parseInt(flags, 16) % 2 === 1 ? "1" : "0"}`;
4815
- }
5104
+ const TOOL_SPANS_RECORDING_OUTPUTS = /* @__PURE__ */ new WeakSet();
5105
+ const TOOL_SPAN_END_HOOKS = /* @__PURE__ */ new WeakMap();
4816
5106
  /**
4817
5107
  * Store a span under `key`. Callers only reach this with a key the tracker does not hold, so the
4818
5108
  * one span at risk of being dropped without `end()` is the oldest entry, which `LRUMap.set` silently
@@ -4853,10 +5143,16 @@ function captureToolError(span, errorInfo) {
4853
5143
  * OpenTelemetry adapter projects them: siblings of `chat`, correlated to model output by tool call
4854
5144
  * id. Keyed by `toolCallId` so concurrent tool calls in one turn cannot cross-attribute.
4855
5145
  */
4856
- function startToolSpan(observation, toolSpans, recordInputs) {
5146
+ function startToolSpan(observation, context, toolSpans, options) {
4857
5147
  const { toolCallId, toolName } = observation;
4858
5148
  if (!toolCallId || toolSpans.get(toolCallId)) return;
4859
- trackSpan(toolSpans, toolCallId, (0, _sentry_core.startInactiveSpan)({
5149
+ const call = {
5150
+ operation: "execute_tool",
5151
+ observation,
5152
+ context
5153
+ };
5154
+ const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);
5155
+ const span = (0, _sentry_core.startInactiveSpan)({
4860
5156
  name: `execute_tool ${toolName ?? "unknown"}`,
4861
5157
  op: getGenAiSpanOp("execute_tool"),
4862
5158
  attributes: {
@@ -4866,14 +5162,21 @@ function startToolSpan(observation, toolSpans, recordInputs) {
4866
5162
  [_sentry_conventions_attributes.GEN_AI_CONVERSATION_ID]: observation.conversationId,
4867
5163
  ...recordInputs && observation.args !== void 0 ? { [_sentry_conventions_attributes.GEN_AI_TOOL_CALL_ARGUMENTS]: (0, _sentry_core.stringify)(observation.args) } : {}
4868
5164
  }
4869
- }));
4870
- }
4871
- function endToolSpan(observation, toolSpans, recordOutputs) {
5165
+ });
5166
+ if (recordOutputs) TOOL_SPANS_RECORDING_OUTPUTS.add(span);
5167
+ runGenAiSpanStart(options, span, call);
5168
+ TOOL_SPAN_END_HOOKS.set(span, (end) => runGenAiSpanEnd(options, span, call, end.isError ? {
5169
+ response: end,
5170
+ error: end.errorInfo
5171
+ } : { response: end }));
5172
+ trackSpan(toolSpans, toolCallId, span);
5173
+ }
5174
+ function endToolSpan(observation, toolSpans) {
4872
5175
  const { toolCallId } = observation;
4873
5176
  const span = toolCallId ? toolSpans.get(toolCallId) : void 0;
4874
5177
  if (!span || !toolCallId) return;
4875
5178
  toolSpans.remove(toolCallId);
4876
- if (recordOutputs) {
5179
+ if (TOOL_SPANS_RECORDING_OUTPUTS.has(span)) {
4877
5180
  const result = toolResultForModel(observation);
4878
5181
  if (result !== void 0) span.setAttribute(_sentry_conventions_attributes.GEN_AI_TOOL_CALL_RESULT, result);
4879
5182
  }
@@ -4884,6 +5187,7 @@ function endToolSpan(observation, toolSpans, recordOutputs) {
4884
5187
  });
4885
5188
  captureToolError(span, observation.errorInfo);
4886
5189
  }
5190
+ TOOL_SPAN_END_HOOKS.get(span)?.(observation);
4887
5191
  span.end();
4888
5192
  }
4889
5193
  /**
@@ -4916,7 +5220,7 @@ function warnIfPiAiNotInstrumented() {
4916
5220
  });
4917
5221
  }
4918
5222
  function getPiAiInstrumentationHint() {
4919
- if (isBun()) return "Build your app with `sentryBunPlugin()` from `@sentry/bun/plugin`; `bun run` cannot instrument it.";
5223
+ if (isBun()) return "On Bun 1.4.6 or later, run your app with `bun --preload @sentry/bun/import app.ts`. Or build it with `sentryBunPlugin()` from `@sentry/bun/plugin`.";
4920
5224
  if (isDeno()) return "Run your app with `deno run --preload=npm:@sentry/deno/import app.ts`.";
4921
5225
  if (isCloudflareWorkers()) return "Add `sentryCloudflareVitePlugin()` from `@sentry/cloudflare/vite` to your Vite config.";
4922
5226
  return "Load Sentry with `--import`, for example `node --import ./instrument.mjs app.mjs`.";
@@ -4945,8 +5249,8 @@ function runInAdmissionContext(admission, next) {
4945
5249
  * as a `gen_ai.chat` span under the agent span.
4946
5250
  *
4947
5251
  * Tool arguments and results are gated on `recordInputs`/`recordOutputs`, which fall back to the
4948
- * current client's `dataCollection.genAI` settings and are read per event. The same options apply to
4949
- * the message content of the `gen_ai.chat` spans.
5252
+ * current client's `dataCollection.genAI` settings and are decided when each tool span starts. The
5253
+ * same options apply to the message content of the `gen_ai.chat` spans.
4950
5254
  */
4951
5255
  function createFlueInstrumentation(options = {}) {
4952
5256
  const agentSpans = /* @__PURE__ */ new Map();
@@ -4964,7 +5268,11 @@ function createFlueInstrumentation(options = {}) {
4964
5268
  const { conversationId } = ctx;
4965
5269
  return (0, _sentry_core.withScope)((scope) => {
4966
5270
  if (conversationId) scope.setConversationId(conversationId);
4967
- setPiAiRecordingOptions(scope, options);
5271
+ setPiAiDriverOptions(scope, options, {
5272
+ operation: "chat",
5273
+ execution: operation,
5274
+ context: ctx
5275
+ });
4968
5276
  return next();
4969
5277
  });
4970
5278
  }
@@ -4989,14 +5297,13 @@ function createFlueInstrumentation(options = {}) {
4989
5297
  agentSpans.delete(operationId);
4990
5298
  }
4991
5299
  });
4992
- const sentryTrace = ctx.traceCarrier?.traceparent ? sentryTraceFromTraceparent(ctx.traceCarrier.traceparent) : void 0;
5300
+ const sentryTrace = ctx.traceCarrier?.traceparent ? (0, _sentry_core.sentryTraceFromTraceparent)(ctx.traceCarrier.traceparent) : void 0;
4993
5301
  return sentryTrace && !(0, _sentry_core.getActiveSpan)() ? (0, _sentry_core.continueTrace)({
4994
5302
  sentryTrace,
4995
5303
  baggage: void 0
4996
5304
  }, openAgentSpan) : openAgentSpan();
4997
5305
  },
4998
- observe: (observation) => {
4999
- const { recordInputs, recordOutputs } = resolveAIRecordingOptions(options);
5306
+ observe: (observation, ctx) => {
5000
5307
  const agentSpan = observation.operationId ? agentSpans.get(observation.operationId) : void 0;
5001
5308
  if (agentSpan) {
5002
5309
  if (observation.conversationId) agentSpan.setAttribute(_sentry_conventions_attributes.GEN_AI_CONVERSATION_ID, observation.conversationId);
@@ -5016,10 +5323,10 @@ function createFlueInstrumentation(options = {}) {
5016
5323
  if (observation.submissionId) admissions.remove(observation.submissionId);
5017
5324
  return;
5018
5325
  case "tool_start":
5019
- startToolSpan(observation, toolSpans, recordInputs);
5326
+ startToolSpan(observation, ctx, toolSpans, options);
5020
5327
  return;
5021
5328
  case "tool":
5022
- endToolSpan(observation, toolSpans, recordOutputs);
5329
+ endToolSpan(observation, toolSpans);
5023
5330
  return;
5024
5331
  default: return;
5025
5332
  }
@@ -6570,6 +6877,18 @@ Object.defineProperty(exports, "getAbortSignal", {
6570
6877
  return getAbortSignal;
6571
6878
  }
6572
6879
  });
6880
+ Object.defineProperty(exports, "getBooleanRecordingOptions", {
6881
+ enumerable: true,
6882
+ get: function() {
6883
+ return getBooleanRecordingOptions;
6884
+ }
6885
+ });
6886
+ Object.defineProperty(exports, "getCallAbortSignal", {
6887
+ enumerable: true,
6888
+ get: function() {
6889
+ return getCallAbortSignal;
6890
+ }
6891
+ });
6573
6892
  Object.defineProperty(exports, "getConversationIdMetadataFromConfig", {
6574
6893
  enumerable: true,
6575
6894
  get: function() {
@@ -6624,6 +6943,12 @@ Object.defineProperty(exports, "getMiddlewareFlags", {
6624
6943
  return getMiddlewareFlags;
6625
6944
  }
6626
6945
  });
6946
+ Object.defineProperty(exports, "getMistralRequestSignal", {
6947
+ enumerable: true,
6948
+ get: function() {
6949
+ return getMistralRequestSignal;
6950
+ }
6951
+ });
6627
6952
  Object.defineProperty(exports, "getOrchestrionInjectedModules", {
6628
6953
  enumerable: true,
6629
6954
  get: function() {
@@ -6636,6 +6961,12 @@ Object.defineProperty(exports, "getOtlpTracesEndpoint", {
6636
6961
  return getOtlpTracesEndpoint;
6637
6962
  }
6638
6963
  });
6964
+ Object.defineProperty(exports, "getPiAiDriver", {
6965
+ enumerable: true,
6966
+ get: function() {
6967
+ return getPiAiDriver;
6968
+ }
6969
+ });
6639
6970
  Object.defineProperty(exports, "getProviderName", {
6640
6971
  enumerable: true,
6641
6972
  get: function() {
@@ -6912,16 +7243,16 @@ Object.defineProperty(exports, "processClassifierEvaluationData", {
6912
7243
  return processClassifierEvaluationData;
6913
7244
  }
6914
7245
  });
6915
- Object.defineProperty(exports, "recordTypeSafeClassifierState", {
7246
+ Object.defineProperty(exports, "recordTimeToFirstChunk", {
6916
7247
  enumerable: true,
6917
7248
  get: function() {
6918
- return recordTypeSafeClassifierState;
7249
+ return recordTimeToFirstChunk;
6919
7250
  }
6920
7251
  });
6921
- Object.defineProperty(exports, "resolveAIRecordingOptions", {
7252
+ Object.defineProperty(exports, "recordTypeSafeClassifierState", {
6922
7253
  enumerable: true,
6923
7254
  get: function() {
6924
- return resolveAIRecordingOptions;
7255
+ return recordTypeSafeClassifierState;
6925
7256
  }
6926
7257
  });
6927
7258
  Object.defineProperty(exports, "resolveChatParams", {
@@ -6930,12 +7261,36 @@ Object.defineProperty(exports, "resolveChatParams", {
6930
7261
  return resolveChatParams;
6931
7262
  }
6932
7263
  });
7264
+ Object.defineProperty(exports, "resolveGenAiCallRecording", {
7265
+ enumerable: true,
7266
+ get: function() {
7267
+ return resolveGenAiCallRecording;
7268
+ }
7269
+ });
6933
7270
  Object.defineProperty(exports, "resolvePiAiRecordingOptions", {
6934
7271
  enumerable: true,
6935
7272
  get: function() {
6936
7273
  return resolvePiAiRecordingOptions;
6937
7274
  }
6938
7275
  });
7276
+ Object.defineProperty(exports, "resolveRecordingOption", {
7277
+ enumerable: true,
7278
+ get: function() {
7279
+ return resolveRecordingOption;
7280
+ }
7281
+ });
7282
+ Object.defineProperty(exports, "runGenAiSpanEnd", {
7283
+ enumerable: true,
7284
+ get: function() {
7285
+ return runGenAiSpanEnd;
7286
+ }
7287
+ });
7288
+ Object.defineProperty(exports, "runGenAiSpanStart", {
7289
+ enumerable: true,
7290
+ get: function() {
7291
+ return runGenAiSpanStart;
7292
+ }
7293
+ });
6939
7294
  Object.defineProperty(exports, "sanitizeSqlQuery", {
6940
7295
  enumerable: true,
6941
7296
  get: function() {
@@ -6954,10 +7309,10 @@ Object.defineProperty(exports, "setHttpServerSpanRouteAttribute", {
6954
7309
  return setHttpServerSpanRouteAttribute;
6955
7310
  }
6956
7311
  });
6957
- Object.defineProperty(exports, "setPiAiRecordingOptions", {
7312
+ Object.defineProperty(exports, "setPiAiDriverOptions", {
6958
7313
  enumerable: true,
6959
7314
  get: function() {
6960
- return setPiAiRecordingOptions;
7315
+ return setPiAiDriverOptions;
6961
7316
  }
6962
7317
  });
6963
7318
  Object.defineProperty(exports, "setStartingClassifierEvaluation", {