@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
@@ -1 +1 @@
1
- {"version":3,"file":"streaming.js","names":[],"sources":["../../../../src/ai/openai/streaming.ts"],"sourcesContent":["import { captureException, SPAN_STATUS_ERROR } from '@sentry/core';\nimport type { Span } from '@sentry/core';\nimport { getToolCallKey } from '../core/streaming-tool-calls';\nimport { endStreamSpan } from '../core/utils';\nimport { RESPONSE_EVENT_TYPES } from './constants';\nimport type {\n ChatCompletionChunk,\n ChatCompletionToolCall,\n OpenAIResponseObject,\n ResponseFunctionCall,\n ResponseStreamingEvent,\n} from './types';\nimport { isChatCompletionChunk, isResponsesApiStreamEvent } from './utils';\n\n/**\n * State object used to accumulate information from a stream of OpenAI events/chunks.\n */\ninterface StreamingState {\n /** Types of events encountered in the stream. */\n eventTypes: string[];\n /** Collected response text fragments (for output recording). */\n responseTexts: string[];\n /** Reasons for finishing the response, as reported by the API. */\n finishReasons: string[];\n /** The response ID. */\n responseId: string;\n /** The model name. */\n responseModel: string;\n /** Number of prompt/input tokens used. */\n promptTokens: number | undefined;\n /** Number of completion/output tokens used. */\n completionTokens: number | undefined;\n /** Total number of tokens used (prompt + completion). */\n totalTokens: number | undefined;\n cacheReadInputTokens: number | undefined;\n cacheCreationInputTokens: number | undefined;\n /**\n * Accumulated tool calls from Chat Completion streaming, keyed by string in the order they were opened.\n * @see https://platform.openai.com/docs/guides/function-calling?api-mode=chat#streaming\n */\n chatCompletionToolCalls: Map<string, ChatCompletionToolCall>;\n /** Key of the latest tool call, which unindexed argument fragments continue. */\n lastChatCompletionToolCallKey?: string;\n /** Key of the call currently open for a reported `index`, when a new `id` reused that index. */\n chatCompletionToolCallKeyByIndex?: Map<number, string>;\n /**\n * Accumulated function calls from Responses API streaming.\n * @see https://platform.openai.com/docs/guides/function-calling?api-mode=responses#streaming\n */\n responsesApiToolCalls: Array<ResponseFunctionCall | unknown>;\n}\n\n/**\n * Processes tool calls from a chat completion chunk delta.\n * Follows the pattern: accumulate by index, then convert to array at the end.\n *\n * @param toolCalls - Array of tool calls from the delta.\n * @param state - The current streaming state to update.\n *\n * @see https://platform.openai.com/docs/guides/function-calling#streaming\n */\nfunction processChatCompletionToolCalls(toolCalls: ChatCompletionToolCall[], state: StreamingState): void {\n for (const toolCall of toolCalls) {\n if (!toolCall.function) continue;\n const index = getToolCallKey(toolCall, toolCall.function.name, {\n calls: state.chatCompletionToolCalls,\n keyByIndex: (state.chatCompletionToolCallKeyByIndex ??= new Map()),\n lastKey: state.lastChatCompletionToolCallKey,\n });\n\n // Initialize tool call if this is the first chunk for this index\n const existingToolCall = state.chatCompletionToolCalls.get(index);\n if (!existingToolCall) {\n state.chatCompletionToolCalls.set(index, {\n ...toolCall,\n function: {\n name: toolCall.function.name,\n arguments: toolCall.function.arguments || '',\n },\n });\n } else {\n // Accumulate function arguments from subsequent chunks\n if (toolCall.function.arguments && existingToolCall.function) {\n existingToolCall.function.arguments += toolCall.function.arguments;\n }\n }\n state.lastChatCompletionToolCallKey = index;\n }\n}\n\n/**\n * Processes a single OpenAI ChatCompletionChunk event, updating the streaming state.\n *\n * @param chunk - The ChatCompletionChunk event to process.\n * @param state - The current streaming state to update.\n * @param recordOutputs - Whether to record output text fragments.\n */\nfunction processChatCompletionChunk(chunk: ChatCompletionChunk, state: StreamingState, recordOutputs: boolean): void {\n state.responseId = chunk.id ?? state.responseId;\n state.responseModel = chunk.model ?? state.responseModel;\n\n if (chunk.usage) {\n // For stream responses, the input tokens remain constant across all events in the stream.\n // Output tokens, however, are only finalized in the last event.\n // Since we can't guarantee that the last event will include usage data or even be a typed event,\n // we update the output token values on every event that includes them.\n // This ensures that output token usage is always set, even if the final event lacks it.\n state.promptTokens = chunk.usage.prompt_tokens;\n state.completionTokens = chunk.usage.completion_tokens;\n state.totalTokens = chunk.usage.total_tokens;\n state.cacheReadInputTokens = chunk.usage.prompt_tokens_details?.cached_tokens ?? state.cacheReadInputTokens;\n state.cacheCreationInputTokens =\n chunk.usage.prompt_tokens_details?.cache_write_tokens ?? state.cacheCreationInputTokens;\n }\n\n for (const choice of chunk.choices ?? []) {\n if (recordOutputs) {\n if (choice.delta?.content) {\n state.responseTexts.push(choice.delta.content);\n }\n\n // Handle tool calls from delta\n if (choice.delta?.tool_calls) {\n processChatCompletionToolCalls(choice.delta.tool_calls, state);\n }\n }\n if (choice.finish_reason) {\n state.finishReasons.push(choice.finish_reason);\n }\n }\n}\n\n/**\n * Processes a single OpenAI Responses API streaming event, updating the streaming state and span.\n *\n * @param streamEvent - The event to process (may be an error or unknown object).\n * @param state - The current streaming state to update.\n * @param recordOutputs - Whether to record output text fragments.\n * @param span - The span to update with error status if needed.\n */\nfunction processResponsesApiEvent(\n streamEvent: ResponseStreamingEvent | unknown | Error,\n state: StreamingState,\n recordOutputs: boolean,\n span: Span,\n): void {\n if (!(streamEvent && typeof streamEvent === 'object')) {\n state.eventTypes.push('unknown:non-object');\n return;\n }\n if (streamEvent instanceof Error) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n captureException(streamEvent, {\n mechanism: {\n handled: false,\n type: 'auto.ai.openai.stream-response',\n },\n });\n return;\n }\n\n if (!('type' in streamEvent)) return;\n const event = streamEvent as ResponseStreamingEvent;\n\n if (!RESPONSE_EVENT_TYPES.includes(event.type)) {\n state.eventTypes.push(event.type);\n return;\n }\n\n // Handle output text delta\n if (recordOutputs) {\n // Handle tool call events for Responses API\n if (event.type === 'response.output_item.done' && 'item' in event) {\n state.responsesApiToolCalls.push(event.item);\n }\n\n if (event.type === 'response.output_text.delta' && 'delta' in event && event.delta) {\n state.responseTexts.push(event.delta);\n return;\n }\n }\n\n if ('response' in event) {\n const { response } = event as { response: OpenAIResponseObject };\n state.responseId = response.id ?? state.responseId;\n state.responseModel = response.model ?? state.responseModel;\n\n if (response.usage) {\n // For stream responses, the input tokens remain constant across all events in the stream.\n // Output tokens, however, are only finalized in the last event.\n // Since we can't guarantee that the last event will include usage data or even be a typed event,\n // we update the output token values on every event that includes them.\n // This ensures that output token usage is always set, even if the final event lacks it.\n state.promptTokens = response.usage.input_tokens;\n state.completionTokens = response.usage.output_tokens;\n state.totalTokens = response.usage.total_tokens;\n state.cacheReadInputTokens = response.usage.input_tokens_details?.cached_tokens ?? state.cacheReadInputTokens;\n state.cacheCreationInputTokens =\n response.usage.input_tokens_details?.cache_write_tokens ?? state.cacheCreationInputTokens;\n }\n\n if (response.status) {\n state.finishReasons.push(response.status);\n }\n\n if (recordOutputs && response.output_text) {\n state.responseTexts.push(response.output_text);\n }\n }\n}\n\n/**\n * Instruments a stream of OpenAI events, updating the provided span with relevant attributes and\n * optionally recording output text. This function yields each event from the input stream as it is processed.\n *\n * @template T - The type of events in the stream.\n * @param stream - The async iterable stream of events to instrument.\n * @param span - The span to add attributes to and to finish at the end of the stream.\n * @param recordOutputs - Whether to record output text fragments in the span.\n * @returns An async generator yielding each event from the input stream.\n */\nexport async function* instrumentStream<T>(\n stream: AsyncIterable<T>,\n span: Span,\n recordOutputs: boolean,\n): AsyncGenerator<T, void, unknown> {\n const state: StreamingState = {\n eventTypes: [],\n responseTexts: [],\n finishReasons: [],\n responseId: '',\n responseModel: '',\n promptTokens: undefined,\n completionTokens: undefined,\n totalTokens: undefined,\n cacheReadInputTokens: undefined,\n cacheCreationInputTokens: undefined,\n chatCompletionToolCalls: new Map(),\n responsesApiToolCalls: [],\n };\n\n try {\n for await (const event of stream) {\n if (isChatCompletionChunk(event)) {\n processChatCompletionChunk(event, state, recordOutputs);\n } else if (isResponsesApiStreamEvent(event)) {\n processResponsesApiEvent(event, state, recordOutputs, span);\n }\n yield event;\n }\n } catch (error) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n throw error;\n } finally {\n const allToolCalls = [...state.chatCompletionToolCalls.values(), ...state.responsesApiToolCalls];\n endStreamSpan(span, { ...state, toolCalls: allToolCalls }, recordOutputs);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AA6DA,SAAS,+BAA+B,WAAqC,OAA6B;CACxG,KAAK,MAAM,YAAY,WAAW;EAChC,IAAI,CAAC,SAAS,UAAU;EACxB,MAAM,QAAQ,eAAe,UAAU,SAAS,SAAS,MAAM;GAC7D,OAAO,MAAM;GACb,YAAa,MAAM,qCAAN,MAAM,mDAAqC,IAAI,IAAI;GAChE,SAAS,MAAM;EACjB,CAAC;EAGD,MAAM,mBAAmB,MAAM,wBAAwB,IAAI,KAAK;EAChE,IAAI,CAAC,kBACH,MAAM,wBAAwB,IAAI,OAAO;GACvC,GAAG;GACH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AU;GAAE,MAAM;GAAmB,SAAS;EAAiB,CAAC;EACrE,MAAM;CACR,UAAU;EACR,MAAM,eAAe,CAAC,GAAG,MAAM,wBAAwB,OAAO,GAAG,GAAG,MAAM,qBAAqB;EAC/F,cAAc,MAAM;GAAE,GAAG;GAAO,WAAW;EAAa,GAAG,aAAa;CAC1E;AACF"}
1
+ {"version":3,"file":"streaming.js","names":[],"sources":["../../../../src/ai/openai/streaming.ts"],"sourcesContent":["import { captureException, SPAN_STATUS_ERROR } from '@sentry/core';\nimport type { Span } from '@sentry/core';\nimport { getToolCallKey } from '../core/streaming-tool-calls';\nimport type { GenAiSpanResult } from '../core/span-hooks';\nimport { endStreamSpan } from '../core/utils';\nimport { recordTimeToFirstChunk } from '../core/time-to-first-chunk';\nimport { RESPONSE_EVENT_TYPES } from './constants';\nimport type {\n ChatCompletionChunk,\n ChatCompletionToolCall,\n OpenAIResponseObject,\n ResponseFunctionCall,\n ResponseStreamingEvent,\n} from './types';\nimport { isChatCompletionChunk, isResponsesApiStreamEvent } from './utils';\n\n/**\n * State object used to accumulate information from a stream of OpenAI events/chunks.\n */\ninterface StreamingState {\n /** Types of events encountered in the stream. */\n eventTypes: string[];\n /** Collected response text fragments (for output recording). */\n responseTexts: string[];\n /** Reasons for finishing the response, as reported by the API. */\n finishReasons: string[];\n /** The response ID. */\n responseId: string;\n /** The model name. */\n responseModel: string;\n /** Number of prompt/input tokens used. */\n promptTokens: number | undefined;\n /** Number of completion/output tokens used. */\n completionTokens: number | undefined;\n /** Total number of tokens used (prompt + completion). */\n totalTokens: number | undefined;\n cacheReadInputTokens: number | undefined;\n cacheCreationInputTokens: number | undefined;\n /**\n * Accumulated tool calls from Chat Completion streaming, keyed by string in the order they were opened.\n * @see https://platform.openai.com/docs/guides/function-calling?api-mode=chat#streaming\n */\n chatCompletionToolCalls: Map<string, ChatCompletionToolCall>;\n /** Key of the latest tool call, which unindexed argument fragments continue. */\n lastChatCompletionToolCallKey?: string;\n /** Key of the call currently open for a reported `index`, when a new `id` reused that index. */\n chatCompletionToolCallKeyByIndex?: Map<number, string>;\n /**\n * Accumulated function calls from Responses API streaming.\n * @see https://platform.openai.com/docs/guides/function-calling?api-mode=responses#streaming\n */\n responsesApiToolCalls: Array<ResponseFunctionCall | unknown>;\n}\n\n/**\n * Processes tool calls from a chat completion chunk delta.\n * Follows the pattern: accumulate by index, then convert to array at the end.\n *\n * @param toolCalls - Array of tool calls from the delta.\n * @param state - The current streaming state to update.\n *\n * @see https://platform.openai.com/docs/guides/function-calling#streaming\n */\nfunction processChatCompletionToolCalls(toolCalls: ChatCompletionToolCall[], state: StreamingState): void {\n for (const toolCall of toolCalls) {\n if (!toolCall.function) continue;\n const index = getToolCallKey(toolCall, toolCall.function.name, {\n calls: state.chatCompletionToolCalls,\n keyByIndex: (state.chatCompletionToolCallKeyByIndex ??= new Map()),\n lastKey: state.lastChatCompletionToolCallKey,\n });\n\n // Initialize tool call if this is the first chunk for this index\n const existingToolCall = state.chatCompletionToolCalls.get(index);\n if (!existingToolCall) {\n state.chatCompletionToolCalls.set(index, {\n ...toolCall,\n function: {\n name: toolCall.function.name,\n arguments: toolCall.function.arguments || '',\n },\n });\n } else {\n // Accumulate function arguments from subsequent chunks\n if (toolCall.function.arguments && existingToolCall.function) {\n existingToolCall.function.arguments += toolCall.function.arguments;\n }\n }\n state.lastChatCompletionToolCallKey = index;\n }\n}\n\n/**\n * Processes a single OpenAI ChatCompletionChunk event, updating the streaming state.\n *\n * @param chunk - The ChatCompletionChunk event to process.\n * @param state - The current streaming state to update.\n * @param recordOutputs - Whether to record output text fragments.\n */\nfunction processChatCompletionChunk(chunk: ChatCompletionChunk, state: StreamingState, recordOutputs: boolean): void {\n state.responseId = chunk.id ?? state.responseId;\n state.responseModel = chunk.model ?? state.responseModel;\n\n if (chunk.usage) {\n // For stream responses, the input tokens remain constant across all events in the stream.\n // Output tokens, however, are only finalized in the last event.\n // Since we can't guarantee that the last event will include usage data or even be a typed event,\n // we update the output token values on every event that includes them.\n // This ensures that output token usage is always set, even if the final event lacks it.\n state.promptTokens = chunk.usage.prompt_tokens;\n state.completionTokens = chunk.usage.completion_tokens;\n state.totalTokens = chunk.usage.total_tokens;\n state.cacheReadInputTokens = chunk.usage.prompt_tokens_details?.cached_tokens ?? state.cacheReadInputTokens;\n state.cacheCreationInputTokens =\n chunk.usage.prompt_tokens_details?.cache_write_tokens ?? state.cacheCreationInputTokens;\n }\n\n for (const choice of chunk.choices ?? []) {\n if (recordOutputs) {\n if (choice.delta?.content) {\n state.responseTexts.push(choice.delta.content);\n }\n\n // Handle tool calls from delta\n if (choice.delta?.tool_calls) {\n processChatCompletionToolCalls(choice.delta.tool_calls, state);\n }\n }\n if (choice.finish_reason) {\n state.finishReasons.push(choice.finish_reason);\n }\n }\n}\n\n/**\n * Processes a single OpenAI Responses API streaming event, updating the streaming state and span.\n *\n * @param streamEvent - The event to process (may be an error or unknown object).\n * @param state - The current streaming state to update.\n * @param recordOutputs - Whether to record output text fragments.\n * @param span - The span to update with error status if needed.\n */\nfunction processResponsesApiEvent(\n streamEvent: ResponseStreamingEvent | unknown | Error,\n state: StreamingState,\n recordOutputs: boolean,\n span: Span,\n): void {\n if (!(streamEvent && typeof streamEvent === 'object')) {\n state.eventTypes.push('unknown:non-object');\n return;\n }\n if (streamEvent instanceof Error) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n captureException(streamEvent, {\n mechanism: {\n handled: false,\n type: 'auto.ai.openai.stream-response',\n },\n });\n return;\n }\n\n if (!('type' in streamEvent)) return;\n const event = streamEvent as ResponseStreamingEvent;\n\n if (!RESPONSE_EVENT_TYPES.includes(event.type)) {\n state.eventTypes.push(event.type);\n return;\n }\n\n // Handle output text delta\n if (recordOutputs) {\n // Handle tool call events for Responses API\n if (event.type === 'response.output_item.done' && 'item' in event) {\n state.responsesApiToolCalls.push(event.item);\n }\n\n if (event.type === 'response.output_text.delta' && 'delta' in event && event.delta) {\n state.responseTexts.push(event.delta);\n return;\n }\n }\n\n if ('response' in event) {\n const { response } = event as { response: OpenAIResponseObject };\n state.responseId = response.id ?? state.responseId;\n state.responseModel = response.model ?? state.responseModel;\n\n if (response.usage) {\n // For stream responses, the input tokens remain constant across all events in the stream.\n // Output tokens, however, are only finalized in the last event.\n // Since we can't guarantee that the last event will include usage data or even be a typed event,\n // we update the output token values on every event that includes them.\n // This ensures that output token usage is always set, even if the final event lacks it.\n state.promptTokens = response.usage.input_tokens;\n state.completionTokens = response.usage.output_tokens;\n state.totalTokens = response.usage.total_tokens;\n state.cacheReadInputTokens = response.usage.input_tokens_details?.cached_tokens ?? state.cacheReadInputTokens;\n state.cacheCreationInputTokens =\n response.usage.input_tokens_details?.cache_write_tokens ?? state.cacheCreationInputTokens;\n }\n\n if (response.status) {\n state.finishReasons.push(response.status);\n }\n\n if (recordOutputs && response.output_text) {\n state.responseTexts.push(response.output_text);\n }\n }\n}\n\n/**\n * Instruments a stream of OpenAI events, updating the provided span with relevant attributes and\n * optionally recording output text. This function yields each event from the input stream as it is processed.\n *\n * @template T - The type of events in the stream.\n * @param stream - The async iterable stream of events to instrument.\n * @param span - The span to add attributes to and to finish at the end of the stream.\n * @param recordOutputs - Whether to record output text fragments in the span.\n * @param beforeSpanEnd - Runs right before the span ends, with the error when the stream failed.\n * @returns An async generator yielding each event from the input stream.\n */\nexport async function* instrumentStream<T>(\n stream: AsyncIterable<T>,\n span: Span,\n recordOutputs: boolean,\n beforeSpanEnd?: (result: GenAiSpanResult<never>) => void,\n): AsyncGenerator<T, void, unknown> {\n const state: StreamingState = {\n eventTypes: [],\n responseTexts: [],\n finishReasons: [],\n responseId: '',\n responseModel: '',\n promptTokens: undefined,\n completionTokens: undefined,\n totalTokens: undefined,\n cacheReadInputTokens: undefined,\n cacheCreationInputTokens: undefined,\n chatCompletionToolCalls: new Map(),\n responsesApiToolCalls: [],\n };\n\n const result: GenAiSpanResult<never> = {};\n\n try {\n for await (const event of stream) {\n recordTimeToFirstChunk(span);\n if (isChatCompletionChunk(event)) {\n processChatCompletionChunk(event, state, recordOutputs);\n } else if (isResponsesApiStreamEvent(event)) {\n processResponsesApiEvent(event, state, recordOutputs, span);\n }\n yield event;\n }\n } catch (error) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n result.error = error;\n throw error;\n } finally {\n const allToolCalls = [...state.chatCompletionToolCalls.values(), ...state.responsesApiToolCalls];\n endStreamSpan(span, { ...state, toolCalls: allToolCalls }, recordOutputs, () => beforeSpanEnd?.(result));\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA+DA,SAAS,+BAA+B,WAAqC,OAA6B;CACxG,KAAK,MAAM,YAAY,WAAW;EAChC,IAAI,CAAC,SAAS,UAAU;EACxB,MAAM,QAAQ,eAAe,UAAU,SAAS,SAAS,MAAM;GAC7D,OAAO,MAAM;GACb,YAAa,MAAM,qCAAN,MAAM,mDAAqC,IAAI,IAAI;GAChE,SAAS,MAAM;EACjB,CAAC;EAGD,MAAM,mBAAmB,MAAM,wBAAwB,IAAI,KAAK;EAChE,IAAI,CAAC,kBACH,MAAM,wBAAwB,IAAI,OAAO;GACvC,GAAG;GACH,UAAU;IACR,MAAM,SAAS,SAAS;IACxB,WAAW,SAAS,SAAS,aAAa;GAC5C;EACF,CAAC;OAGD,IAAI,SAAS,SAAS,aAAa,iBAAiB,UAClD,iBAAiB,SAAS,aAAa,SAAS,SAAS;EAG7D,MAAM,gCAAgC;CACxC;AACF;;;;;;;;AASA,SAAS,2BAA2B,OAA4B,OAAuB,eAA8B;CACnH,MAAM,aAAa,MAAM,MAAM,MAAM;CACrC,MAAM,gBAAgB,MAAM,SAAS,MAAM;CAE3C,IAAI,MAAM,OAAO;EAMf,MAAM,eAAe,MAAM,MAAM;EACjC,MAAM,mBAAmB,MAAM,MAAM;EACrC,MAAM,cAAc,MAAM,MAAM;EAChC,MAAM,uBAAuB,MAAM,MAAM,uBAAuB,iBAAiB,MAAM;EACvF,MAAM,2BACJ,MAAM,MAAM,uBAAuB,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MAAM;GACzF,MAAM,2BACJ,SAAS,MAAM,sBAAsB,sBAAsB,MAAM;EACrE;EAEA,IAAI,SAAS,QACX,MAAM,cAAc,KAAK,SAAS,MAAM;EAG1C,IAAI,iBAAiB,SAAS,aAC5B,MAAM,cAAc,KAAK,SAAS,WAAW;CAEjD;AACF;;;;;;;;;;;;AAaA,gBAAuB,iBACrB,QACA,MACA,eACA,eACkC;CAClC,MAAM,QAAwB;EAC5B,YAAY,CAAC;EACb,eAAe,CAAC;EAChB,eAAe,CAAC;EAChB,YAAY;EACZ,eAAe;EACf,cAAc,KAAA;EACd,kBAAkB,KAAA;EAClB,aAAa,KAAA;EACb,sBAAsB,KAAA;EACtB,0BAA0B,KAAA;EAC1B,yCAAyB,IAAI,IAAI;EACjC,uBAAuB,CAAC;CAC1B;CAEA,MAAM,SAAiC,CAAC;CAExC,IAAI;EACF,WAAW,MAAM,SAAS,QAAQ;GAChC,uBAAuB,IAAI;GAC3B,IAAI,sBAAsB,KAAK,GAC7B,2BAA2B,OAAO,OAAO,aAAa;QACjD,IAAI,0BAA0B,KAAK,GACxC,yBAAyB,OAAO,OAAO,eAAe,IAAI;GAE5D,MAAM;EACR;CACF,SAAS,OAAO;EACd,KAAK,UAAU;GAAE,MAAM;GAAmB,SAAS;EAAiB,CAAC;EACrE,OAAO,QAAQ;EACf,MAAM;CACR,UAAU;EACR,MAAM,eAAe,CAAC,GAAG,MAAM,wBAAwB,OAAO,GAAG,GAAG,MAAM,qBAAqB;EAC/F,cAAc,MAAM;GAAE,GAAG;GAAO,WAAW;EAAa,GAAG,qBAAqB,gBAAgB,MAAM,CAAC;CACzG;AACF"}
@@ -1,3 +1,4 @@
1
+ import { recordTimeToFirstChunk } from "../core/time-to-first-chunk.js";
1
2
  import { PI_AI_ORIGIN } from "./constants.js";
2
3
  import { piAiAssistantMessageToGenAiMessage, piAiFinishReason, piAiMessagesToGenAiMessages, piAiSystemInstructions, piAiToolDefinitions } from "./messages.js";
3
4
  import { setPiAiUsageAttributes } from "./usage.js";
@@ -69,6 +70,22 @@ function getRequestContentAttributes(context) {
69
70
  [GEN_AI_TOOL_DEFINITIONS]: tools.length ? stringify(tools) : void 0
70
71
  };
71
72
  }
72
- export { getPiAiChatSpanOptions, setPiAiResponseAttributes };
73
+ /**
74
+ * Records `gen_ai.response.time_to_first_chunk` for a streamed request. The stream has one consumer,
75
+ * so instead of reading it, this wraps `push`, which the provider calls for each event as it decodes
76
+ * it. The wrapper is removed after the first chunk.
77
+ */
78
+ function observePiAiFirstChunk(span, events) {
79
+ const push = events?.push;
80
+ if (!events || typeof push !== "function") return;
81
+ events.push = function(event) {
82
+ if (event?.type !== "start") {
83
+ recordTimeToFirstChunk(span);
84
+ events.push = push;
85
+ }
86
+ return push.call(this, event);
87
+ };
88
+ }
89
+ export { getPiAiChatSpanOptions, observePiAiFirstChunk, setPiAiResponseAttributes };
73
90
 
74
91
  //# sourceMappingURL=chat.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"chat.js","names":[],"sources":["../../../../src/ai/pi-ai/chat.ts"],"sourcesContent":["import type { Span, StartSpanOptions } from '@sentry/core';\nimport {\n getCurrentScope,\n getIsolationScope,\n isURLObjectRelative,\n parseStringToURLObject,\n SPAN_STATUS_ERROR,\n stringify,\n} from '@sentry/core';\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_OUTPUT_MESSAGES,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_MAX_TOKENS,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_REQUEST_REASONING_LEVEL,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_STREAMING,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_TOOL_DEFINITIONS,\n SENTRY_ORIGIN,\n SERVER_ADDRESS,\n SERVER_PORT,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_CHAT } from '@sentry/conventions/op';\nimport { PI_AI_ORIGIN } from './constants';\nimport type { PiAiContext } from './messages';\nimport {\n piAiAssistantMessageToGenAiMessage,\n piAiFinishReason,\n piAiMessagesToGenAiMessages,\n piAiSystemInstructions,\n piAiToolDefinitions,\n} from './messages';\nimport type { PiAssistantMessage, PiModel, PiStreamOptions } from './types';\nimport { setPiAiUsageAttributes } from './usage';\n\ninterface PiAiChatRequest {\n model: PiModel;\n /** Absent for the deferred calls, which pass a handle in place of the request context. */\n context?: PiAiContext;\n callOptions?: PiStreamOptions;\n streaming: boolean;\n recordInputs: boolean;\n}\n\n/** The span options of the `gen_ai.chat` span of a pi-ai request. */\nexport function getPiAiChatSpanOptions(request: PiAiChatRequest): StartSpanOptions {\n const { model, context, callOptions, streaming, recordInputs } = request;\n const conversationId =\n getCurrentScope().getScopeData().conversationId ?? getIsolationScope().getScopeData().conversationId;\n\n return {\n name: model.id ? `chat ${model.id}` : 'chat',\n op: GEN_AI_CHAT,\n attributes: {\n [SENTRY_ORIGIN]: PI_AI_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'chat',\n [GEN_AI_PROVIDER_NAME]: model.provider,\n [GEN_AI_REQUEST_MODEL]: model.id,\n [GEN_AI_CONVERSATION_ID]: conversationId,\n [GEN_AI_RESPONSE_STREAMING]: streaming || undefined,\n [GEN_AI_REQUEST_TEMPERATURE]: callOptions?.temperature,\n [GEN_AI_REQUEST_MAX_TOKENS]: callOptions?.maxTokens,\n [GEN_AI_REQUEST_REASONING_LEVEL]: callOptions?.reasoning,\n ...getServerAttributes(model),\n ...(recordInputs && context ? getRequestContentAttributes(context) : {}),\n },\n };\n}\n\n/**\n * Record the settled message of a pi-ai request on its span. pi-ai never rejects a request: a\n * provider failure or an abort settles as a message with `stopReason` `error` or `aborted`.\n */\nexport function setPiAiResponseAttributes(span: Span, message: PiAssistantMessage, recordOutputs: boolean): void {\n const { responseModel, model, responseId, stopReason, usage } = message;\n\n const finishReason = piAiFinishReason(stopReason);\n const output = recordOutputs ? piAiAssistantMessageToGenAiMessage(message, finishReason) : undefined;\n\n span.setAttributes({\n [GEN_AI_RESPONSE_MODEL]: responseModel ?? model,\n [GEN_AI_RESPONSE_ID]: responseId,\n [GEN_AI_RESPONSE_FINISH_REASONS]: finishReason ? stringify([finishReason]) : undefined,\n [GEN_AI_OUTPUT_MESSAGES]: output ? stringify([output], String) : undefined,\n });\n\n const failed = stopReason === 'error';\n setPiAiUsageAttributes(span, usage, failed || stopReason === 'deferred');\n\n if (failed) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n } else if (stopReason === 'aborted') {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n }\n}\n\nfunction getServerAttributes(model: PiModel): Record<string, string | number | undefined> {\n const url = model.baseUrl ? parseStringToURLObject(model.baseUrl) : undefined;\n if (!url || isURLObjectRelative(url) || !url.hostname) {\n return {};\n }\n return { [SERVER_ADDRESS]: url.hostname, [SERVER_PORT]: url.port ? Number(url.port) : undefined };\n}\n\nfunction getRequestContentAttributes(context: PiAiContext): Record<string, string | undefined> {\n const messages = piAiMessagesToGenAiMessages(context.messages);\n const tools = piAiToolDefinitions(context);\n return {\n [GEN_AI_SYSTEM_INSTRUCTIONS]: piAiSystemInstructions(context),\n [GEN_AI_INPUT_MESSAGES]: messages.length ? stringify(messages) : undefined,\n [GEN_AI_TOOL_DEFINITIONS]: tools.length ? stringify(tools) : undefined,\n };\n}\n"],"mappings":";;;;;;;;AAoDA,SAAgB,uBAAuB,SAA4C;CACjF,MAAM,EAAE,OAAO,SAAS,aAAa,WAAW,iBAAiB;CACjE,MAAM,iBACJ,gBAAgB,CAAC,CAAC,aAAa,CAAC,CAAC,kBAAkB,kBAAkB,CAAC,CAAC,aAAa,CAAC,CAAC;CAExF,OAAO;EACL,MAAM,MAAM,KAAK,QAAQ,MAAM,OAAO;EACtC,IAAI;E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,oBAAoB,OAAO;CACzC,OAAO;GACJ,6BAA6B,uBAAuB,OAAO;GAC3D,wBAAwB,SAAS,SAAS,UAAU,QAAQ,IAAI,KAAA;GAChE,0BAA0B,MAAM,SAAS,UAAU,KAAK,IAAI,KAAA;CAC/D;AACF"}
1
+ {"version":3,"file":"chat.js","names":[],"sources":["../../../../src/ai/pi-ai/chat.ts"],"sourcesContent":["import type { Span, StartSpanOptions } from '@sentry/core';\nimport {\n getCurrentScope,\n getIsolationScope,\n isURLObjectRelative,\n parseStringToURLObject,\n SPAN_STATUS_ERROR,\n stringify,\n} from '@sentry/core';\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_OUTPUT_MESSAGES,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_MAX_TOKENS,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_REQUEST_REASONING_LEVEL,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_STREAMING,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_TOOL_DEFINITIONS,\n SENTRY_ORIGIN,\n SERVER_ADDRESS,\n SERVER_PORT,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_CHAT } from '@sentry/conventions/op';\nimport { recordTimeToFirstChunk } from '../core/time-to-first-chunk';\nimport { PI_AI_ORIGIN } from './constants';\nimport type { PiAiContext } from './messages';\nimport {\n piAiAssistantMessageToGenAiMessage,\n piAiFinishReason,\n piAiMessagesToGenAiMessages,\n piAiSystemInstructions,\n piAiToolDefinitions,\n} from './messages';\nimport type { PiAssistantMessage, PiEventStream, PiModel, PiStreamOptions } from './types';\nimport { setPiAiUsageAttributes } from './usage';\n\ninterface PiAiChatRequest {\n model: PiModel;\n /** Absent for the deferred calls, which pass a handle in place of the request context. */\n context?: PiAiContext;\n callOptions?: PiStreamOptions;\n streaming: boolean;\n recordInputs: boolean;\n}\n\n/** The span options of the `gen_ai.chat` span of a pi-ai request. */\nexport function getPiAiChatSpanOptions(request: PiAiChatRequest): StartSpanOptions {\n const { model, context, callOptions, streaming, recordInputs } = request;\n const conversationId =\n getCurrentScope().getScopeData().conversationId ?? getIsolationScope().getScopeData().conversationId;\n\n return {\n name: model.id ? `chat ${model.id}` : 'chat',\n op: GEN_AI_CHAT,\n attributes: {\n [SENTRY_ORIGIN]: PI_AI_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'chat',\n [GEN_AI_PROVIDER_NAME]: model.provider,\n [GEN_AI_REQUEST_MODEL]: model.id,\n [GEN_AI_CONVERSATION_ID]: conversationId,\n [GEN_AI_RESPONSE_STREAMING]: streaming || undefined,\n [GEN_AI_REQUEST_TEMPERATURE]: callOptions?.temperature,\n [GEN_AI_REQUEST_MAX_TOKENS]: callOptions?.maxTokens,\n [GEN_AI_REQUEST_REASONING_LEVEL]: callOptions?.reasoning,\n ...getServerAttributes(model),\n ...(recordInputs && context ? getRequestContentAttributes(context) : {}),\n },\n };\n}\n\n/**\n * Record the settled message of a pi-ai request on its span. pi-ai never rejects a request: a\n * provider failure or an abort settles as a message with `stopReason` `error` or `aborted`.\n */\nexport function setPiAiResponseAttributes(span: Span, message: PiAssistantMessage, recordOutputs: boolean): void {\n const { responseModel, model, responseId, stopReason, usage } = message;\n\n const finishReason = piAiFinishReason(stopReason);\n const output = recordOutputs ? piAiAssistantMessageToGenAiMessage(message, finishReason) : undefined;\n\n span.setAttributes({\n [GEN_AI_RESPONSE_MODEL]: responseModel ?? model,\n [GEN_AI_RESPONSE_ID]: responseId,\n [GEN_AI_RESPONSE_FINISH_REASONS]: finishReason ? stringify([finishReason]) : undefined,\n [GEN_AI_OUTPUT_MESSAGES]: output ? stringify([output], String) : undefined,\n });\n\n const failed = stopReason === 'error';\n setPiAiUsageAttributes(span, usage, failed || stopReason === 'deferred');\n\n if (failed) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n } else if (stopReason === 'aborted') {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n }\n}\n\nfunction getServerAttributes(model: PiModel): Record<string, string | number | undefined> {\n const url = model.baseUrl ? parseStringToURLObject(model.baseUrl) : undefined;\n if (!url || isURLObjectRelative(url) || !url.hostname) {\n return {};\n }\n return { [SERVER_ADDRESS]: url.hostname, [SERVER_PORT]: url.port ? Number(url.port) : undefined };\n}\n\nfunction getRequestContentAttributes(context: PiAiContext): Record<string, string | undefined> {\n const messages = piAiMessagesToGenAiMessages(context.messages);\n const tools = piAiToolDefinitions(context);\n return {\n [GEN_AI_SYSTEM_INSTRUCTIONS]: piAiSystemInstructions(context),\n [GEN_AI_INPUT_MESSAGES]: messages.length ? stringify(messages) : undefined,\n [GEN_AI_TOOL_DEFINITIONS]: tools.length ? stringify(tools) : undefined,\n };\n}\n\n/**\n * Records `gen_ai.response.time_to_first_chunk` for a streamed request. The stream has one consumer,\n * so instead of reading it, this wraps `push`, which the provider calls for each event as it decodes\n * it. The wrapper is removed after the first chunk.\n */\nexport function observePiAiFirstChunk(span: Span, events: Partial<PiEventStream> | undefined): void {\n const push = events?.push;\n if (!events || typeof push !== 'function') {\n return;\n }\n events.push = function (this: unknown, event: unknown) {\n // Providers push `start` before the response arrives.\n if ((event as { type?: unknown } | undefined)?.type !== 'start') {\n recordTimeToFirstChunk(span);\n events.push = push;\n }\n return push.call(this, event);\n };\n}\n"],"mappings":";;;;;;;;;AAqDA,SAAgB,uBAAuB,SAA4C;CACjF,MAAM,EAAE,OAAO,SAAS,aAAa,WAAW,iBAAiB;CACjE,MAAM,iBACJ,gBAAgB,CAAC,CAAC,aAAa,CAAC,CAAC,kBAAkB,kBAAkB,CAAC,CAAC,aAAa,CAAC,CAAC;CAExF,OAAO;EACL,MAAM,MAAM,KAAK,QAAQ,MAAM,OAAO;EACtC,IAAI;EACJ,YAAY;IACT,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CACzC,OAAO;GACJ,6BAA6B,uBAAuB,OAAO;GAC3D,wBAAwB,SAAS,SAAS,UAAU,QAAQ,IAAI,KAAA;GAChE,0BAA0B,MAAM,SAAS,UAAU,KAAK,IAAI,KAAA;CAC/D;AACF;;;;;;AAOA,SAAgB,sBAAsB,MAAY,QAAkD;CAClG,MAAM,OAAO,QAAQ;CACrB,IAAI,CAAC,UAAU,OAAO,SAAS,YAC7B;CAEF,OAAO,OAAO,SAAyB,OAAgB;EAErD,IAAK,OAA0C,SAAS,SAAS;GAC/D,uBAAuB,IAAI;GAC3B,OAAO,OAAO;EAChB;EACA,OAAO,KAAK,KAAK,MAAM,KAAK;CAC9B;AACF"}
@@ -1,28 +1,47 @@
1
- import { resolveAIRecordingOptions } from "../core/utils.js";
1
+ import { runGenAiSpanEnd, runGenAiSpanStart } from "../core/span-hooks.js";
2
+ import { resolveGenAiCallRecording, resolveRecordingOption } from "../core/utils.js";
2
3
  import { getCurrentScope } from "@sentry/core";
3
4
  // src/ai/pi-ai/recording.ts
4
- const RECORDING_OPTIONS_KEY = "piAiRecordingOptions";
5
+ const DRIVER_KEY = "piAiDriver";
5
6
  /**
6
- * Apply the recording options of an integration that sends its model calls through pi-ai, such as
7
- * Flue, to the `gen_ai.chat` spans of the requests sent under `scope`.
7
+ * Apply the recording options and span hooks of an integration that sends its model calls through
8
+ * pi-ai, such as Flue, to the `gen_ai.chat` spans of the requests sent under `scope`. Options and
9
+ * hooks that are functions get `call`.
8
10
  */
9
- function setPiAiRecordingOptions(scope, options) {
10
- scope.setSDKProcessingMetadata({ [RECORDING_OPTIONS_KEY]: options });
11
+ function setPiAiDriverOptions(scope, options, call) {
12
+ const driver = {
13
+ recording: () => ({
14
+ recordInputs: resolveRecordingOption(options.recordInputs, call),
15
+ recordOutputs: resolveRecordingOption(options.recordOutputs, call)
16
+ }),
17
+ onSpanStart: (span) => runGenAiSpanStart(options, span, call),
18
+ onSpanEnd: (span, result) => runGenAiSpanEnd(options, span, call, result)
19
+ };
20
+ scope.setSDKProcessingMetadata({ [DRIVER_KEY]: driver });
21
+ }
22
+ /** The integration driving the pi-ai requests sent from the current scope, if any. */
23
+ function getPiAiDriver() {
24
+ return getCurrentScope().getScopeData().sdkProcessingMetadata[DRIVER_KEY];
11
25
  }
12
26
  /**
13
27
  * The recording options of a pi-ai request, read when it starts: its response can settle outside the
14
- * scope it was sent from. An explicit `false` on either integration keeps the content out, since an
15
- * opt-out must not depend on which integration it was set on. Otherwise the integration driving
16
- * pi-ai comes first, then `piAiIntegration`, then `dataCollection.genAI`.
28
+ * scope it was sent from. An explicit `false` on either integration, or from either one's function,
29
+ * keeps the content out, since an opt-out must not depend on which integration it was set on.
30
+ * Otherwise the integration driving pi-ai comes first, then `piAiIntegration`, then
31
+ * `dataCollection.genAI`.
17
32
  */
18
- function resolvePiAiRecordingOptions(options) {
19
- const driver = getCurrentScope().getScopeData().sdkProcessingMetadata[RECORDING_OPTIONS_KEY];
20
- const { recordInputs, recordOutputs } = resolveAIRecordingOptions(options);
33
+ function resolvePiAiRecordingOptions(options, call, driver = getPiAiDriver()) {
34
+ const driverRecording = driver?.recording();
35
+ const own = {
36
+ recordInputs: resolveRecordingOption(options.recordInputs, call),
37
+ recordOutputs: resolveRecordingOption(options.recordOutputs, call)
38
+ };
39
+ const { recordInputs, recordOutputs } = resolveGenAiCallRecording(own, call);
21
40
  return {
22
- recordInputs: options.recordInputs !== false && (driver?.recordInputs ?? recordInputs),
23
- recordOutputs: options.recordOutputs !== false && (driver?.recordOutputs ?? recordOutputs)
41
+ recordInputs: own.recordInputs !== false && (driverRecording?.recordInputs ?? recordInputs),
42
+ recordOutputs: own.recordOutputs !== false && (driverRecording?.recordOutputs ?? recordOutputs)
24
43
  };
25
44
  }
26
- export { resolvePiAiRecordingOptions, setPiAiRecordingOptions };
45
+ export { getPiAiDriver, resolvePiAiRecordingOptions, setPiAiDriverOptions };
27
46
 
28
47
  //# sourceMappingURL=recording.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"recording.js","names":[],"sources":["../../../../src/ai/pi-ai/recording.ts"],"sourcesContent":["import type { Scope } from '@sentry/core';\nimport { getCurrentScope } from '@sentry/core';\nimport type { GenAiOptions } from '../core/utils';\nimport { resolveAIRecordingOptions } from '../core/utils';\n\nconst RECORDING_OPTIONS_KEY = 'piAiRecordingOptions';\n\n/**\n * Apply the recording options of an integration that sends its model calls through pi-ai, such as\n * Flue, to the `gen_ai.chat` spans of the requests sent under `scope`.\n */\nexport function setPiAiRecordingOptions(scope: Scope, options: GenAiOptions): void {\n scope.setSDKProcessingMetadata({ [RECORDING_OPTIONS_KEY]: options });\n}\n\n/**\n * The recording options of a pi-ai request, read when it starts: its response can settle outside the\n * scope it was sent from. An explicit `false` on either integration keeps the content out, since an\n * opt-out must not depend on which integration it was set on. Otherwise the integration driving\n * pi-ai comes first, then `piAiIntegration`, then `dataCollection.genAI`.\n */\nexport function resolvePiAiRecordingOptions(options: GenAiOptions): Required<GenAiOptions> {\n const driver = getCurrentScope().getScopeData().sdkProcessingMetadata[RECORDING_OPTIONS_KEY] as\n | GenAiOptions\n | undefined;\n const { recordInputs, recordOutputs } = resolveAIRecordingOptions(options);\n return {\n recordInputs: options.recordInputs !== false && (driver?.recordInputs ?? recordInputs),\n recordOutputs: options.recordOutputs !== false && (driver?.recordOutputs ?? recordOutputs),\n };\n}\n"],"mappings":";;;AAKA,MAAM,wBAAwB;;;;;AAM9B,SAAgB,wBAAwB,OAAc,SAA6B;CACjF,MAAM,yBAAyB,GAAG,wBAAwB,QAAQ,CAAC;AACrE;;;;;;;AAQA,SAAgB,4BAA4B,SAA+C;CACzF,MAAM,SAAS,gBAAgB,CAAC,CAAC,aAAa,CAAC,CAAC,sBAAsB;CAGtE,MAAM,EAAE,cAAc,kBAAkB,0BAA0B,OAAO;CACzE,OAAO;EACL,cAAc,QAAQ,iBAAiB,UAAU,QAAQ,gBAAgB;EACzE,eAAe,QAAQ,kBAAkB,UAAU,QAAQ,iBAAiB;CAC9E;AACF"}
1
+ {"version":3,"file":"recording.js","names":[],"sources":["../../../../src/ai/pi-ai/recording.ts"],"sourcesContent":["import type { Scope, Span } from '@sentry/core';\nimport { getCurrentScope } from '@sentry/core';\nimport type { GenAiSpanHooks, GenAiSpanResult } from '../core/span-hooks';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { GenAiCallOptions, GenAiOptions } from '../core/utils';\nimport { resolveGenAiCallRecording, resolveRecordingOption } from '../core/utils';\nimport type { PiAiCallInfo, PiAssistantMessage } from './types';\n\nconst DRIVER_KEY = 'piAiDriver';\n\n/** The options of the integration driving pi-ai, bound to its call info. */\nexport interface PiAiDriver {\n recording: () => GenAiOptions;\n onSpanStart: (span: Span) => void;\n onSpanEnd: (span: Span, result: GenAiSpanResult<PiAssistantMessage>) => void;\n}\n\n/**\n * Apply the recording options and span hooks of an integration that sends its model calls through\n * pi-ai, such as Flue, to the `gen_ai.chat` spans of the requests sent under `scope`. Options and\n * hooks that are functions get `call`.\n */\nexport function setPiAiDriverOptions<TCall>(\n scope: Scope,\n options: GenAiCallOptions<TCall> & GenAiSpanHooks<TCall, PiAssistantMessage>,\n call: TCall,\n): void {\n const driver: PiAiDriver = {\n recording: () => ({\n recordInputs: resolveRecordingOption(options.recordInputs, call),\n recordOutputs: resolveRecordingOption(options.recordOutputs, call),\n }),\n onSpanStart: span => runGenAiSpanStart(options, span, call),\n onSpanEnd: (span, result) => runGenAiSpanEnd(options, span, call, result),\n };\n scope.setSDKProcessingMetadata({ [DRIVER_KEY]: driver });\n}\n\n/** The integration driving the pi-ai requests sent from the current scope, if any. */\nexport function getPiAiDriver(): PiAiDriver | undefined {\n return getCurrentScope().getScopeData().sdkProcessingMetadata[DRIVER_KEY] as PiAiDriver | undefined;\n}\n\n/**\n * The recording options of a pi-ai request, read when it starts: its response can settle outside the\n * scope it was sent from. An explicit `false` on either integration, or from either one's function,\n * keeps the content out, since an opt-out must not depend on which integration it was set on.\n * Otherwise the integration driving pi-ai comes first, then `piAiIntegration`, then\n * `dataCollection.genAI`.\n */\nexport function resolvePiAiRecordingOptions(\n options: GenAiCallOptions<PiAiCallInfo>,\n call: PiAiCallInfo,\n driver = getPiAiDriver(),\n): Required<GenAiOptions> {\n const driverRecording = driver?.recording();\n const own = {\n recordInputs: resolveRecordingOption(options.recordInputs, call),\n recordOutputs: resolveRecordingOption(options.recordOutputs, call),\n };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(own, call);\n return {\n recordInputs: own.recordInputs !== false && (driverRecording?.recordInputs ?? recordInputs),\n recordOutputs: own.recordOutputs !== false && (driverRecording?.recordOutputs ?? recordOutputs),\n };\n}\n"],"mappings":";;;;AAQA,MAAM,aAAa;;;;;;AAcnB,SAAgB,qBACd,OACA,SACA,MACM;CACN,MAAM,SAAqB;EACzB,kBAAkB;GAChB,cAAc,uBAAuB,QAAQ,cAAc,IAAI;GAC/D,eAAe,uBAAuB,QAAQ,eAAe,IAAI;EACnE;EACA,cAAa,SAAQ,kBAAkB,SAAS,MAAM,IAAI;EAC1D,YAAY,MAAM,WAAW,gBAAgB,SAAS,MAAM,MAAM,MAAM;CAC1E;CACA,MAAM,yBAAyB,GAAG,aAAa,OAAO,CAAC;AACzD;;AAGA,SAAgB,gBAAwC;CACtD,OAAO,gBAAgB,CAAC,CAAC,aAAa,CAAC,CAAC,sBAAsB;AAChE;;;;;;;;AASA,SAAgB,4BACd,SACA,MACA,SAAS,cAAc,GACC;CACxB,MAAM,kBAAkB,QAAQ,UAAU;CAC1C,MAAM,MAAM;EACV,cAAc,uBAAuB,QAAQ,cAAc,IAAI;EAC/D,eAAe,uBAAuB,QAAQ,eAAe,IAAI;CACnE;CACA,MAAM,EAAE,cAAc,kBAAkB,0BAA0B,KAAK,IAAI;CAC3E,OAAO;EACL,cAAc,IAAI,iBAAiB,UAAU,iBAAiB,gBAAgB;EAC9E,eAAe,IAAI,kBAAkB,UAAU,iBAAiB,iBAAiB;CACnF;AACF"}
@@ -1,4 +1,4 @@
1
- import { setPiAiRecordingOptions } from "../pi-ai/recording.js";
1
+ import { setPiAiDriverOptions } from "../pi-ai/recording.js";
2
2
  import { PI_DURABLE_ORIGIN, PI_TASK } from "./constants.js";
3
3
  import { createRuns, endRun, observeRunControl, readProviderSessionId, startRun, toSentryConversationId } from "./runs.js";
4
4
  import { instrumentTool, instrumentToolPhase } from "./tools.js";
@@ -68,6 +68,7 @@ function endRunsOnClose(harnessOptions, harness) {
68
68
  code: SPAN_STATUS_ERROR,
69
69
  message: "cancelled"
70
70
  });
71
+ call.onSpanEnd?.();
71
72
  call.span.end(call.endTimestamp);
72
73
  }
73
74
  runs.toolCalls.clear();
@@ -145,7 +146,11 @@ function runPhase(kind, phase, runtime, context, runs, wrapTool, isAbort, option
145
146
  }
146
147
  }
147
148
  scope.setConversationId(sessionId ?? toSentryConversationId(runs, conversationId));
148
- setPiAiRecordingOptions(scope, options);
149
+ setPiAiDriverOptions(scope, options, {
150
+ operation: "chat",
151
+ runtime,
152
+ context
153
+ });
149
154
  try {
150
155
  return await phase(observed);
151
156
  } catch (error) {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../../src/ai/pi-durable/index.ts"],"sourcesContent":["import type { Scope } from '@sentry/core';\nimport {\n addNonEnumerableProperty,\n captureException,\n getCurrentScope,\n getDefaultIsolationScope,\n SPAN_STATUS_ERROR,\n startNewTrace,\n withActiveSpan,\n} from '@sentry/core';\nimport { GEN_AI_CONVERSATION_ID } from '@sentry/conventions/attributes';\nimport type { GenAiOptions } from '../core/utils';\nimport { setPiAiRecordingOptions } from '../pi-ai/recording';\nimport { PI_DURABLE_ORIGIN, PI_TASK } from './constants';\nimport type { PiRuns } from './runs';\nimport { createRuns, endRun, observeRunControl, readProviderSessionId, startRun, toSentryConversationId } from './runs';\nimport { instrumentTool, instrumentToolPhase } from './tools';\nimport type {\n PiHarness,\n PiHarnessOptions,\n PiPhaseHandler,\n PiRegistryReader,\n PiRegistrySnapshot,\n PiTask,\n PiTaskRuntime,\n PiTool,\n} from './types';\nimport { withCleanScopes } from '../../utils/withCleanScopes';\nimport { bound } from './utils';\n\nexport type PiDurableOptions = GenAiOptions;\n\nconst INSTRUMENTED = Symbol.for('sentry.pi-durable.instrumented');\nconst RUNS = Symbol.for('sentry.pi-durable.runs');\n\n/**\n * Return pi-durable `HarnessOptions` whose task phases and tool calls are traced. The caller's\n * `registry` object is wrapped, never modified. The result has the caller's options as prototype:\n * pi-durable reads `settings`, `env` and `conversationCreated` at every use, so they stay live,\n * getters included.\n *\n * Spans:\n * - `gen_ai.invoke_agent` for each run, a new trace per run, or a child of the tool call that\n * created the conversation for a subagent;\n * - `gen_ai.chat` for each model request, under its run, from `piAiIntegration`;\n * - `gen_ai.execute_tool` for each tool call, under its run.\n *\n * The scheduler starts task phases from whichever async context last woke it, often an unrelated\n * request. Every phase therefore runs in its run's own scopes and trace, never in the ones it\n * inherits.\n */\nexport function instrumentPiDurableHarnessOptions<T extends PiHarnessOptions>(\n harnessOptions: T,\n options: PiDurableOptions = {},\n): T {\n if (!harnessOptions || (harnessOptions as Record<symbol, unknown>)[INSTRUMENTED]) {\n return harnessOptions;\n }\n\n const runs = createRuns();\n const own = (value: unknown): PropertyDescriptor => ({ value, enumerable: true, configurable: true, writable: true });\n const instrumented: T = Object.create(harnessOptions, {\n ...(harnessOptions.registry ? { registry: own(instrumentRegistry(harnessOptions.registry, options, runs)) } : {}),\n // pi-durable passes failures of extension code here, such as a throwing hook, and keeps going.\n // Only an app that passed its own `onReport` gets a chance to handle them.\n onReport: own((error: unknown) => {\n captureException(error, { mechanism: { handled: !!harnessOptions.onReport, type: PI_DURABLE_ORIGIN } });\n harnessOptions.onReport?.(error);\n }),\n });\n addNonEnumerableProperty(instrumented, INSTRUMENTED, true);\n addNonEnumerableProperty(instrumented, RUNS, runs);\n return instrumented;\n}\n\n/**\n * End the open runs and tool calls of `harness` when it closes. Closing stops the scheduler without\n * settling the inputs in flight, so nothing else would end their spans, and the maps that track\n * them would keep the spans for the lifetime of the process. A run whose ending commit is still in\n * flight ends with that commit's status.\n */\nexport function endRunsOnClose(harnessOptions: PiHarnessOptions, harness: unknown): void {\n const runs = (harnessOptions as Record<symbol, unknown>)[RUNS] as PiRuns | undefined;\n const closable = harness as PiHarness | undefined;\n if (!runs || typeof closable?.subscribeClose !== 'function') {\n return;\n }\n closable.subscribeClose(() => {\n for (const run of runs.active.values()) {\n endRun(run, runs, run.pendingEnd ? run.pendingEnd.status : { code: SPAN_STATUS_ERROR, message: 'cancelled' });\n }\n for (const calls of runs.toolCalls.values()) {\n for (const call of calls) {\n if (call.endTimestamp === undefined) {\n call.span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n }\n call.span.end(call.endTimestamp);\n }\n }\n runs.toolCalls.clear();\n runs.owners.clear();\n });\n}\n\nfunction instrumentRegistry(registry: PiRegistryReader, options: PiDurableOptions, runs: PiRuns): PiRegistryReader {\n // Cached so identity stays stable: the scheduler hands a task over to a new definition whenever\n // `snapshot().task(kind)` returns a different object than the one it runs.\n const snapshots = new WeakMap<PiRegistrySnapshot, PiRegistrySnapshot>();\n const tasks = new WeakMap<PiTask, PiTask>();\n const tools = new WeakMap<PiTool, PiTool>();\n\n const wrapTool = (tool: PiTool): PiTool => {\n let wrapped = tools.get(tool);\n if (!wrapped) {\n wrapped = instrumentTool(tool, runs, options);\n tools.set(tool, wrapped);\n }\n return wrapped;\n };\n\n const wrapTask = (task: PiTask | undefined): PiTask | undefined => {\n if (!task?.definition?.phases) {\n return task;\n }\n let wrapped = tasks.get(task);\n if (!wrapped) {\n const { definition } = task;\n // pi-durable calls a phase on the `phases` object and `abort` on the definition; keep that\n // receiver, so handlers that use `this` work.\n const wrapPhase =\n (phase: PiPhaseHandler, receiver: unknown, isAbort = false): PiPhaseHandler =>\n (taskRecord, runtime, context) =>\n runPhase(\n definition.name,\n observed => phase.call(receiver, taskRecord, observed, context),\n runtime,\n context,\n runs,\n wrapTool,\n isAbort,\n options,\n );\n const phases: Record<string, PiPhaseHandler> = {};\n for (const [name, phase] of Object.entries(definition.phases)) {\n phases[name] = typeof phase === 'function' ? wrapPhase(phase, definition.phases) : phase;\n }\n wrapped = {\n ...task,\n definition: {\n ...definition,\n phases,\n ...(typeof definition.abort === 'function' ? { abort: wrapPhase(definition.abort, definition, true) } : {}),\n },\n };\n tasks.set(task, wrapped);\n }\n return wrapped;\n };\n\n const wrapSnapshot = (snapshot: PiRegistrySnapshot): PiRegistrySnapshot => {\n let wrapped = snapshots.get(snapshot);\n if (!wrapped) {\n wrapped = new Proxy(snapshot, {\n get(target, property) {\n if (property === 'task') {\n return (name: string) => wrapTask(target.task(name));\n }\n if (property === 'tasks') {\n return () => target.tasks().map(task => wrapTask(task));\n }\n return bound(target, property);\n },\n });\n snapshots.set(snapshot, wrapped);\n }\n return wrapped;\n };\n\n return new Proxy(registry, {\n get(target, property) {\n if (property === 'snapshot') {\n return () => wrapSnapshot(target.snapshot());\n }\n return bound(target, property);\n },\n });\n}\n\nfunction runPhase(\n kind: string,\n phase: (runtime: PiTaskRuntime) => Promise<unknown>,\n runtime: PiTaskRuntime,\n context: unknown,\n runs: PiRuns,\n wrapTool: (tool: PiTool) => PiTool,\n isAbort: boolean,\n options: PiDurableOptions,\n): Promise<unknown> {\n const { conversationId } = runtime;\n const isRunWork = kind === PI_TASK.GENERATION || kind === PI_TASK.TOOL;\n // A compaction joins the run it was started for. One started while idle has no run, and its\n // `chat` span becomes the root of a trace of its own. An abort handler ends the run of its task,\n // so it joins that run but never starts one. Tasks of extensions never join a run.\n const run =\n isRunWork || kind === PI_TASK.COMPACTION\n ? (runs.active.get(conversationId) ?? (isRunWork && !isAbort ? startRun(conversationId, runs) : undefined))\n : undefined;\n\n let observed = runtime;\n let finishToolPhase: (() => void) | undefined;\n if (run && kind === PI_TASK.GENERATION) {\n observed = observeRunControl(runtime, run, runs);\n } else if (kind === PI_TASK.TOOL) {\n const toolPhase = instrumentToolPhase(runtime, runs, wrapTool);\n observed = toolPhase.runtime;\n finishToolPhase = toolPhase.finish;\n }\n\n const runInScope = async (scope: Scope): Promise<unknown> => {\n // Read at the first phase of a run, which is a `pi.tool` phase when a restarted Harness reruns a\n // tool call, and at each phase outside a run, such as an idle compaction or a task of an extension.\n let sessionId = run?.sessionId;\n if (!sessionId) {\n sessionId = await readProviderSessionId(runtime, context);\n if (run && sessionId) {\n run.sessionId = sessionId;\n run.span.setAttribute(GEN_AI_CONVERSATION_ID, sessionId);\n }\n }\n scope.setConversationId(sessionId ?? toSentryConversationId(runs, conversationId));\n setPiAiRecordingOptions(scope, options);\n try {\n return await phase(observed);\n } catch (error) {\n // The scheduler faults a task whose phase throws, and a faulted generation ends its run. A\n // throw after an abort mark, or once the Harness closes, is not a fault.\n if (!runtime.signal?.aborted) {\n captureException(error, { mechanism: { handled: false, type: PI_DURABLE_ORIGIN } });\n if (run && kind === PI_TASK.GENERATION) {\n endRun(run, runs, { code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n }\n throw error;\n } finally {\n finishToolPhase?.();\n }\n };\n\n if (!run) {\n return withCleanScopes(getDefaultIsolationScope().clone(), () =>\n startNewTrace(() => runInScope(getCurrentScope())),\n );\n }\n return withCleanScopes(run.isolationScope, () => withActiveSpan(run.span, runInScope));\n}\n"],"mappings":";;;;;;;;;AAgCA,MAAM,eAAe,OAAO,IAAI,gCAAgC;AAChE,MAAM,OAAO,OAAO,IAAI,wBAAwB;;;;;;;;;;;;;;;;;AAkBhD,SAAgB,kCACd,gBACA,UAA4B,CAAC,GAC1B;CACH,IAAI,CAAC,kBAAmB,eAA2C,eACjE,OAAO;CAGT,MAAM,OAAO,WAAW;CACxB,MAAM,OAAO,WAAwC;EAAE;EAAO,YAAY;EAAM,cAAc;EAAM,UAAU;CAAK;CACnH,MAAM,eAAkB,OAAO,OAAO,gBAAgB;EACpD,GAAI,eAAe,WAAW,EAAE,UAAU,IAAI,mBAAmB,eAAe,UAAU,SAAS,IAAI,CAAC,EAAE,IAAI,CAAC;EAG/G,U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../src/ai/pi-durable/index.ts"],"sourcesContent":["import type { Scope } from '@sentry/core';\nimport {\n addNonEnumerableProperty,\n captureException,\n getCurrentScope,\n getDefaultIsolationScope,\n SPAN_STATUS_ERROR,\n startNewTrace,\n withActiveSpan,\n} from '@sentry/core';\nimport { GEN_AI_CONVERSATION_ID } from '@sentry/conventions/attributes';\nimport type { GenAiSpanHooks } from '../core/span-hooks';\nimport type { GenAiCallOptions } from '../core/utils';\nimport { setPiAiDriverOptions } from '../pi-ai/recording';\nimport type { PiAssistantMessage } from '../pi-ai/types';\nimport { PI_DURABLE_ORIGIN, PI_TASK } from './constants';\nimport type { PiRuns } from './runs';\nimport { createRuns, endRun, observeRunControl, readProviderSessionId, startRun, toSentryConversationId } from './runs';\nimport { instrumentTool, instrumentToolPhase } from './tools';\nimport type {\n PiDurableCallInfo,\n PiHarness,\n PiHarnessOptions,\n PiPhaseHandler,\n PiRegistryReader,\n PiRegistrySnapshot,\n PiTask,\n PiTaskRuntime,\n PiTool,\n PiToolExecutionResult,\n} from './types';\nimport { withCleanScopes } from '../../utils/withCleanScopes';\nimport { bound } from './utils';\n\n/**\n * The span hooks run for the `gen_ai.chat` spans of the model requests, which pi-ai reports, and for\n * the tool spans. `onSpanStart` runs in the scopes of the task phase, not in those of the code that\n * submitted the input. `onSpanEnd` gets the `AssistantMessage` of a model request, and what\n * `tool.execute()` returned for a tool call. A tool call still running when the Harness closes does\n * not run `onSpanEnd`.\n */\nexport type PiDurableOptions = GenAiCallOptions<PiDurableCallInfo> &\n GenAiSpanHooks<PiDurableCallInfo, PiAssistantMessage | PiToolExecutionResult>;\n\nconst INSTRUMENTED = Symbol.for('sentry.pi-durable.instrumented');\nconst RUNS = Symbol.for('sentry.pi-durable.runs');\n\n/**\n * Return pi-durable `HarnessOptions` whose task phases and tool calls are traced. The caller's\n * `registry` object is wrapped, never modified. The result has the caller's options as prototype:\n * pi-durable reads `settings`, `env` and `conversationCreated` at every use, so they stay live,\n * getters included.\n *\n * Spans:\n * - `gen_ai.invoke_agent` for each run, a new trace per run, or a child of the tool call that\n * created the conversation for a subagent;\n * - `gen_ai.chat` for each model request, under its run, from `piAiIntegration`;\n * - `gen_ai.execute_tool` for each tool call, under its run.\n *\n * The scheduler starts task phases from whichever async context last woke it, often an unrelated\n * request. Every phase therefore runs in its run's own scopes and trace, never in the ones it\n * inherits.\n */\nexport function instrumentPiDurableHarnessOptions<T extends PiHarnessOptions>(\n harnessOptions: T,\n options: PiDurableOptions = {},\n): T {\n if (!harnessOptions || (harnessOptions as Record<symbol, unknown>)[INSTRUMENTED]) {\n return harnessOptions;\n }\n\n const runs = createRuns();\n const own = (value: unknown): PropertyDescriptor => ({ value, enumerable: true, configurable: true, writable: true });\n const instrumented: T = Object.create(harnessOptions, {\n ...(harnessOptions.registry ? { registry: own(instrumentRegistry(harnessOptions.registry, options, runs)) } : {}),\n // pi-durable passes failures of extension code here, such as a throwing hook, and keeps going.\n // Only an app that passed its own `onReport` gets a chance to handle them.\n onReport: own((error: unknown) => {\n captureException(error, { mechanism: { handled: !!harnessOptions.onReport, type: PI_DURABLE_ORIGIN } });\n harnessOptions.onReport?.(error);\n }),\n });\n addNonEnumerableProperty(instrumented, INSTRUMENTED, true);\n addNonEnumerableProperty(instrumented, RUNS, runs);\n return instrumented;\n}\n\n/**\n * End the open runs and tool calls of `harness` when it closes. Closing stops the scheduler without\n * settling the inputs in flight, so nothing else would end their spans, and the maps that track\n * them would keep the spans for the lifetime of the process. A run whose ending commit is still in\n * flight ends with that commit's status.\n */\nexport function endRunsOnClose(harnessOptions: PiHarnessOptions, harness: unknown): void {\n const runs = (harnessOptions as Record<symbol, unknown>)[RUNS] as PiRuns | undefined;\n const closable = harness as PiHarness | undefined;\n if (!runs || typeof closable?.subscribeClose !== 'function') {\n return;\n }\n closable.subscribeClose(() => {\n for (const run of runs.active.values()) {\n endRun(run, runs, run.pendingEnd ? run.pendingEnd.status : { code: SPAN_STATUS_ERROR, message: 'cancelled' });\n }\n for (const calls of runs.toolCalls.values()) {\n for (const call of calls) {\n if (call.endTimestamp === undefined) {\n call.span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n }\n call.onSpanEnd?.();\n call.span.end(call.endTimestamp);\n }\n }\n runs.toolCalls.clear();\n runs.owners.clear();\n });\n}\n\nfunction instrumentRegistry(registry: PiRegistryReader, options: PiDurableOptions, runs: PiRuns): PiRegistryReader {\n // Cached so identity stays stable: the scheduler hands a task over to a new definition whenever\n // `snapshot().task(kind)` returns a different object than the one it runs.\n const snapshots = new WeakMap<PiRegistrySnapshot, PiRegistrySnapshot>();\n const tasks = new WeakMap<PiTask, PiTask>();\n const tools = new WeakMap<PiTool, PiTool>();\n\n const wrapTool = (tool: PiTool): PiTool => {\n let wrapped = tools.get(tool);\n if (!wrapped) {\n wrapped = instrumentTool(tool, runs, options);\n tools.set(tool, wrapped);\n }\n return wrapped;\n };\n\n const wrapTask = (task: PiTask | undefined): PiTask | undefined => {\n if (!task?.definition?.phases) {\n return task;\n }\n let wrapped = tasks.get(task);\n if (!wrapped) {\n const { definition } = task;\n // pi-durable calls a phase on the `phases` object and `abort` on the definition; keep that\n // receiver, so handlers that use `this` work.\n const wrapPhase =\n (phase: PiPhaseHandler, receiver: unknown, isAbort = false): PiPhaseHandler =>\n (taskRecord, runtime, context) =>\n runPhase(\n definition.name,\n observed => phase.call(receiver, taskRecord, observed, context),\n runtime,\n context,\n runs,\n wrapTool,\n isAbort,\n options,\n );\n const phases: Record<string, PiPhaseHandler> = {};\n for (const [name, phase] of Object.entries(definition.phases)) {\n phases[name] = typeof phase === 'function' ? wrapPhase(phase, definition.phases) : phase;\n }\n wrapped = {\n ...task,\n definition: {\n ...definition,\n phases,\n ...(typeof definition.abort === 'function' ? { abort: wrapPhase(definition.abort, definition, true) } : {}),\n },\n };\n tasks.set(task, wrapped);\n }\n return wrapped;\n };\n\n const wrapSnapshot = (snapshot: PiRegistrySnapshot): PiRegistrySnapshot => {\n let wrapped = snapshots.get(snapshot);\n if (!wrapped) {\n wrapped = new Proxy(snapshot, {\n get(target, property) {\n if (property === 'task') {\n return (name: string) => wrapTask(target.task(name));\n }\n if (property === 'tasks') {\n return () => target.tasks().map(task => wrapTask(task));\n }\n return bound(target, property);\n },\n });\n snapshots.set(snapshot, wrapped);\n }\n return wrapped;\n };\n\n return new Proxy(registry, {\n get(target, property) {\n if (property === 'snapshot') {\n return () => wrapSnapshot(target.snapshot());\n }\n return bound(target, property);\n },\n });\n}\n\nfunction runPhase(\n kind: string,\n phase: (runtime: PiTaskRuntime) => Promise<unknown>,\n runtime: PiTaskRuntime,\n context: unknown,\n runs: PiRuns,\n wrapTool: (tool: PiTool) => PiTool,\n isAbort: boolean,\n options: PiDurableOptions,\n): Promise<unknown> {\n const { conversationId } = runtime;\n const isRunWork = kind === PI_TASK.GENERATION || kind === PI_TASK.TOOL;\n // A compaction joins the run it was started for. One started while idle has no run, and its\n // `chat` span becomes the root of a trace of its own. An abort handler ends the run of its task,\n // so it joins that run but never starts one. Tasks of extensions never join a run.\n const run =\n isRunWork || kind === PI_TASK.COMPACTION\n ? (runs.active.get(conversationId) ?? (isRunWork && !isAbort ? startRun(conversationId, runs) : undefined))\n : undefined;\n\n let observed = runtime;\n let finishToolPhase: (() => void) | undefined;\n if (run && kind === PI_TASK.GENERATION) {\n observed = observeRunControl(runtime, run, runs);\n } else if (kind === PI_TASK.TOOL) {\n const toolPhase = instrumentToolPhase(runtime, runs, wrapTool);\n observed = toolPhase.runtime;\n finishToolPhase = toolPhase.finish;\n }\n\n const runInScope = async (scope: Scope): Promise<unknown> => {\n // Read at the first phase of a run, which is a `pi.tool` phase when a restarted Harness reruns a\n // tool call, and at each phase outside a run, such as an idle compaction or a task of an extension.\n let sessionId = run?.sessionId;\n if (!sessionId) {\n sessionId = await readProviderSessionId(runtime, context);\n if (run && sessionId) {\n run.sessionId = sessionId;\n run.span.setAttribute(GEN_AI_CONVERSATION_ID, sessionId);\n }\n }\n scope.setConversationId(sessionId ?? toSentryConversationId(runs, conversationId));\n setPiAiDriverOptions(scope, options, { operation: 'chat', runtime, context });\n try {\n return await phase(observed);\n } catch (error) {\n // The scheduler faults a task whose phase throws, and a faulted generation ends its run. A\n // throw after an abort mark, or once the Harness closes, is not a fault.\n if (!runtime.signal?.aborted) {\n captureException(error, { mechanism: { handled: false, type: PI_DURABLE_ORIGIN } });\n if (run && kind === PI_TASK.GENERATION) {\n endRun(run, runs, { code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n }\n throw error;\n } finally {\n finishToolPhase?.();\n }\n };\n\n if (!run) {\n return withCleanScopes(getDefaultIsolationScope().clone(), () =>\n startNewTrace(() => runInScope(getCurrentScope())),\n );\n }\n return withCleanScopes(run.isolationScope, () => withActiveSpan(run.span, runInScope));\n}\n"],"mappings":";;;;;;;;;AA4CA,MAAM,eAAe,OAAO,IAAI,gCAAgC;AAChE,MAAM,OAAO,OAAO,IAAI,wBAAwB;;;;;;;;;;;;;;;;;AAkBhD,SAAgB,kCACd,gBACA,UAA4B,CAAC,GAC1B;CACH,IAAI,CAAC,kBAAmB,eAA2C,eACjE,OAAO;CAGT,MAAM,OAAO,WAAW;CACxB,MAAM,OAAO,WAAwC;EAAE;EAAO,YAAY;EAAM,cAAc;EAAM,UAAU;CAAK;CACnH,MAAM,eAAkB,OAAO,OAAO,gBAAgB;EACpD,GAAI,eAAe,WAAW,EAAE,UAAU,IAAI,mBAAmB,eAAe,UAAU,SAAS,IAAI,CAAC,EAAE,IAAI,CAAC;EAG/G,UAAU,KAAK,UAAmB;GAChC,iBAAiB,OAAO,EAAE,WAAW;IAAE,SAAS,CAAC,CAAC,eAAe;IAAU,MAAM;GAAkB,EAAE,CAAC;GACtG,eAAe,WAAW,KAAK;EACjC,CAAC;CACH,CAAC;CACD,yBAAyB,cAAc,cAAc,IAAI;CACzD,yBAAyB,cAAc,MAAM,IAAI;CACjD,OAAO;AACT;;;;;;;AAQA,SAAgB,eAAe,gBAAkC,SAAwB;CACvF,MAAM,OAAQ,eAA2C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AAS,QAAQ,MAAM;EAChC,MAAM,YAAY,oBAAoB,SAAS,MAAM,QAAQ;EAC7D,WAAW,UAAU;EACrB,kBAAkB,UAAU;CAC9B;CAEA,MAAM,aAAa,OAAO,UAAmC;EAG3D,IAAI,YAAY,KAAK;EACrB,IAAI,CAAC,WAAW;GACd,YAAY,MAAM,sBAAsB,SAAS,OAAO;GACxD,IAAI,OAAO,WAAW;IACpB,IAAI,YAAY;IAChB,IAAI,KAAK,aAAa,wBAAwB,SAAS;GACzD;EACF;EACA,MAAM,kBAAkB,aAAa,uBAAuB,MAAM,cAAc,CAAC;EACjF,qBAAqB,OAAO,SAAS;GAAE,WAAW;GAAQ;GAAS;EAAQ,CAAC;EAC5E,IAAI;GACF,OAAO,MAAM,MAAM,QAAQ;EAC7B,SAAS,OAAO;GAGd,IAAI,CAAC,QAAQ,QAAQ,SAAS;IAC5B,iBAAiB,OAAO,EAAE,WAAW;KAAE,SAAS;KAAO,MAAM;IAAkB,EAAE,CAAC;IAClF,IAAI,OAAO,SAAS,QAAQ,YAC1B,OAAO,KAAK,MAAM;KAAE,MAAM;KAAmB,SAAS;IAAiB,CAAC;GAE5E;GACA,MAAM;EACR,UAAU;GACR,kBAAkB;EACpB;CACF;CAEA,IAAI,CAAC,KACH,OAAO,gBAAgB,yBAAyB,CAAC,CAAC,MAAM,SACtD,oBAAoB,WAAW,gBAAgB,CAAC,CAAC,CACnD;CAEF,OAAO,gBAAgB,IAAI,sBAAsB,eAAe,IAAI,MAAM,UAAU,CAAC;AACvF"}
@@ -1 +1 @@
1
- {"version":3,"file":"runs.js","names":[],"sources":["../../../../src/ai/pi-durable/runs.ts"],"sourcesContent":["import type { MaybeWeakRef, Scope, Span, SpanStatus } from '@sentry/core';\nimport {\n continueTrace,\n debug,\n derefWeakRef,\n getDefaultIsolationScope,\n getRootSpan,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n startNewTrace,\n uuid4,\n} from '@sentry/core';\nimport { GEN_AI_CONVERSATION_ID, GEN_AI_OPERATION_NAME, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { GEN_AI_INVOKE_AGENT } from '@sentry/conventions/op';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { MAX_TRACKED_PI_RUNS, PI_DURABLE_ORIGIN, PI_LIVE_DOC_KIND, PI_PROVIDER_DOC_KIND } from './constants';\nimport type { PiCommitChange, PiDocToken, PiLiveState, PiProviderState, PiSettlement, PiTaskRuntime } from './types';\nimport { withCleanScopes } from '../../utils/withCleanScopes';\nimport { bound } from './utils';\n\n// The definition of `pi.provider` as pi-durable checks it on a read: the address, the version and the\n// persisted semantics of the document.\nconst PROVIDER_DOC = {\n definition: { kind: PI_PROVIDER_DOC_KIND, version: 1, scope: 'conversation', history: 'latest', fork: 'initial' },\n};\n\n// Unanswered reasons that mean the run was stopped, not that it failed.\nconst CANCELLED_REASONS = new Set(['aborted', 'reset']);\n\n/**\n * One run: the work from an input to its answer. It spans several `pi.generation` tasks (run control\n * moves to a new one after every tool round) and their `pi.tool` tasks, so it is tracked per\n * conversation, which runs at most one run at a time.\n */\nexport interface PiRun {\n conversationId: unknown;\n span: Span;\n isolationScope: Scope;\n /** The run's first input submission, which identifies the run in `pi.live`. */\n firstInput?: unknown;\n /** The conversation's provider session id, read by the first phase of the run. */\n sessionId?: string;\n /**\n * The status the run ends with, set while the commit that ends it is in flight. `harness.close()`\n * can begin in that gap, because `wait()` resolves as soon as the commit settles the inputs.\n */\n pendingEnd?: { status?: SpanStatus };\n}\n\n/** Open runs of one Harness, keyed by the pi-durable conversation id. */\nexport interface PiRuns {\n /**\n * Random id of this Harness, prefixed to `gen_ai.conversation.id` until the provider session id of\n * the conversation is known. pi-durable numbers conversations per storage from 1, so the bare id\n * would merge the root conversations of every Harness into one Sentry conversation.\n */\n harnessId: string;\n active: Map<unknown, PiRun>;\n /**\n * Tool calls that created a conversation they own, keyed by that conversation. The child's first\n * run becomes a child of the call while the call's trace is in progress, and otherwise continues\n * that trace with the call as parent. This is how a subagent's run joins the trace of the run that\n * delegated to it.\n */\n owners: Map<unknown, PiOwner>;\n /**\n * Tool calls of running `pi.tool` phases, keyed by task id. Their spans end when the phase ends,\n * after it has committed the result the model receives.\n */\n toolCalls: Map<unknown, PiToolCall[]>;\n}\n\n/** A tool call that created a conversation it owns. */\nexport interface PiOwner {\n /**\n * The call's `execute_tool` span, held weakly: a conversation whose first run never starts must\n * not keep the trace of the call alive.\n */\n span: MaybeWeakRef<Span>;\n /** The `sentry-trace` value of the span, used to continue its trace once that trace has ended. */\n sentryTrace: string;\n /** The `baggage` value of the span, used together with `sentryTrace`. */\n baggage: string | undefined;\n}\n\n/** One `execute()` of a tool. */\nexport interface PiToolCall {\n span: Span;\n callId?: string;\n recordOutputs: boolean;\n /** Set once the span has a status other than ok, so the committed result does not overwrite it. */\n failed?: boolean;\n /** When `execute()` settled, used as the span's end time. */\n endTimestamp?: number;\n}\n\nexport function createRuns(): PiRuns {\n return {\n harnessId: uuid4(),\n active: new Map(),\n owners: new Map(),\n toolCalls: new Map(),\n };\n}\n\nexport function toSentryConversationId(runs: PiRuns, conversationId: unknown): string {\n return runs.active.get(conversationId)?.sessionId ?? `${runs.harnessId}:${String(conversationId)}`;\n}\n\n/**\n * Read the provider session id of the conversation, or `undefined` when pi-durable keeps none.\n *\n * pi-durable 1.0.2 and later keep a UUIDv7 per conversation in the `pi.provider` document, stored with\n * the conversation. Unlike the harness prefix, it stays the same when a Harness opens the storage\n * again, for example after a Durable Object restarts, and it is unique across storages.\n */\nexport async function readProviderSessionId(runtime: PiTaskRuntime, context: unknown): Promise<string | undefined> {\n try {\n const provider = (await runtime.snapshot?.(PROVIDER_DOC, runtime.conversationId, context)) as\n | PiProviderState\n | undefined;\n return typeof provider?.sessionId === 'string' && provider.sessionId ? provider.sessionId : undefined;\n } catch (error) {\n // A later version of the document fails the read. The harness prefix is used then.\n DEBUG_BUILD && debug.warn('[pi-durable] failed to read the provider session id', error);\n return undefined;\n }\n}\n\n/** Start a run of `conversationId`: a new trace, or a child of the tool call that owns the conversation. */\nexport function startRun(conversationId: unknown, runs: PiRuns): PiRun {\n if (runs.active.size >= MAX_TRACKED_PI_RUNS) {\n const oldest = runs.active.keys().next().value;\n runs.active.get(oldest)?.span.end();\n runs.active.delete(oldest);\n }\n\n const owner = runs.owners.get(conversationId);\n runs.owners.delete(conversationId);\n const ownerSpan = derefWeakRef(owner?.span);\n // Under a trace that has ended, the run would be split into one transaction per span when spans are\n // not streamed. Continuing the trace instead also gives the same result whether or not GC ran.\n const parentSpan = ownerSpan && getRootSpan(ownerSpan).isRecording() ? ownerSpan : undefined;\n\n const isolationScope = getDefaultIsolationScope().clone();\n const startRunSpan = (): Span =>\n startInactiveSpan({\n name: 'invoke_agent',\n op: GEN_AI_INVOKE_AGENT,\n ...(parentSpan ? { parentSpan } : {}),\n attributes: {\n [SENTRY_ORIGIN]: PI_DURABLE_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'invoke_agent',\n [GEN_AI_CONVERSATION_ID]: toSentryConversationId(runs, conversationId),\n },\n });\n const span = withCleanScopes(isolationScope, () => {\n if (parentSpan) {\n return startRunSpan();\n }\n return owner\n ? continueTrace({ sentryTrace: owner.sentryTrace, baggage: owner.baggage }, startRunSpan)\n : startNewTrace(startRunSpan);\n });\n\n const run: PiRun = { conversationId, span, isolationScope };\n runs.active.set(conversationId, run);\n DEBUG_BUILD && debug.log(`[pi-durable] run of conversation ${String(conversationId)} started`);\n return run;\n}\n\nexport function endRun(run: PiRun, runs: PiRuns, status?: SpanStatus): void {\n if (runs.active.get(run.conversationId) !== run) {\n return;\n }\n runs.active.delete(run.conversationId);\n DEBUG_BUILD && debug.log(`[pi-durable] run of conversation ${String(run.conversationId)} ended`, status ?? 'ok');\n if (status) {\n run.span.setStatus(status);\n }\n run.span.end();\n}\n\n/**\n * Watch the generation task's commits for the end of its run.\n *\n * pi-durable keeps run control in the conversation's `pi.live` document: `run` names the task that\n * owns the run and the run's inputs, it moves to the next generation after every tool round, and it\n * is removed, in the same commit that settles the inputs, when the run ends. Every commit that moves\n * or ends a run edits `pi.live` through `tx.doc()`, so reading that draft after the commit's change\n * function returns shows whether the run survived the commit.\n */\nexport function observeRunControl(runtime: PiTaskRuntime, run: PiRun, runs: PiRuns): PiTaskRuntime {\n const commit = (change: PiCommitChange, context: unknown): Promise<void> => {\n let ended = false;\n let settlement: PiSettlement | undefined;\n\n const observedChange: PiCommitChange = async (tx, current) => {\n // A commit can run its change again, so only the attempt that committed counts.\n ended = false;\n settlement = undefined;\n let live: Promise<unknown> | undefined;\n const observedTx = new Proxy(tx, {\n get(target, property) {\n const value = bound(target, property);\n if (typeof value !== 'function') {\n return value;\n }\n if (property === 'doc') {\n return (token: PiDocToken, id: unknown, ...rest: unknown[]) => {\n const draft = value(token, id, ...rest);\n if (token?.definition?.kind === PI_LIVE_DOC_KIND && id === run.conversationId) {\n live = Promise.resolve(draft);\n }\n return draft;\n };\n }\n if (property === 'settleSubmission') {\n return (id: unknown, submissionSettlement: PiSettlement, ...rest: unknown[]) => {\n if (run.firstInput === undefined || id === run.firstInput) {\n settlement = submissionSettlement;\n }\n return value(id, submissionSettlement, ...rest);\n };\n }\n return value;\n },\n });\n\n const result = await change(observedTx, current);\n const draft = (await live) as PiLiveState | undefined;\n if (draft) {\n const firstInput = draft.run?.inputs?.[0];\n if (firstInput === undefined) {\n ended = true;\n } else if (run.firstInput === undefined) {\n run.firstInput = firstInput;\n } else if (firstInput !== run.firstInput) {\n // The run ended and a queued input started the next one in the same commit.\n ended = true;\n }\n }\n run.pendingEnd = ended ? { status: toRunStatus(settlement) } : undefined;\n return result;\n };\n\n return runtime.commit(observedChange, context).then(\n () => {\n if (ended) {\n endRun(run, runs, toRunStatus(settlement));\n }\n },\n error => {\n run.pendingEnd = undefined;\n throw error;\n },\n );\n };\n\n return new Proxy(runtime, {\n get(target, property) {\n return property === 'commit' ? commit : bound(target, property);\n },\n });\n}\n\nfunction toRunStatus(settlement: PiSettlement | undefined): SpanStatus | undefined {\n if (settlement?.status !== 'unanswered') {\n return undefined;\n }\n const reason = settlement.reason ?? 'internal_error';\n return { code: SPAN_STATUS_ERROR, message: CANCELLED_REASONS.has(reason) ? 'cancelled' : reason };\n}\n"],"mappings":";;;;;;;;AAsBA,MAAM,eAAe,EACnB,YAAY;CAAE,MAAM;CAAsB,SAAS;CAAG,OAAO;CAAgB,SAAS;CAAU,MAAM;AAAU,EAClH;AAGA,MAAM,oCAAoB,IAAI,IAAI,CAAC,WAAW,OAAO,CAAC;AAqEtD,SAAgB,aAAqB;CACnC,OAAO;EACL,WAAW,MAAM;EACjB,wBAAQ,IAAI,IAAI;EAChB,wBAAQ,IAAI,IAAI;EAChB,2BAAW,IAAI,IAAI;CACrB;AACF;AAEA,SAAgB,uBAAuB,MAAc,gBAAiC;CACpF,OAAO,KAAK,OAAO,IAAI,cAAc,CAAC,EAAE,aAAa,GAAG,KAAK,UAAU,GAAG,OAAO,cAAc;AACjG;;;;;;;;AASA,eAAsB,sBAAsB,SAAwB,SAA+C;CACjH,IAAI;EACF,MAAM,WAAY,MAAM,QAAQ,WAAW,cAAc,QAAQ,gBAAgB,OAAO;EAGxF,OAAO,OAAO,UAAU,cAAc,YAAY,SAAS,YAAY,SAAS,YAAY,KAAA;CAC9F,SAAS,OAAO;EAEd,eAAe,MAAM,KAAK,uDAAuD,KAAK;EACtF;CACF;AACF;;AAGA,SAAgB,SAAS,gBAAyB,MAAqB;CACrE,IAAI,KAAK,OAAO,QAAA,KAA6B;EAC3C,MAAM,SAAS,KAAK,OAAO,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC;EACzC,KAAK,OAAO,IAAI,MAAM,CAAC,EAAE,KAAK,IAAI;EAClC,KAAK,OAAO,OAAO,MAAM;CAC3B;CAEA,MAAM,QAAQ,KAAK,OAAO,IAAI,cAAc;CAC5C,KAAK,OAAO,OAAO,cAAc;CACjC,MAAM,YAAY,aAAa,OAAO,IAAI;CAG1C,MAAM,aAAa,aAAa,YAAY,SAAS,CAAC,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],"sourcesContent":["import type { MaybeWeakRef, Scope, Span, SpanStatus } from '@sentry/core';\nimport {\n continueTrace,\n debug,\n derefWeakRef,\n getDefaultIsolationScope,\n getRootSpan,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n startNewTrace,\n uuid4,\n} from '@sentry/core';\nimport { GEN_AI_CONVERSATION_ID, GEN_AI_OPERATION_NAME, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { GEN_AI_INVOKE_AGENT } from '@sentry/conventions/op';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { MAX_TRACKED_PI_RUNS, PI_DURABLE_ORIGIN, PI_LIVE_DOC_KIND, PI_PROVIDER_DOC_KIND } from './constants';\nimport type { PiCommitChange, PiDocToken, PiLiveState, PiProviderState, PiSettlement, PiTaskRuntime } from './types';\nimport { withCleanScopes } from '../../utils/withCleanScopes';\nimport { bound } from './utils';\n\n// The definition of `pi.provider` as pi-durable checks it on a read: the address, the version and the\n// persisted semantics of the document.\nconst PROVIDER_DOC = {\n definition: { kind: PI_PROVIDER_DOC_KIND, version: 1, scope: 'conversation', history: 'latest', fork: 'initial' },\n};\n\n// Unanswered reasons that mean the run was stopped, not that it failed.\nconst CANCELLED_REASONS = new Set(['aborted', 'reset']);\n\n/**\n * One run: the work from an input to its answer. It spans several `pi.generation` tasks (run control\n * moves to a new one after every tool round) and their `pi.tool` tasks, so it is tracked per\n * conversation, which runs at most one run at a time.\n */\nexport interface PiRun {\n conversationId: unknown;\n span: Span;\n isolationScope: Scope;\n /** The run's first input submission, which identifies the run in `pi.live`. */\n firstInput?: unknown;\n /** The conversation's provider session id, read by the first phase of the run. */\n sessionId?: string;\n /**\n * The status the run ends with, set while the commit that ends it is in flight. `harness.close()`\n * can begin in that gap, because `wait()` resolves as soon as the commit settles the inputs.\n */\n pendingEnd?: { status?: SpanStatus };\n}\n\n/** Open runs of one Harness, keyed by the pi-durable conversation id. */\nexport interface PiRuns {\n /**\n * Random id of this Harness, prefixed to `gen_ai.conversation.id` until the provider session id of\n * the conversation is known. pi-durable numbers conversations per storage from 1, so the bare id\n * would merge the root conversations of every Harness into one Sentry conversation.\n */\n harnessId: string;\n active: Map<unknown, PiRun>;\n /**\n * Tool calls that created a conversation they own, keyed by that conversation. The child's first\n * run becomes a child of the call while the call's trace is in progress, and otherwise continues\n * that trace with the call as parent. This is how a subagent's run joins the trace of the run that\n * delegated to it.\n */\n owners: Map<unknown, PiOwner>;\n /**\n * Tool calls of running `pi.tool` phases, keyed by task id. Their spans end when the phase ends,\n * after it has committed the result the model receives.\n */\n toolCalls: Map<unknown, PiToolCall[]>;\n}\n\n/** A tool call that created a conversation it owns. */\nexport interface PiOwner {\n /**\n * The call's `execute_tool` span, held weakly: a conversation whose first run never starts must\n * not keep the trace of the call alive.\n */\n span: MaybeWeakRef<Span>;\n /** The `sentry-trace` value of the span, used to continue its trace once that trace has ended. */\n sentryTrace: string;\n /** The `baggage` value of the span, used together with `sentryTrace`. */\n baggage: string | undefined;\n}\n\n/** One `execute()` of a tool. */\nexport interface PiToolCall {\n span: Span;\n callId?: string;\n recordOutputs: boolean;\n /** Set once the span has a status other than ok, so the committed result does not overwrite it. */\n failed?: boolean;\n /** When `execute()` settled, used as the span's end time. */\n endTimestamp?: number;\n /** Set once `execute()` settled. Runs `onSpanEnd` with its result. */\n onSpanEnd?: () => void;\n}\n\nexport function createRuns(): PiRuns {\n return {\n harnessId: uuid4(),\n active: new Map(),\n owners: new Map(),\n toolCalls: new Map(),\n };\n}\n\nexport function toSentryConversationId(runs: PiRuns, conversationId: unknown): string {\n return runs.active.get(conversationId)?.sessionId ?? `${runs.harnessId}:${String(conversationId)}`;\n}\n\n/**\n * Read the provider session id of the conversation, or `undefined` when pi-durable keeps none.\n *\n * pi-durable 1.0.2 and later keep a UUIDv7 per conversation in the `pi.provider` document, stored with\n * the conversation. Unlike the harness prefix, it stays the same when a Harness opens the storage\n * again, for example after a Durable Object restarts, and it is unique across storages.\n */\nexport async function readProviderSessionId(runtime: PiTaskRuntime, context: unknown): Promise<string | undefined> {\n try {\n const provider = (await runtime.snapshot?.(PROVIDER_DOC, runtime.conversationId, context)) as\n | PiProviderState\n | undefined;\n return typeof provider?.sessionId === 'string' && provider.sessionId ? provider.sessionId : undefined;\n } catch (error) {\n // A later version of the document fails the read. The harness prefix is used then.\n DEBUG_BUILD && debug.warn('[pi-durable] failed to read the provider session id', error);\n return undefined;\n }\n}\n\n/** Start a run of `conversationId`: a new trace, or a child of the tool call that owns the conversation. */\nexport function startRun(conversationId: unknown, runs: PiRuns): PiRun {\n if (runs.active.size >= MAX_TRACKED_PI_RUNS) {\n const oldest = runs.active.keys().next().value;\n runs.active.get(oldest)?.span.end();\n runs.active.delete(oldest);\n }\n\n const owner = runs.owners.get(conversationId);\n runs.owners.delete(conversationId);\n const ownerSpan = derefWeakRef(owner?.span);\n // Under a trace that has ended, the run would be split into one transaction per span when spans are\n // not streamed. Continuing the trace instead also gives the same result whether or not GC ran.\n const parentSpan = ownerSpan && getRootSpan(ownerSpan).isRecording() ? ownerSpan : undefined;\n\n const isolationScope = getDefaultIsolationScope().clone();\n const startRunSpan = (): Span =>\n startInactiveSpan({\n name: 'invoke_agent',\n op: GEN_AI_INVOKE_AGENT,\n ...(parentSpan ? { parentSpan } : {}),\n attributes: {\n [SENTRY_ORIGIN]: PI_DURABLE_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'invoke_agent',\n [GEN_AI_CONVERSATION_ID]: toSentryConversationId(runs, conversationId),\n },\n });\n const span = withCleanScopes(isolationScope, () => {\n if (parentSpan) {\n return startRunSpan();\n }\n return owner\n ? continueTrace({ sentryTrace: owner.sentryTrace, baggage: owner.baggage }, startRunSpan)\n : startNewTrace(startRunSpan);\n });\n\n const run: PiRun = { conversationId, span, isolationScope };\n runs.active.set(conversationId, run);\n DEBUG_BUILD && debug.log(`[pi-durable] run of conversation ${String(conversationId)} started`);\n return run;\n}\n\nexport function endRun(run: PiRun, runs: PiRuns, status?: SpanStatus): void {\n if (runs.active.get(run.conversationId) !== run) {\n return;\n }\n runs.active.delete(run.conversationId);\n DEBUG_BUILD && debug.log(`[pi-durable] run of conversation ${String(run.conversationId)} ended`, status ?? 'ok');\n if (status) {\n run.span.setStatus(status);\n }\n run.span.end();\n}\n\n/**\n * Watch the generation task's commits for the end of its run.\n *\n * pi-durable keeps run control in the conversation's `pi.live` document: `run` names the task that\n * owns the run and the run's inputs, it moves to the next generation after every tool round, and it\n * is removed, in the same commit that settles the inputs, when the run ends. Every commit that moves\n * or ends a run edits `pi.live` through `tx.doc()`, so reading that draft after the commit's change\n * function returns shows whether the run survived the commit.\n */\nexport function observeRunControl(runtime: PiTaskRuntime, run: PiRun, runs: PiRuns): PiTaskRuntime {\n const commit = (change: PiCommitChange, context: unknown): Promise<void> => {\n let ended = false;\n let settlement: PiSettlement | undefined;\n\n const observedChange: PiCommitChange = async (tx, current) => {\n // A commit can run its change again, so only the attempt that committed counts.\n ended = false;\n settlement = undefined;\n let live: Promise<unknown> | undefined;\n const observedTx = new Proxy(tx, {\n get(target, property) {\n const value = bound(target, property);\n if (typeof value !== 'function') {\n return value;\n }\n if (property === 'doc') {\n return (token: PiDocToken, id: unknown, ...rest: unknown[]) => {\n const draft = value(token, id, ...rest);\n if (token?.definition?.kind === PI_LIVE_DOC_KIND && id === run.conversationId) {\n live = Promise.resolve(draft);\n }\n return draft;\n };\n }\n if (property === 'settleSubmission') {\n return (id: unknown, submissionSettlement: PiSettlement, ...rest: unknown[]) => {\n if (run.firstInput === undefined || id === run.firstInput) {\n settlement = submissionSettlement;\n }\n return value(id, submissionSettlement, ...rest);\n };\n }\n return value;\n },\n });\n\n const result = await change(observedTx, current);\n const draft = (await live) as PiLiveState | undefined;\n if (draft) {\n const firstInput = draft.run?.inputs?.[0];\n if (firstInput === undefined) {\n ended = true;\n } else if (run.firstInput === undefined) {\n run.firstInput = firstInput;\n } else if (firstInput !== run.firstInput) {\n // The run ended and a queued input started the next one in the same commit.\n ended = true;\n }\n }\n run.pendingEnd = ended ? { status: toRunStatus(settlement) } : undefined;\n return result;\n };\n\n return runtime.commit(observedChange, context).then(\n () => {\n if (ended) {\n endRun(run, runs, toRunStatus(settlement));\n }\n },\n error => {\n run.pendingEnd = undefined;\n throw error;\n },\n );\n };\n\n return new Proxy(runtime, {\n get(target, property) {\n return property === 'commit' ? commit : bound(target, property);\n },\n });\n}\n\nfunction toRunStatus(settlement: PiSettlement | undefined): SpanStatus | undefined {\n if (settlement?.status !== 'unanswered') {\n return undefined;\n }\n const reason = settlement.reason ?? 'internal_error';\n return { code: SPAN_STATUS_ERROR, message: CANCELLED_REASONS.has(reason) ? 'cancelled' : reason };\n}\n"],"mappings":";;;;;;;;AAsBA,MAAM,eAAe,EACnB,YAAY;CAAE,MAAM;CAAsB,SAAS;CAAG,OAAO;CAAgB,SAAS;CAAU,MAAM;AAAU,EAClH;AAGA,MAAM,oCAAoB,IAAI,IAAI,CAAC,WAAW,OAAO,CAAC;AAuEtD,SAAgB,aAAqB;CACnC,OAAO;EACL,WAAW,MAAM;EACjB,wBAAQ,IAAI,IAAI;EAChB,wBAAQ,IAAI,IAAI;EAChB,2BAAW,IAAI,IAAI;CACrB;AACF;AAEA,SAAgB,uBAAuB,MAAc,gBAAiC;CACpF,OAAO,KAAK,OAAO,IAAI,cAAc,CAAC,EAAE,aAAa,GAAG,KAAK,UAAU,GAAG,OAAO,cAAc;AACjG;;;;;;;;AASA,eAAsB,sBAAsB,SAAwB,SAA+C;CACjH,IAAI;EACF,MAAM,WAAY,MAAM,QAAQ,WAAW,cAAc,QAAQ,gBAAgB,OAAO;EAGxF,OAAO,OAAO,UAAU,cAAc,YAAY,SAAS,YAAY,SAAS,YAAY,KAAA;CAC9F,SAAS,OAAO;EAEd,eAAe,MAAM,KAAK,uDAAuD,KAAK;EACtF;CACF;AACF;;AAGA,SAAgB,SAAS,gBAAyB,MAAqB;CACrE,IAAI,KAAK,OAAO,QAAA,KAA6B;EAC3C,MAAM,SAAS,KAAK,OAAO,KAAK,CAAC,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AAM,QAAQ,QAAQ;CAChE,EACF,CAAC;AACH;AAEA,SAAS,YAAY,YAA8D;CACjF,IAAI,YAAY,WAAW,cACzB;CAEF,MAAM,SAAS,WAAW,UAAU;CACpC,OAAO;EAAE,MAAM;EAAmB,SAAS,kBAAkB,IAAI,MAAM,IAAI,cAAc;CAAO;AAClG"}
@@ -1,5 +1,6 @@
1
1
  import { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from "../core/gen-ai-attributes.js";
2
- import { resolveAIRecordingOptions } from "../core/utils.js";
2
+ import { runGenAiSpanEnd, runGenAiSpanStart } from "../core/span-hooks.js";
3
+ import { resolveGenAiCallRecording } from "../core/utils.js";
3
4
  import { piAiContentToString } from "../pi-ai/messages.js";
4
5
  import { PI_DURABLE_ORIGIN } from "./constants.js";
5
6
  import { toSentryConversationId } from "./runs.js";
@@ -55,7 +56,14 @@ function instrumentToolPhase(runtime, runs, wrapTool) {
55
56
  /** Wrap a tool so each call gets a `gen_ai.execute_tool` span. */
56
57
  function instrumentTool(tool, runs, options) {
57
58
  const execute = (args, api, context) => {
58
- const { recordInputs, recordOutputs } = resolveAIRecordingOptions(options);
59
+ const toolCall = {
60
+ operation: "execute_tool",
61
+ tool,
62
+ args,
63
+ api,
64
+ context
65
+ };
66
+ const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, toolCall);
59
67
  const phaseCalls = runs.toolCalls.get(api?.taskId);
60
68
  const calls = phaseCalls?.some((call) => call.callId !== void 0 && call.callId === api?.callId) ? void 0 : phaseCalls;
61
69
  return startSpanManual({
@@ -77,9 +85,11 @@ function instrumentTool(tool, runs, options) {
77
85
  recordOutputs
78
86
  };
79
87
  calls?.push(call);
88
+ runGenAiSpanStart(options, span, toolCall);
80
89
  try {
81
90
  const result = await tool.execute(args, trackOwnedConversations(api, span, runs), context);
82
91
  call.endTimestamp = timestampInSeconds();
92
+ call.onSpanEnd = () => runGenAiSpanEnd(options, span, toolCall, { response: result });
83
93
  if (!calls) finishToolCall(call, {
84
94
  content: result?.output ?? result?.content,
85
95
  isError: result?.isError
@@ -88,6 +98,7 @@ function instrumentTool(tool, runs, options) {
88
98
  } catch (error) {
89
99
  call.endTimestamp = timestampInSeconds();
90
100
  call.failed = true;
101
+ call.onSpanEnd = () => runGenAiSpanEnd(options, span, toolCall, { error });
91
102
  if (context?.abortSignal?.aborted) span.setStatus({
92
103
  code: SPAN_STATUS_ERROR,
93
104
  message: "cancelled"
@@ -102,7 +113,10 @@ function instrumentTool(tool, runs, options) {
102
113
  type: PI_DURABLE_ORIGIN
103
114
  } });
104
115
  }
105
- if (!calls) span.end(call.endTimestamp);
116
+ if (!calls) {
117
+ call.onSpanEnd();
118
+ span.end(call.endTimestamp);
119
+ }
106
120
  throw error;
107
121
  }
108
122
  });
@@ -120,6 +134,7 @@ function finishToolCall(call, message) {
120
134
  message: "internal_error"
121
135
  });
122
136
  }
137
+ call.onSpanEnd?.();
123
138
  call.span.end(call.endTimestamp);
124
139
  }
125
140
  function observeToolResultEntries(tx, committed) {
@@ -1 +1 @@
1
- {"version":3,"file":"tools.js","names":[],"sources":["../../../../src/ai/pi-durable/tools.ts"],"sourcesContent":["import type { Span } from '@sentry/core';\nimport {\n captureException,\n isObjectLike,\n makeWeakRef,\n SPAN_STATUS_ERROR,\n spanToBaggageHeader,\n spanToTraceHeader,\n startSpanManual,\n stringify,\n timestampInSeconds,\n} from '@sentry/core';\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_OPERATION_NAME,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DESCRIPTION,\n GEN_AI_TOOL_NAME,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_EXECUTE_TOOL } from '@sentry/conventions/op';\nimport { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport type { GenAiOptions } from '../core/utils';\nimport { resolveAIRecordingOptions } from '../core/utils';\nimport { piAiContentToString } from '../pi-ai/messages';\nimport { MAX_TRACKED_PI_RUNS, PI_DURABLE_ORIGIN, PI_TOOL_RESULT_ENTRY_KIND } from './constants';\nimport type { PiRuns, PiToolCall } from './runs';\nimport { toSentryConversationId } from './runs';\nimport type {\n PiAgent,\n PiCommitChange,\n PiEntryToken,\n PiTaskRuntime,\n PiTool,\n PiToolExecutionApi,\n PiToolResultMessage,\n} from './types';\nimport { bound } from './utils';\n\n/**\n * The tools pi-durable's `createBashTool`, `createReadTool`, `createEditTool` and `createWriteTool`\n * factories return. They throw to report expected failures to the model, such as a command that\n * exits non-zero, so their throws are not captured. Filled by the integration from the factories'\n * channels, which also covers the tools an app registers in an extension of its own.\n */\nconst BUILT_IN_TOOLS = new WeakSet<object>();\n\nexport function markBuiltInTool(tool: unknown): void {\n if (isObjectLike(tool)) {\n BUILT_IN_TOOLS.add(tool);\n }\n}\n\n/**\n * Prepare the runtime of a `pi.tool` phase. The tool task resolves the called tool from its agent,\n * so the runtime hands out traced tools, and it collects the result entries the phase commits.\n * `finish` ends the phase's tool spans with the result the model receives, which pi-durable builds\n * after `execute()` returns: from `api.output()`, through `afterTool` hooks and output limits.\n */\nexport function instrumentToolPhase(\n runtime: PiTaskRuntime,\n runs: PiRuns,\n wrapTool: (tool: PiTool) => PiTool,\n): { runtime: PiTaskRuntime; finish: () => void } {\n const results = new Map<unknown, PiToolResultMessage>();\n runs.toolCalls.set(runtime.taskId, []);\n\n const agent = (context: unknown): Promise<PiAgent> =>\n runtime\n .agent(context)\n .then(resolved => (resolved?.tools ? { ...resolved, tools: resolved.tools.map(wrapTool) } : resolved));\n\n const commit = (change: PiCommitChange, context: unknown): Promise<void> => {\n let committed: PiToolResultMessage[] = [];\n const observedChange: PiCommitChange = (tx, current) => {\n // A commit can run its change again, so only the attempt that committed counts.\n committed = [];\n return change(observeToolResultEntries(tx, committed), current);\n };\n return runtime.commit(observedChange, context).then(() => {\n for (const message of committed) {\n results.set(message.toolCallId, message);\n }\n });\n };\n\n return {\n runtime: new Proxy(runtime, {\n get(target, property) {\n if (property === 'agent') {\n return agent;\n }\n return property === 'commit' ? commit : bound(target, property);\n },\n }),\n finish: () => {\n for (const call of runs.toolCalls.get(runtime.taskId) ?? []) {\n finishToolCall(call, call.callId !== undefined ? results.get(call.callId) : undefined);\n }\n runs.toolCalls.delete(runtime.taskId);\n },\n };\n}\n\n/** Wrap a tool so each call gets a `gen_ai.execute_tool` span. */\nexport function instrumentTool(tool: PiTool, runs: PiRuns, options: GenAiOptions): PiTool {\n const execute = (args: unknown, api: PiToolExecutionApi, context: unknown): Promise<unknown> => {\n const { recordInputs, recordOutputs } = resolveAIRecordingOptions(options);\n const phaseCalls = runs.toolCalls.get(api?.taskId);\n // A tool that runs another tool of its agent passes its own `api` on, so the inner call shares\n // the call id. Only the outer call gets the committed result; the inner one ends with its own.\n const calls = phaseCalls?.some(call => call.callId !== undefined && call.callId === api?.callId)\n ? undefined\n : phaseCalls;\n\n return startSpanManual(\n {\n name: `execute_tool ${tool.name}`,\n op: GEN_AI_EXECUTE_TOOL,\n attributes: {\n [SENTRY_ORIGIN]: PI_DURABLE_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'execute_tool',\n [GEN_AI_TOOL_NAME]: tool.name,\n [GEN_AI_TOOL_DESCRIPTION]: tool.description,\n [GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: api?.callId,\n ...(api?.conversationId !== undefined\n ? { [GEN_AI_CONVERSATION_ID]: toSentryConversationId(runs, api.conversationId) }\n : {}),\n ...(recordInputs && args !== undefined ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(args) } : {}),\n },\n },\n async span => {\n const call: PiToolCall = { span, callId: api?.callId, recordOutputs };\n calls?.push(call);\n try {\n const result = await tool.execute(args, trackOwnedConversations(api, span, runs), context);\n call.endTimestamp = timestampInSeconds();\n if (!calls) {\n // No result entry follows a call outside a tool task phase, nor a nested call.\n finishToolCall(call, { content: result?.output ?? result?.content, isError: result?.isError });\n }\n return result;\n } catch (error) {\n call.endTimestamp = timestampInSeconds();\n call.failed = true;\n // pi-durable turns the throw into an error result for the model, so the app never gets a\n // chance to handle it. An aborted call is not a failure.\n if ((context as { abortSignal?: AbortSignal } | undefined)?.abortSignal?.aborted) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n } else {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n if (!BUILT_IN_TOOLS.has(tool)) {\n captureException(error, { mechanism: { handled: false, type: PI_DURABLE_ORIGIN } });\n }\n }\n if (!calls) {\n span.end(call.endTimestamp);\n }\n throw error;\n }\n },\n );\n };\n\n // The proxy's target is an empty object with the tool as prototype, not the tool itself, so a\n // frozen tool does not break the proxy invariants. Members are read bound to the tool, so a\n // method that reads a private field works.\n return new Proxy(Object.create(tool) as PiTool, {\n get(_target, property) {\n return property === 'execute' ? execute : bound(tool, property);\n },\n });\n}\n\nfunction finishToolCall(call: PiToolCall, message: PiToolResultMessage | undefined): void {\n if (message) {\n const result = call.recordOutputs ? piAiContentToString(message.content) : undefined;\n if (result !== undefined) {\n call.span.setAttribute(GEN_AI_TOOL_CALL_RESULT, result);\n }\n if (message.isError && !call.failed) {\n call.span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n }\n call.span.end(call.endTimestamp);\n}\n\nfunction observeToolResultEntries(tx: object, committed: PiToolResultMessage[]): object {\n return new Proxy(tx, {\n get(target, property) {\n const value = bound(target, property);\n if (property !== 'appendEntry' || typeof value !== 'function') {\n return value;\n }\n return (\n token: PiEntryToken,\n conversationId: unknown,\n draft: { model?: unknown[] } | undefined,\n ...rest: unknown[]\n ) => {\n const message = token?.kind === PI_TOOL_RESULT_ENTRY_KIND ? draft?.model?.[0] : undefined;\n if (isObjectLike(message)) {\n committed.push(message);\n }\n return value(token, conversationId, draft, ...rest);\n };\n },\n });\n}\n\n/**\n * Record the conversations a tool call creates for itself, the subagent pattern: `api.commit()` with\n * `tx.createConversation()` or `tx.forkConversation()` and `ownership: { kind: 'task', taskId: api.taskId }`.\n */\nfunction trackOwnedConversations(api: PiToolExecutionApi, span: Span, runs: PiRuns): PiToolExecutionApi {\n if (typeof api?.commit !== 'function') {\n return api;\n }\n const commit = api.commit.bind(api);\n\n const trackCreatedConversations = (tx: object): object =>\n new Proxy(tx, {\n get(target, property) {\n const value = bound(target, property);\n if ((property !== 'createConversation' && property !== 'forkConversation') || typeof value !== 'function') {\n return value;\n }\n return async (...args: unknown[]) => {\n const record = (await value(...args)) as { id?: unknown } | undefined;\n const ownership = args.find(\n (arg): arg is { ownership: { kind?: string } } => isObjectLike(arg) && isObjectLike(arg.ownership),\n )?.ownership;\n if (ownership?.kind === 'task' && record?.id !== undefined) {\n if (runs.owners.size >= MAX_TRACKED_PI_RUNS) {\n runs.owners.delete(runs.owners.keys().next().value);\n }\n runs.owners.set(record.id, {\n span: makeWeakRef(span),\n sentryTrace: spanToTraceHeader(span),\n baggage: spanToBaggageHeader(span),\n });\n }\n return record;\n };\n },\n });\n\n return new Proxy(api, {\n get(target, property) {\n if (property !== 'commit') {\n return bound(target, property);\n }\n return (change: (tx: object) => unknown, context: unknown) =>\n commit((tx: object) => change(trackCreatedConversations(tx)), context);\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA8CA,MAAM,iCAAiB,IAAI,QAAgB;AAE3C,SAAgB,gBAAgB,MAAqB;CACnD,IAAI,aAAa,IAAI,GACnB,eAAe,IAAI,IAAI;AAE3B;;;;;;;AAQA,SAAgB,oBACd,SACA,MACA,UACgD;CAChD,MAAM,0BAAU,IAAI,IAAkC;CACtD,KAAK,UAAU,IAAI,QAAQ,QAAQ,CAAC,CAAC;CAErC,MAAM,SAAS,YACb,QACG,MAAM,OAAO,CAAC,CACd,MAAK,aAAa,UAAU,QAAQ;EAAE,GAAG;EAAU,OAAO,SAAS,MAAM,IAAI,QAAQ;CAAE,IAAI,QAAS;CAEzG,MAAM,UAAU,QAAwB,YAAoC;EAC1E,IAAI,YAAmC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I,QAAQ,UAAU;EACpB,IAAI,aAAa,UACf,OAAO,MAAM,QAAQ,QAAQ;EAE/B,QAAQ,QAAiC,YACvC,QAAQ,OAAe,OAAO,0BAA0B,EAAE,CAAC,GAAG,OAAO;CACzE,EACF,CAAC;AACH"}
1
+ {"version":3,"file":"tools.js","names":[],"sources":["../../../../src/ai/pi-durable/tools.ts"],"sourcesContent":["import type { Span } from '@sentry/core';\nimport {\n captureException,\n isObjectLike,\n makeWeakRef,\n SPAN_STATUS_ERROR,\n spanToBaggageHeader,\n spanToTraceHeader,\n startSpanManual,\n stringify,\n timestampInSeconds,\n} from '@sentry/core';\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_OPERATION_NAME,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DESCRIPTION,\n GEN_AI_TOOL_NAME,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_EXECUTE_TOOL } from '@sentry/conventions/op';\nimport { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport type { GenAiSpanHooks } from '../core/span-hooks';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { GenAiCallOptions } from '../core/utils';\nimport { resolveGenAiCallRecording } from '../core/utils';\nimport { piAiContentToString } from '../pi-ai/messages';\nimport { MAX_TRACKED_PI_RUNS, PI_DURABLE_ORIGIN, PI_TOOL_RESULT_ENTRY_KIND } from './constants';\nimport type { PiRuns, PiToolCall } from './runs';\nimport { toSentryConversationId } from './runs';\nimport type {\n PiAgent,\n PiCommitChange,\n PiDurableCallInfo,\n PiEntryToken,\n PiTaskRuntime,\n PiTool,\n PiToolExecutionApi,\n PiToolExecutionResult,\n PiToolResultMessage,\n} from './types';\nimport { bound } from './utils';\n\n/**\n * The tools pi-durable's `createBashTool`, `createReadTool`, `createEditTool` and `createWriteTool`\n * factories return. They throw to report expected failures to the model, such as a command that\n * exits non-zero, so their throws are not captured. Filled by the integration from the factories'\n * channels, which also covers the tools an app registers in an extension of its own.\n */\nconst BUILT_IN_TOOLS = new WeakSet<object>();\n\nexport function markBuiltInTool(tool: unknown): void {\n if (isObjectLike(tool)) {\n BUILT_IN_TOOLS.add(tool);\n }\n}\n\n/**\n * Prepare the runtime of a `pi.tool` phase. The tool task resolves the called tool from its agent,\n * so the runtime hands out traced tools, and it collects the result entries the phase commits.\n * `finish` ends the phase's tool spans with the result the model receives, which pi-durable builds\n * after `execute()` returns: from `api.output()`, through `afterTool` hooks and output limits.\n */\nexport function instrumentToolPhase(\n runtime: PiTaskRuntime,\n runs: PiRuns,\n wrapTool: (tool: PiTool) => PiTool,\n): { runtime: PiTaskRuntime; finish: () => void } {\n const results = new Map<unknown, PiToolResultMessage>();\n runs.toolCalls.set(runtime.taskId, []);\n\n const agent = (context: unknown): Promise<PiAgent> =>\n runtime\n .agent(context)\n .then(resolved => (resolved?.tools ? { ...resolved, tools: resolved.tools.map(wrapTool) } : resolved));\n\n const commit = (change: PiCommitChange, context: unknown): Promise<void> => {\n let committed: PiToolResultMessage[] = [];\n const observedChange: PiCommitChange = (tx, current) => {\n // A commit can run its change again, so only the attempt that committed counts.\n committed = [];\n return change(observeToolResultEntries(tx, committed), current);\n };\n return runtime.commit(observedChange, context).then(() => {\n for (const message of committed) {\n results.set(message.toolCallId, message);\n }\n });\n };\n\n return {\n runtime: new Proxy(runtime, {\n get(target, property) {\n if (property === 'agent') {\n return agent;\n }\n return property === 'commit' ? commit : bound(target, property);\n },\n }),\n finish: () => {\n for (const call of runs.toolCalls.get(runtime.taskId) ?? []) {\n finishToolCall(call, call.callId !== undefined ? results.get(call.callId) : undefined);\n }\n runs.toolCalls.delete(runtime.taskId);\n },\n };\n}\n\n/** Wrap a tool so each call gets a `gen_ai.execute_tool` span. */\nexport function instrumentTool(\n tool: PiTool,\n runs: PiRuns,\n options: GenAiCallOptions<PiDurableCallInfo> & GenAiSpanHooks<PiDurableCallInfo, PiToolExecutionResult>,\n): PiTool {\n const execute = (args: unknown, api: PiToolExecutionApi, context: unknown): Promise<unknown> => {\n const toolCall: PiDurableCallInfo = { operation: 'execute_tool', tool, args, api, context };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, toolCall);\n const phaseCalls = runs.toolCalls.get(api?.taskId);\n // A tool that runs another tool of its agent passes its own `api` on, so the inner call shares\n // the call id. Only the outer call gets the committed result; the inner one ends with its own.\n const calls = phaseCalls?.some(call => call.callId !== undefined && call.callId === api?.callId)\n ? undefined\n : phaseCalls;\n\n return startSpanManual(\n {\n name: `execute_tool ${tool.name}`,\n op: GEN_AI_EXECUTE_TOOL,\n attributes: {\n [SENTRY_ORIGIN]: PI_DURABLE_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'execute_tool',\n [GEN_AI_TOOL_NAME]: tool.name,\n [GEN_AI_TOOL_DESCRIPTION]: tool.description,\n [GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: api?.callId,\n ...(api?.conversationId !== undefined\n ? { [GEN_AI_CONVERSATION_ID]: toSentryConversationId(runs, api.conversationId) }\n : {}),\n ...(recordInputs && args !== undefined ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(args) } : {}),\n },\n },\n async span => {\n const call: PiToolCall = { span, callId: api?.callId, recordOutputs };\n calls?.push(call);\n runGenAiSpanStart(options, span, toolCall);\n try {\n const result = await tool.execute(args, trackOwnedConversations(api, span, runs), context);\n call.endTimestamp = timestampInSeconds();\n call.onSpanEnd = () => runGenAiSpanEnd(options, span, toolCall, { response: result });\n if (!calls) {\n // No result entry follows a call outside a tool task phase, nor a nested call.\n finishToolCall(call, { content: result?.output ?? result?.content, isError: result?.isError });\n }\n return result;\n } catch (error) {\n call.endTimestamp = timestampInSeconds();\n call.failed = true;\n call.onSpanEnd = () => runGenAiSpanEnd(options, span, toolCall, { error });\n // pi-durable turns the throw into an error result for the model, so the app never gets a\n // chance to handle it. An aborted call is not a failure.\n if ((context as { abortSignal?: AbortSignal } | undefined)?.abortSignal?.aborted) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n } else {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n if (!BUILT_IN_TOOLS.has(tool)) {\n captureException(error, { mechanism: { handled: false, type: PI_DURABLE_ORIGIN } });\n }\n }\n if (!calls) {\n call.onSpanEnd();\n span.end(call.endTimestamp);\n }\n throw error;\n }\n },\n );\n };\n\n // The proxy's target is an empty object with the tool as prototype, not the tool itself, so a\n // frozen tool does not break the proxy invariants. Members are read bound to the tool, so a\n // method that reads a private field works.\n return new Proxy(Object.create(tool) as PiTool, {\n get(_target, property) {\n return property === 'execute' ? execute : bound(tool, property);\n },\n });\n}\n\nfunction finishToolCall(call: PiToolCall, message: PiToolResultMessage | undefined): void {\n if (message) {\n const result = call.recordOutputs ? piAiContentToString(message.content) : undefined;\n if (result !== undefined) {\n call.span.setAttribute(GEN_AI_TOOL_CALL_RESULT, result);\n }\n if (message.isError && !call.failed) {\n call.span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n }\n call.onSpanEnd?.();\n call.span.end(call.endTimestamp);\n}\n\nfunction observeToolResultEntries(tx: object, committed: PiToolResultMessage[]): object {\n return new Proxy(tx, {\n get(target, property) {\n const value = bound(target, property);\n if (property !== 'appendEntry' || typeof value !== 'function') {\n return value;\n }\n return (\n token: PiEntryToken,\n conversationId: unknown,\n draft: { model?: unknown[] } | undefined,\n ...rest: unknown[]\n ) => {\n const message = token?.kind === PI_TOOL_RESULT_ENTRY_KIND ? draft?.model?.[0] : undefined;\n if (isObjectLike(message)) {\n committed.push(message);\n }\n return value(token, conversationId, draft, ...rest);\n };\n },\n });\n}\n\n/**\n * Record the conversations a tool call creates for itself, the subagent pattern: `api.commit()` with\n * `tx.createConversation()` or `tx.forkConversation()` and `ownership: { kind: 'task', taskId: api.taskId }`.\n */\nfunction trackOwnedConversations(api: PiToolExecutionApi, span: Span, runs: PiRuns): PiToolExecutionApi {\n if (typeof api?.commit !== 'function') {\n return api;\n }\n const commit = api.commit.bind(api);\n\n const trackCreatedConversations = (tx: object): object =>\n new Proxy(tx, {\n get(target, property) {\n const value = bound(target, property);\n if ((property !== 'createConversation' && property !== 'forkConversation') || typeof value !== 'function') {\n return value;\n }\n return async (...args: unknown[]) => {\n const record = (await value(...args)) as { id?: unknown } | undefined;\n const ownership = args.find(\n (arg): arg is { ownership: { kind?: string } } => isObjectLike(arg) && isObjectLike(arg.ownership),\n )?.ownership;\n if (ownership?.kind === 'task' && record?.id !== undefined) {\n if (runs.owners.size >= MAX_TRACKED_PI_RUNS) {\n runs.owners.delete(runs.owners.keys().next().value);\n }\n runs.owners.set(record.id, {\n span: makeWeakRef(span),\n sentryTrace: spanToTraceHeader(span),\n baggage: spanToBaggageHeader(span),\n });\n }\n return record;\n };\n },\n });\n\n return new Proxy(api, {\n get(target, property) {\n if (property !== 'commit') {\n return bound(target, property);\n }\n return (change: (tx: object) => unknown, context: unknown) =>\n commit((tx: object) => change(trackCreatedConversations(tx)), context);\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAkDA,MAAM,iCAAiB,IAAI,QAAgB;AAE3C,SAAgB,gBAAgB,MAAqB;CACnD,IAAI,aAAa,IAAI,GACnB,eAAe,IAAI,IAAI;AAE3B;;;;;;;AAQA,SAAgB,oBACd,SACA,MACA,UACgD;CAChD,MAAM,0BAAU,IAAI,IAAkC;CACtD,KAAK,UAAU,IAAI,QAAQ,QAAQ,CAAC,CAAC;CAErC,MAAM,SAAS,YACb,QACG,MAAM,OAAO,CAAC,CACd,MAAK,aAAa,UAAU,QAAQ;EAAE,GAAG;EAAU,OAAO,SAAS,MAAM,IAAI,QAAQ;CAAE,IAAI,QAAS;CAEzG,MAAM,UAAU,QAAwB,YAAoC;EAC1E,IAAI,YAAmC,CAAC;EACxC,MAAM,kBAAkC,IAAI,YAAY;GAEtD,YAAY,CAAC;GACb,OAAO,OAAO,yBAAy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EpD,KAAK,OAAO,IAAI,OAAO,IAAI;KACzB,MAAM,YAAY,IAAI;KACtB,aAAa,kBAAkB,IAAI;KACnC,SAAS,oBAAoB,IAAI;IACnC,CAAC;GACH;GACA,OAAO;EACT;CACF,EACF,CAAC;CAEH,OAAO,IAAI,MAAM,KAAK,EACpB,IAAI,QAAQ,UAAU;EACpB,IAAI,aAAa,UACf,OAAO,MAAM,QAAQ,QAAQ;EAE/B,QAAQ,QAAiC,YACvC,QAAQ,OAAe,OAAO,0BAA0B,EAAE,CAAC,GAAG,OAAO;CACzE,EACF,CAAC;AACH"}
@@ -1,4 +1,5 @@
1
- import { getEvaluationInputMessages, getEvaluationOutputMessages, resolveAIRecordingOptions } from "../core/utils.js";
1
+ import { runGenAiSpanEnd, runGenAiSpanStart } from "../core/span-hooks.js";
2
+ import { getEvaluationInputMessages, getEvaluationOutputMessages, resolveGenAiCallRecording } from "../core/utils.js";
2
3
  import { TYPESAFE_ORIGIN, TYPESAFE_PROVIDER_NAME } from "./constants.js";
3
4
  import { GEN_AI_INPUT_MESSAGES, GEN_AI_OPERATION_NAME, GEN_AI_OUTPUT_MESSAGES, GEN_AI_PROVIDER_NAME, GEN_AI_REQUEST_MODEL, GEN_AI_RESPONSE_MODEL, GEN_AI_USAGE_INPUT_TOKENS, GEN_AI_USAGE_OUTPUT_TOKENS, GEN_AI_USAGE_TOTAL_TOKENS, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
4
5
  import { SPAN_STATUS_ERROR, isObjectLike, startInactiveSpan, withActiveSpan } from "@sentry/core";
@@ -63,31 +64,38 @@ function instrumentTypeSafeClient(client, options) {
63
64
  return new Proxy(client, { get(target, prop) {
64
65
  const value = Reflect.get(target, prop, target);
65
66
  if (typeof value !== "function") return value;
66
- if (prop === "systemOne") return (...args) => instrumentSystemOne(value, target, args, options);
67
+ if (prop === "systemOne") return (...args) => instrumentSystemOne(value, target, args, options ?? {});
67
68
  return value.bind(target);
68
69
  } });
69
70
  }
70
71
  function instrumentSystemOne(systemOne, client, args, options) {
71
- const { recordInputs, recordOutputs } = resolveAIRecordingOptions(options);
72
+ const call = { request: args[0] };
73
+ const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);
72
74
  const span = startDecideSpan(args[0], client, recordInputs);
73
- const endWithError = () => {
75
+ runGenAiSpanStart(options, span, call);
76
+ const endWithError = (error) => {
74
77
  span.setStatus({
75
78
  code: SPAN_STATUS_ERROR,
76
79
  message: "internal_error"
77
80
  });
81
+ runGenAiSpanEnd(options, span, call, { error });
78
82
  span.end();
79
83
  };
80
84
  let result;
81
85
  try {
82
86
  result = withActiveSpan(span, () => systemOne.apply(client, args));
83
87
  } catch (error) {
84
- endWithError();
88
+ endWithError(error);
85
89
  throw error;
86
90
  }
87
91
  if (!onSystemOneResponse(result, (body) => {
88
92
  addResponseAttributes(span, body, recordOutputs);
93
+ runGenAiSpanEnd(options, span, call, { response: body });
89
94
  span.end();
90
- }, endWithError)) span.end();
95
+ }, endWithError)) {
96
+ runGenAiSpanEnd(options, span, call, { response: result });
97
+ span.end();
98
+ }
91
99
  return result;
92
100
  }
93
101
  export { addResponseAttributes, instrumentTypeSafeClient, onSystemOneResponse, startDecideSpan };