@sentry/server-utils 11.14.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 (277) hide show
  1. package/build/cjs/chunks/exports.js +526 -217
  2. package/build/cjs/chunks/exports.js.map +1 -1
  3. package/build/cjs/index.js +1028 -120
  4. package/build/cjs/index.js.map +1 -1
  5. package/build/esm/ai/anthropic-ai/index.js +32 -56
  6. package/build/esm/ai/anthropic-ai/index.js.map +1 -1
  7. package/build/esm/ai/anthropic-ai/streaming.js +10 -6
  8. package/build/esm/ai/anthropic-ai/streaming.js.map +1 -1
  9. package/build/esm/ai/anthropic-ai/tool-runner.js +18 -3
  10. package/build/esm/ai/anthropic-ai/tool-runner.js.map +1 -1
  11. package/build/esm/ai/anthropic-ai/utils.js +41 -3
  12. package/build/esm/ai/anthropic-ai/utils.js.map +1 -1
  13. package/build/esm/ai/core/span-hooks.js +23 -0
  14. package/build/esm/ai/core/span-hooks.js.map +1 -0
  15. package/build/esm/ai/core/time-to-first-chunk.js +14 -0
  16. package/build/esm/ai/core/time-to-first-chunk.js.map +1 -0
  17. package/build/esm/ai/core/utils.js +29 -3
  18. package/build/esm/ai/core/utils.js.map +1 -1
  19. package/build/esm/ai/flue/index.js +15 -12
  20. package/build/esm/ai/flue/index.js.map +1 -1
  21. package/build/esm/ai/flue/utils.js +24 -17
  22. package/build/esm/ai/flue/utils.js.map +1 -1
  23. package/build/esm/ai/google-genai/index.js +21 -8
  24. package/build/esm/ai/google-genai/index.js.map +1 -1
  25. package/build/esm/ai/google-genai/streaming.js +6 -2
  26. package/build/esm/ai/google-genai/streaming.js.map +1 -1
  27. package/build/esm/ai/langchain/embeddings.js +5 -2
  28. package/build/esm/ai/langchain/embeddings.js.map +1 -1
  29. package/build/esm/ai/langchain/index.js +82 -24
  30. package/build/esm/ai/langchain/index.js.map +1 -1
  31. package/build/esm/ai/langchain/utils.js +9 -1
  32. package/build/esm/ai/langchain/utils.js.map +1 -1
  33. package/build/esm/ai/langgraph/agent-span.js +13 -5
  34. package/build/esm/ai/langgraph/agent-span.js.map +1 -1
  35. package/build/esm/ai/langgraph/index.js +13 -15
  36. package/build/esm/ai/langgraph/index.js.map +1 -1
  37. package/build/esm/ai/langgraph/stream.js +4 -3
  38. package/build/esm/ai/langgraph/stream.js.map +1 -1
  39. package/build/esm/ai/langgraph/utils.js +17 -8
  40. package/build/esm/ai/langgraph/utils.js.map +1 -1
  41. package/build/esm/ai/mastra/classifier-evaluation.js.map +1 -1
  42. package/build/esm/ai/mastra/index.js +33 -16
  43. package/build/esm/ai/mastra/index.js.map +1 -1
  44. package/build/esm/ai/mastra/utils.js +3 -5
  45. package/build/esm/ai/mastra/utils.js.map +1 -1
  46. package/build/esm/ai/mistral/index.js +21 -7
  47. package/build/esm/ai/mistral/index.js.map +1 -1
  48. package/build/esm/ai/mistral/streaming.js +4 -2
  49. package/build/esm/ai/mistral/streaming.js.map +1 -1
  50. package/build/esm/ai/openai/index.js +19 -8
  51. package/build/esm/ai/openai/index.js.map +1 -1
  52. package/build/esm/ai/openai/streaming.js +7 -2
  53. package/build/esm/ai/openai/streaming.js.map +1 -1
  54. package/build/esm/ai/pi-ai/chat.js +18 -1
  55. package/build/esm/ai/pi-ai/chat.js.map +1 -1
  56. package/build/esm/ai/pi-ai/recording.js +34 -15
  57. package/build/esm/ai/pi-ai/recording.js.map +1 -1
  58. package/build/esm/ai/pi-durable/index.js +7 -2
  59. package/build/esm/ai/pi-durable/index.js.map +1 -1
  60. package/build/esm/ai/pi-durable/runs.js.map +1 -1
  61. package/build/esm/ai/pi-durable/tools.js +18 -3
  62. package/build/esm/ai/pi-durable/tools.js.map +1 -1
  63. package/build/esm/ai/typesafe/index.js +14 -6
  64. package/build/esm/ai/typesafe/index.js.map +1 -1
  65. package/build/esm/ai/workers-ai/index.js +26 -9
  66. package/build/esm/ai/workers-ai/index.js.map +1 -1
  67. package/build/esm/ai/workers-ai/streaming.js +6 -4
  68. package/build/esm/ai/workers-ai/streaming.js.map +1 -1
  69. package/build/esm/cron/common.js +16 -0
  70. package/build/esm/cron/common.js.map +1 -0
  71. package/build/esm/cron/cron.js +82 -0
  72. package/build/esm/cron/cron.js.map +1 -0
  73. package/build/esm/cron/index.js +13 -0
  74. package/build/esm/cron/index.js.map +1 -0
  75. package/build/esm/cron/node-cron.js +66 -0
  76. package/build/esm/cron/node-cron.js.map +1 -0
  77. package/build/esm/cron/node-schedule.js +43 -0
  78. package/build/esm/cron/node-schedule.js.map +1 -0
  79. package/build/esm/index.js +6 -2
  80. package/build/esm/index.js.map +1 -1
  81. package/build/esm/integrations/anthropic.js +25 -16
  82. package/build/esm/integrations/anthropic.js.map +1 -1
  83. package/build/esm/integrations/aws-sdk/index.js +1 -0
  84. package/build/esm/integrations/aws-sdk/index.js.map +1 -1
  85. package/build/esm/integrations/aws-sdk/services/ServicesExtensions.js +3 -0
  86. package/build/esm/integrations/aws-sdk/services/ServicesExtensions.js.map +1 -1
  87. package/build/esm/integrations/aws-sdk/services/bedrock-runtime.js +45 -12
  88. package/build/esm/integrations/aws-sdk/services/bedrock-runtime.js.map +1 -1
  89. package/build/esm/integrations/bullmq/contextManager.js +45 -0
  90. package/build/esm/integrations/bullmq/contextManager.js.map +1 -0
  91. package/build/esm/integrations/bullmq/index.js +44 -0
  92. package/build/esm/integrations/bullmq/index.js.map +1 -0
  93. package/build/esm/integrations/bullmq/meter.js +86 -0
  94. package/build/esm/integrations/bullmq/meter.js.map +1 -0
  95. package/build/esm/integrations/bullmq/span.js +114 -0
  96. package/build/esm/integrations/bullmq/span.js.map +1 -0
  97. package/build/esm/integrations/bullmq/tracer.js +62 -0
  98. package/build/esm/integrations/bullmq/tracer.js.map +1 -0
  99. package/build/esm/integrations/express/instrumentation.js +10 -1
  100. package/build/esm/integrations/express/instrumentation.js.map +1 -1
  101. package/build/esm/integrations/google-genai.js +17 -9
  102. package/build/esm/integrations/google-genai.js.map +1 -1
  103. package/build/esm/integrations/langgraph.js +5 -7
  104. package/build/esm/integrations/langgraph.js.map +1 -1
  105. package/build/esm/integrations/mastra-classifier.js +1 -1
  106. package/build/esm/integrations/mastra-classifier.js.map +1 -1
  107. package/build/esm/integrations/mistral.js +13 -4
  108. package/build/esm/integrations/mistral.js.map +1 -1
  109. package/build/esm/integrations/openai-compatible.js +16 -8
  110. package/build/esm/integrations/openai-compatible.js.map +1 -1
  111. package/build/esm/integrations/openai.js +16 -8
  112. package/build/esm/integrations/openai.js.map +1 -1
  113. package/build/esm/integrations/pi-ai.js +39 -18
  114. package/build/esm/integrations/pi-ai.js.map +1 -1
  115. package/build/esm/integrations/pino.js +131 -0
  116. package/build/esm/integrations/pino.js.map +1 -0
  117. package/build/esm/integrations/typesafe.js +17 -3
  118. package/build/esm/integrations/typesafe.js.map +1 -1
  119. package/build/esm/integrations/vercel-ai/index.js.map +1 -1
  120. package/build/esm/integrations/vercel-ai/util.js +3 -2
  121. package/build/esm/integrations/vercel-ai/util.js.map +1 -1
  122. package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js +44 -17
  123. package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -1
  124. package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js +22 -16
  125. package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js.map +1 -1
  126. package/build/esm/integrations/winston.js +90 -0
  127. package/build/esm/integrations/winston.js.map +1 -0
  128. package/build/esm/orchestrion/detect.js +1 -1
  129. package/build/esm/orchestrion/detect.js.map +1 -1
  130. package/build/esm/package.json +1 -1
  131. package/build/types/ai/anthropic-ai/index.d.ts +1 -5
  132. package/build/types/ai/anthropic-ai/index.d.ts.map +1 -1
  133. package/build/types/ai/anthropic-ai/streaming.d.ts +3 -2
  134. package/build/types/ai/anthropic-ai/streaming.d.ts.map +1 -1
  135. package/build/types/ai/anthropic-ai/tool-runner.d.ts.map +1 -1
  136. package/build/types/ai/anthropic-ai/types.d.ts +24 -3
  137. package/build/types/ai/anthropic-ai/types.d.ts.map +1 -1
  138. package/build/types/ai/anthropic-ai/utils.d.ts +2 -3
  139. package/build/types/ai/anthropic-ai/utils.d.ts.map +1 -1
  140. package/build/types/ai/core/span-hooks.d.ts +31 -0
  141. package/build/types/ai/core/span-hooks.d.ts.map +1 -0
  142. package/build/types/ai/core/time-to-first-chunk.d.ts +7 -0
  143. package/build/types/ai/core/time-to-first-chunk.d.ts.map +1 -0
  144. package/build/types/ai/core/utils.d.ts +30 -1
  145. package/build/types/ai/core/utils.d.ts.map +1 -1
  146. package/build/types/ai/flue/index.d.ts +13 -5
  147. package/build/types/ai/flue/index.d.ts.map +1 -1
  148. package/build/types/ai/flue/types.d.ts +20 -2
  149. package/build/types/ai/flue/types.d.ts.map +1 -1
  150. package/build/types/ai/flue/utils.d.ts +5 -9
  151. package/build/types/ai/flue/utils.d.ts.map +1 -1
  152. package/build/types/ai/google-genai/index.d.ts.map +1 -1
  153. package/build/types/ai/google-genai/streaming.d.ts +2 -1
  154. package/build/types/ai/google-genai/streaming.d.ts.map +1 -1
  155. package/build/types/ai/google-genai/types.d.ts +17 -3
  156. package/build/types/ai/google-genai/types.d.ts.map +1 -1
  157. package/build/types/ai/langchain/index.d.ts.map +1 -1
  158. package/build/types/ai/langchain/types.d.ts +49 -3
  159. package/build/types/ai/langchain/types.d.ts.map +1 -1
  160. package/build/types/ai/langchain/utils.d.ts +6 -0
  161. package/build/types/ai/langchain/utils.d.ts.map +1 -1
  162. package/build/types/ai/langgraph/agent-span.d.ts +4 -1
  163. package/build/types/ai/langgraph/agent-span.d.ts.map +1 -1
  164. package/build/types/ai/langgraph/index.d.ts +1 -1
  165. package/build/types/ai/langgraph/index.d.ts.map +1 -1
  166. package/build/types/ai/langgraph/stream.d.ts.map +1 -1
  167. package/build/types/ai/langgraph/types.d.ts +14 -3
  168. package/build/types/ai/langgraph/types.d.ts.map +1 -1
  169. package/build/types/ai/langgraph/utils.d.ts +3 -0
  170. package/build/types/ai/langgraph/utils.d.ts.map +1 -1
  171. package/build/types/ai/mastra/classifier-evaluation.d.ts +3 -3
  172. package/build/types/ai/mastra/classifier-evaluation.d.ts.map +1 -1
  173. package/build/types/ai/mastra/index.d.ts +17 -3
  174. package/build/types/ai/mastra/index.d.ts.map +1 -1
  175. package/build/types/ai/mastra/types.d.ts +2 -0
  176. package/build/types/ai/mastra/types.d.ts.map +1 -1
  177. package/build/types/ai/mastra/utils.d.ts.map +1 -1
  178. package/build/types/ai/mistral/index.d.ts.map +1 -1
  179. package/build/types/ai/mistral/streaming.d.ts +2 -1
  180. package/build/types/ai/mistral/streaming.d.ts.map +1 -1
  181. package/build/types/ai/mistral/types.d.ts +14 -3
  182. package/build/types/ai/mistral/types.d.ts.map +1 -1
  183. package/build/types/ai/openai/index.d.ts.map +1 -1
  184. package/build/types/ai/openai/streaming.d.ts +3 -1
  185. package/build/types/ai/openai/streaming.d.ts.map +1 -1
  186. package/build/types/ai/openai/types.d.ts +14 -3
  187. package/build/types/ai/openai/types.d.ts.map +1 -1
  188. package/build/types/ai/pi-ai/chat.d.ts +7 -1
  189. package/build/types/ai/pi-ai/chat.d.ts.map +1 -1
  190. package/build/types/ai/pi-ai/recording.d.ts +21 -9
  191. package/build/types/ai/pi-ai/recording.d.ts.map +1 -1
  192. package/build/types/ai/pi-ai/types.d.ts +16 -0
  193. package/build/types/ai/pi-ai/types.d.ts.map +1 -1
  194. package/build/types/ai/pi-durable/index.d.ts +12 -3
  195. package/build/types/ai/pi-durable/index.d.ts.map +1 -1
  196. package/build/types/ai/pi-durable/runs.d.ts +2 -0
  197. package/build/types/ai/pi-durable/runs.d.ts.map +1 -1
  198. package/build/types/ai/pi-durable/tools.d.ts +4 -3
  199. package/build/types/ai/pi-durable/tools.d.ts.map +1 -1
  200. package/build/types/ai/pi-durable/types.d.ts +15 -0
  201. package/build/types/ai/pi-durable/types.d.ts.map +1 -1
  202. package/build/types/ai/typesafe/index.d.ts +10 -2
  203. package/build/types/ai/typesafe/index.d.ts.map +1 -1
  204. package/build/types/ai/workers-ai/index.d.ts.map +1 -1
  205. package/build/types/ai/workers-ai/streaming.d.ts +2 -1
  206. package/build/types/ai/workers-ai/streaming.d.ts.map +1 -1
  207. package/build/types/ai/workers-ai/types.d.ts +18 -3
  208. package/build/types/ai/workers-ai/types.d.ts.map +1 -1
  209. package/build/types/cron/common.d.ts +8 -0
  210. package/build/types/cron/common.d.ts.map +1 -0
  211. package/build/types/cron/cron.d.ts +45 -0
  212. package/build/types/cron/cron.d.ts.map +1 -0
  213. package/build/types/cron/index.d.ts +10 -0
  214. package/build/types/cron/index.d.ts.map +1 -0
  215. package/build/types/cron/node-cron.d.ts +33 -0
  216. package/build/types/cron/node-cron.d.ts.map +1 -0
  217. package/build/types/cron/node-schedule.d.ts +19 -0
  218. package/build/types/cron/node-schedule.d.ts.map +1 -0
  219. package/build/types/index.d.ts +5 -2
  220. package/build/types/index.d.ts.map +1 -1
  221. package/build/types/integrations/anthropic.d.ts +2 -1
  222. package/build/types/integrations/anthropic.d.ts.map +1 -1
  223. package/build/types/integrations/aws-sdk/index.d.ts +3 -3
  224. package/build/types/integrations/aws-sdk/index.d.ts.map +1 -1
  225. package/build/types/integrations/aws-sdk/services/ServiceExtension.d.ts +1 -0
  226. package/build/types/integrations/aws-sdk/services/ServiceExtension.d.ts.map +1 -1
  227. package/build/types/integrations/aws-sdk/services/ServicesExtensions.d.ts +3 -2
  228. package/build/types/integrations/aws-sdk/services/ServicesExtensions.d.ts.map +1 -1
  229. package/build/types/integrations/aws-sdk/services/bedrock-runtime.d.ts +25 -4
  230. package/build/types/integrations/aws-sdk/services/bedrock-runtime.d.ts.map +1 -1
  231. package/build/types/integrations/bullmq/contextManager.d.ts +13 -0
  232. package/build/types/integrations/bullmq/contextManager.d.ts.map +1 -0
  233. package/build/types/integrations/bullmq/index.d.ts +43 -0
  234. package/build/types/integrations/bullmq/index.d.ts.map +1 -0
  235. package/build/types/integrations/bullmq/meter.d.ts +7 -0
  236. package/build/types/integrations/bullmq/meter.d.ts.map +1 -0
  237. package/build/types/integrations/bullmq/span.d.ts +35 -0
  238. package/build/types/integrations/bullmq/span.d.ts.map +1 -0
  239. package/build/types/integrations/bullmq/tracer.d.ts +5 -0
  240. package/build/types/integrations/bullmq/tracer.d.ts.map +1 -0
  241. package/build/types/integrations/bullmq/types.d.ts +72 -0
  242. package/build/types/integrations/bullmq/types.d.ts.map +1 -0
  243. package/build/types/integrations/express/types.d.ts +1 -0
  244. package/build/types/integrations/express/types.d.ts.map +1 -1
  245. package/build/types/integrations/flue.d.ts +2 -1
  246. package/build/types/integrations/flue.d.ts.map +1 -1
  247. package/build/types/integrations/google-genai.d.ts +2 -1
  248. package/build/types/integrations/google-genai.d.ts.map +1 -1
  249. package/build/types/integrations/groq.d.ts +1 -1
  250. package/build/types/integrations/langchain.d.ts +2 -1
  251. package/build/types/integrations/langchain.d.ts.map +1 -1
  252. package/build/types/integrations/langgraph.d.ts +2 -1
  253. package/build/types/integrations/langgraph.d.ts.map +1 -1
  254. package/build/types/integrations/mistral.d.ts +2 -1
  255. package/build/types/integrations/mistral.d.ts.map +1 -1
  256. package/build/types/integrations/openai-compatible.d.ts.map +1 -1
  257. package/build/types/integrations/openai.d.ts +2 -1
  258. package/build/types/integrations/openai.d.ts.map +1 -1
  259. package/build/types/integrations/pi-ai.d.ts +6 -3
  260. package/build/types/integrations/pi-ai.d.ts.map +1 -1
  261. package/build/types/integrations/pi-durable.d.ts +2 -1
  262. package/build/types/integrations/pi-durable.d.ts.map +1 -1
  263. package/build/types/integrations/pino.d.ts +61 -0
  264. package/build/types/integrations/pino.d.ts.map +1 -0
  265. package/build/types/integrations/together-ai.d.ts +1 -1
  266. package/build/types/integrations/typesafe.d.ts +2 -2
  267. package/build/types/integrations/typesafe.d.ts.map +1 -1
  268. package/build/types/integrations/vercel-ai/index.d.ts +3 -3
  269. package/build/types/integrations/vercel-ai/index.d.ts.map +1 -1
  270. package/build/types/integrations/vercel-ai/util.d.ts +2 -1
  271. package/build/types/integrations/vercel-ai/util.d.ts.map +1 -1
  272. package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts +20 -4
  273. package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts.map +1 -1
  274. package/build/types/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.d.ts.map +1 -1
  275. package/build/types/integrations/winston.d.ts +55 -0
  276. package/build/types/integrations/winston.d.ts.map +1 -0
  277. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"streaming.js","names":[],"sources":["../../../../src/ai/mistral/streaming.ts"],"sourcesContent":["import type { Span } from '@sentry/core';\nimport { endStreamSpan, getErrorStatus, setOutputMessagesAttribute } from '../core/utils';\nimport type { MistralCompletionChunk, MistralToolCall } from './types';\nimport { contentToString } from './utils';\n\n/**\n * State accumulated while consuming a Mistral event stream.\n */\ninterface StreamingState {\n responseTexts: string[];\n finishReasons: string[];\n responseId: string;\n responseModel: string;\n promptTokens: number | undefined;\n completionTokens: number | undefined;\n totalTokens: number | undefined;\n /** Tool calls accumulated by their delta `index`; `function.arguments` arrives fragmented. */\n toolCalls: Record<number, MistralToolCall>;\n}\n\n/** Which drain path owns accumulation. See {@link instrumentEventStream}. */\ntype StreamConsumer = 'iterator' | 'reader';\n\ntype AsyncIterableStream = { [Symbol.asyncIterator]: () => AsyncIterator<unknown> };\n\ninterface StreamReaderLike {\n read: () => Promise<{ done: boolean; value?: unknown }>;\n cancel?: (reason?: unknown) => Promise<unknown>;\n}\n\ninterface ReadableStreamLike {\n getReader?: (...args: unknown[]) => StreamReaderLike;\n cancel?: (reason?: unknown) => Promise<unknown>;\n tee?: () => unknown;\n pipeTo?: (destination: unknown, options?: unknown) => Promise<unknown>;\n pipeThrough?: (transform: unknown, options?: unknown) => unknown;\n}\n\n/** Whether a value can be drained with `for await`. */\nexport function isAsyncIterable(value: unknown): value is AsyncIterableStream {\n return !!value && typeof (value as AsyncIterableStream)[Symbol.asyncIterator] === 'function';\n}\n\nfunction createStreamingState(): StreamingState {\n return {\n responseTexts: [],\n finishReasons: [],\n responseId: '',\n responseModel: '',\n promptTokens: undefined,\n completionTokens: undefined,\n totalTokens: undefined,\n toolCalls: {},\n };\n}\n\nfunction processToolCalls(toolCalls: MistralToolCall[], state: StreamingState): void {\n for (const toolCall of toolCalls) {\n const index = toolCall.index;\n if (index === undefined || !toolCall.function) {\n continue;\n }\n\n const existing = state.toolCalls[index];\n if (!existing) {\n state.toolCalls[index] = {\n ...toolCall,\n function: { name: toolCall.function.name, arguments: toolCall.function.arguments ?? '' },\n };\n } else if (toolCall.function.arguments && existing.function) {\n existing.function.arguments = `${existing.function.arguments}${toolCall.function.arguments}`;\n }\n }\n}\n\nfunction processChunk(chunk: MistralCompletionChunk, 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 // Input tokens stay constant across the stream; output tokens are only finalized in the last\n // event, so we overwrite on every event that carries usage to guarantee the totals are set.\n state.promptTokens = chunk.usage.promptTokens;\n state.completionTokens = chunk.usage.completionTokens;\n state.totalTokens = chunk.usage.totalTokens;\n }\n\n for (const choice of chunk.choices ?? []) {\n if (recordOutputs) {\n // Deltas carry either a plain string or the same content-chunk array the non-streaming\n // responses use, so both go through `contentToString`.\n const content = contentToString(choice.delta?.content);\n if (content) {\n state.responseTexts.push(content);\n }\n if (choice.delta?.toolCalls) {\n processToolCalls(choice.delta.toolCalls, state);\n }\n }\n if (choice.finishReason) {\n state.finishReasons.push(choice.finishReason);\n }\n }\n}\n\n/** Mistral yields `CompletionEvent` objects that wrap the chunk under `data`. */\nfunction processEvent(event: unknown, state: StreamingState, recordOutputs: boolean): void {\n const chunk = (event as { data?: MistralCompletionChunk } | undefined)?.data;\n if (chunk && typeof chunk === 'object') {\n processChunk(chunk, state, recordOutputs);\n }\n}\n\nasync function* instrumentIterator(\n iterate: () => AsyncIterator<unknown>,\n state: StreamingState,\n recordOutputs: boolean,\n claim: (consumer: StreamConsumer) => boolean,\n settle: (error?: unknown) => void,\n): AsyncGenerator<unknown, void, unknown> {\n try {\n for await (const event of { [Symbol.asyncIterator]: iterate }) {\n if (claim('iterator')) {\n processEvent(event, state, recordOutputs);\n }\n yield event;\n }\n } catch (error) {\n settle(error);\n throw error;\n } finally {\n settle();\n }\n}\n\nfunction wrapReader(\n reader: StreamReaderLike,\n state: StreamingState,\n recordOutputs: boolean,\n claim: (consumer: StreamConsumer) => boolean,\n settle: (error?: unknown) => void,\n markCancelled: () => void,\n): StreamReaderLike {\n // Captured before the proxy exists so the wrappers below call the real reader, not themselves.\n const originalRead = reader.read;\n const originalCancel = reader.cancel;\n const read = (): Promise<{ done: boolean; value?: unknown }> => originalRead.call(reader);\n const cancel =\n typeof originalCancel === 'function'\n ? (reason?: unknown): Promise<unknown> => originalCancel.call(reader, reason)\n : undefined;\n\n return new Proxy(reader, {\n get(target: StreamReaderLike, prop: string | symbol): unknown {\n if (prop === 'read') {\n return async (): Promise<{ done: boolean; value?: unknown }> => {\n try {\n const result = await read();\n if (result.done) {\n settle();\n } else if (claim('reader')) {\n processEvent(result.value, state, recordOutputs);\n }\n return result;\n } catch (error) {\n settle(error);\n throw error;\n }\n };\n }\n\n if (prop === 'cancel' && cancel) {\n return async (reason?: unknown): Promise<unknown> => {\n markCancelled();\n try {\n return await cancel(reason);\n } finally {\n settle();\n }\n };\n }\n\n const value = Reflect.get(target, prop, target) as unknown;\n return typeof value === 'function' ? value.bind(target) : value;\n },\n });\n}\n\n/**\n * A stream that pulls through `readable`'s instrumented reader.\n *\n * `tee`, `pipeTo` and `pipeThrough` acquire their reader through internal slots rather than by\n * calling the public `getReader`, so patching that method alone leaves them uninstrumented: the\n * chunks bypass accumulation and the span is never ended. Handing them this stream instead routes\n * them back through the wrapped reader, so there is still exactly one accumulating consumer.\n *\n * Same idea as `monitorStream` in `@sentry/deno`, with two deliberate differences: chunks are pulled\n * on demand rather than drained in a `start` loop, so backpressure still reaches the source, and\n * `cancel` is forwarded (the hole #24054 fixed there) so the source stops producing when the\n * consumer disconnects.\n */\nfunction instrumentedSource(readable: ReadableStreamLike): ReadableStream<unknown> {\n // The patched `getReader`, so reads are accumulated and the span is ended by the shared logic.\n const reader = readable.getReader!();\n\n return new ReadableStream({\n async pull(controller) {\n const { done, value } = await reader.read();\n if (done) {\n controller.close();\n return;\n }\n controller.enqueue(value);\n },\n async cancel(reason) {\n await reader.cancel?.(reason);\n },\n });\n}\n\n/**\n * Instrument a Mistral event stream in place: accumulate response attributes as it is drained and\n * end `span` when it finishes.\n *\n * The stream is patched rather than replaced because `EventStream` extends `ReadableStream`, so\n * handing back a bare async generator would drop `getReader`, `tee`, `pipeTo` and the rest of the\n * `ReadableStream` API the caller is entitled to.\n *\n * Both `for await` and `getReader()` are valid ways to drain a `ReadableStream`, and the SDK's\n * iterator polyfill reads through `getReader()`, so both are wrapped. The first path to see a chunk\n * claims accumulation and the other stays a pass-through, which keeps a chunk from being counted\n * twice when one path drives the other.\n *\n * Returns `false` for a value that is not a stream, leaving it untouched.\n */\nexport function instrumentEventStream(\n stream: unknown,\n span: Span,\n recordOutputs: boolean,\n abortSignal?: AbortSignal,\n): boolean {\n if (!isAsyncIterable(stream)) {\n return false;\n }\n\n const state = createStreamingState();\n let consumer: StreamConsumer | undefined;\n let settled = false;\n let cancelled = false;\n\n const claim = (candidate: StreamConsumer): boolean => {\n consumer ??= candidate;\n return consumer === candidate;\n };\n\n // Set synchronously when the caller asks to cancel, before the underlying cancel is awaited.\n // Cancelling can reject an in-flight `read()` (it aborts the HTTP body the stream reads from), and\n // that rejection would otherwise reach `settle` first and record a deliberate abort as a failure.\n const markCancelled = (): void => {\n cancelled = true;\n };\n\n const settle = (error?: unknown): void => {\n if (settled) {\n return;\n }\n settled = true;\n if (error !== undefined && !cancelled) {\n span.setStatus(getErrorStatus(abortSignal));\n }\n\n const toolCalls = Object.values(state.toolCalls);\n\n if (recordOutputs) {\n // Set the authoritative `gen_ai.output.messages` alongside the deprecated response attributes\n // `endStreamSpan` writes, so tool calls survive Relay's lossy migration. A stream is a single\n // assistant turn, so the accumulated fragments make up one message.\n setOutputMessagesAttribute(span, {\n responseText: state.responseTexts.join(''),\n toolCalls,\n finishReason: state.finishReasons[0],\n });\n }\n\n endStreamSpan(span, { ...state, toolCalls }, recordOutputs);\n };\n\n const iterate = stream[Symbol.asyncIterator].bind(stream);\n const instrumented = instrumentIterator(iterate, state, recordOutputs, claim, settle);\n stream[Symbol.asyncIterator] = () => instrumented;\n\n const readable = stream as ReadableStreamLike;\n\n if (typeof readable.getReader === 'function') {\n const getReader = readable.getReader.bind(readable);\n readable.getReader = (...args: unknown[]) =>\n wrapReader(getReader(...args), state, recordOutputs, claim, settle, markCancelled);\n }\n\n if (typeof readable.cancel === 'function') {\n const cancel = readable.cancel.bind(readable);\n readable.cancel = async (reason?: unknown): Promise<unknown> => {\n markCancelled();\n try {\n return await cancel(reason);\n } finally {\n settle();\n }\n };\n }\n\n // Only patched when `getReader` is present, since that is what `instrumentedSource` pulls through.\n if (typeof readable.getReader === 'function') {\n if (typeof readable.tee === 'function') {\n readable.tee = () => instrumentedSource(readable).tee();\n }\n\n if (typeof readable.pipeTo === 'function') {\n readable.pipeTo = (destination: unknown, options?: unknown) =>\n instrumentedSource(readable).pipeTo(destination as WritableStream<unknown>, options as StreamPipeOptions);\n }\n\n if (typeof readable.pipeThrough === 'function') {\n readable.pipeThrough = (transform: unknown, options?: unknown) =>\n instrumentedSource(readable).pipeThrough(\n transform as ReadableWritablePair<unknown, unknown>,\n options as StreamPipeOptions,\n );\n }\n }\n\n return true;\n}\n"],"mappings":";;;;AAuCA,SAAgB,gBAAgB,OAA8C;CAC5E,OAAO,CAAC,CAAC,SAAS,OAAQ,MAA8B,OAAO,mBAAmB;AACpF;AAEA,SAAS,uBAAuC;CAC9C,OAAO;EACL,eAAe,CAAC;EAChB,eAAe,CAAC;EAChB,YAAY;EACZ,eAAe;EACf,cAAc,KAAA;EACd,kBAAkB,KA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C1B,SAAS,YAAY,mBAAmB,QAAQ,CAAC,CAAC,IAAI;EAGxD,IAAI,OAAO,SAAS,WAAW,YAC7B,SAAS,UAAU,aAAsB,YACvC,mBAAmB,QAAQ,CAAC,CAAC,OAAO,aAAwC,OAA4B;EAG5G,IAAI,OAAO,SAAS,gBAAgB,YAClC,SAAS,eAAe,WAAoB,YAC1C,mBAAmB,QAAQ,CAAC,CAAC,YAC3B,WACA,OACF;CAEN;CAEA,OAAO;AACT"}
1
+ {"version":3,"file":"streaming.js","names":[],"sources":["../../../../src/ai/mistral/streaming.ts"],"sourcesContent":["import type { Span } from '@sentry/core';\nimport type { GenAiSpanResult } from '../core/span-hooks';\nimport { endStreamSpan, getErrorStatus, setOutputMessagesAttribute } from '../core/utils';\nimport { recordTimeToFirstChunk } from '../core/time-to-first-chunk';\nimport type { MistralCompletionChunk, MistralToolCall } from './types';\nimport { contentToString } from './utils';\n\n/**\n * State accumulated while consuming a Mistral event stream.\n */\ninterface StreamingState {\n responseTexts: string[];\n finishReasons: string[];\n responseId: string;\n responseModel: string;\n promptTokens: number | undefined;\n completionTokens: number | undefined;\n totalTokens: number | undefined;\n /** Tool calls accumulated by their delta `index`; `function.arguments` arrives fragmented. */\n toolCalls: Record<number, MistralToolCall>;\n}\n\n/** Which drain path owns accumulation. See {@link instrumentEventStream}. */\ntype StreamConsumer = 'iterator' | 'reader';\n\ntype AsyncIterableStream = { [Symbol.asyncIterator]: () => AsyncIterator<unknown> };\n\ninterface StreamReaderLike {\n read: () => Promise<{ done: boolean; value?: unknown }>;\n cancel?: (reason?: unknown) => Promise<unknown>;\n}\n\ninterface ReadableStreamLike {\n getReader?: (...args: unknown[]) => StreamReaderLike;\n cancel?: (reason?: unknown) => Promise<unknown>;\n tee?: () => unknown;\n pipeTo?: (destination: unknown, options?: unknown) => Promise<unknown>;\n pipeThrough?: (transform: unknown, options?: unknown) => unknown;\n}\n\n/** Whether a value can be drained with `for await`. */\nexport function isAsyncIterable(value: unknown): value is AsyncIterableStream {\n return !!value && typeof (value as AsyncIterableStream)[Symbol.asyncIterator] === 'function';\n}\n\nfunction createStreamingState(): StreamingState {\n return {\n responseTexts: [],\n finishReasons: [],\n responseId: '',\n responseModel: '',\n promptTokens: undefined,\n completionTokens: undefined,\n totalTokens: undefined,\n toolCalls: {},\n };\n}\n\nfunction processToolCalls(toolCalls: MistralToolCall[], state: StreamingState): void {\n for (const toolCall of toolCalls) {\n const index = toolCall.index;\n if (index === undefined || !toolCall.function) {\n continue;\n }\n\n const existing = state.toolCalls[index];\n if (!existing) {\n state.toolCalls[index] = {\n ...toolCall,\n function: { name: toolCall.function.name, arguments: toolCall.function.arguments ?? '' },\n };\n } else if (toolCall.function.arguments && existing.function) {\n existing.function.arguments = `${existing.function.arguments}${toolCall.function.arguments}`;\n }\n }\n}\n\nfunction processChunk(chunk: MistralCompletionChunk, 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 // Input tokens stay constant across the stream; output tokens are only finalized in the last\n // event, so we overwrite on every event that carries usage to guarantee the totals are set.\n state.promptTokens = chunk.usage.promptTokens;\n state.completionTokens = chunk.usage.completionTokens;\n state.totalTokens = chunk.usage.totalTokens;\n }\n\n for (const choice of chunk.choices ?? []) {\n if (recordOutputs) {\n // Deltas carry either a plain string or the same content-chunk array the non-streaming\n // responses use, so both go through `contentToString`.\n const content = contentToString(choice.delta?.content);\n if (content) {\n state.responseTexts.push(content);\n }\n if (choice.delta?.toolCalls) {\n processToolCalls(choice.delta.toolCalls, state);\n }\n }\n if (choice.finishReason) {\n state.finishReasons.push(choice.finishReason);\n }\n }\n}\n\n/** Mistral yields `CompletionEvent` objects that wrap the chunk under `data`. */\nfunction processEvent(event: unknown, state: StreamingState, recordOutputs: boolean): void {\n const chunk = (event as { data?: MistralCompletionChunk } | undefined)?.data;\n if (chunk && typeof chunk === 'object') {\n processChunk(chunk, state, recordOutputs);\n }\n}\n\nasync function* instrumentIterator(\n iterate: () => AsyncIterator<unknown>,\n state: StreamingState,\n recordOutputs: boolean,\n claim: (consumer: StreamConsumer) => boolean,\n settle: (error?: unknown) => void,\n): AsyncGenerator<unknown, void, unknown> {\n try {\n for await (const event of { [Symbol.asyncIterator]: iterate }) {\n if (claim('iterator')) {\n processEvent(event, state, recordOutputs);\n }\n yield event;\n }\n } catch (error) {\n settle(error);\n throw error;\n } finally {\n settle();\n }\n}\n\nfunction wrapReader(\n reader: StreamReaderLike,\n state: StreamingState,\n recordOutputs: boolean,\n claim: (consumer: StreamConsumer) => boolean,\n settle: (error?: unknown) => void,\n markCancelled: () => void,\n): StreamReaderLike {\n // Captured before the proxy exists so the wrappers below call the real reader, not themselves.\n const originalRead = reader.read;\n const originalCancel = reader.cancel;\n const read = (): Promise<{ done: boolean; value?: unknown }> => originalRead.call(reader);\n const cancel =\n typeof originalCancel === 'function'\n ? (reason?: unknown): Promise<unknown> => originalCancel.call(reader, reason)\n : undefined;\n\n return new Proxy(reader, {\n get(target: StreamReaderLike, prop: string | symbol): unknown {\n if (prop === 'read') {\n return async (): Promise<{ done: boolean; value?: unknown }> => {\n try {\n const result = await read();\n if (result.done) {\n settle();\n } else if (claim('reader')) {\n processEvent(result.value, state, recordOutputs);\n }\n return result;\n } catch (error) {\n settle(error);\n throw error;\n }\n };\n }\n\n if (prop === 'cancel' && cancel) {\n return async (reason?: unknown): Promise<unknown> => {\n markCancelled();\n try {\n return await cancel(reason);\n } finally {\n settle();\n }\n };\n }\n\n const value = Reflect.get(target, prop, target) as unknown;\n return typeof value === 'function' ? value.bind(target) : value;\n },\n });\n}\n\n/**\n * A stream that pulls through `readable`'s instrumented reader.\n *\n * `tee`, `pipeTo` and `pipeThrough` acquire their reader through internal slots rather than by\n * calling the public `getReader`, so patching that method alone leaves them uninstrumented: the\n * chunks bypass accumulation and the span is never ended. Handing them this stream instead routes\n * them back through the wrapped reader, so there is still exactly one accumulating consumer.\n *\n * Same idea as `monitorStream` in `@sentry/deno`, with two deliberate differences: chunks are pulled\n * on demand rather than drained in a `start` loop, so backpressure still reaches the source, and\n * `cancel` is forwarded (the hole #24054 fixed there) so the source stops producing when the\n * consumer disconnects.\n */\nfunction instrumentedSource(readable: ReadableStreamLike): ReadableStream<unknown> {\n // The patched `getReader`, so reads are accumulated and the span is ended by the shared logic.\n const reader = readable.getReader!();\n\n return new ReadableStream({\n async pull(controller) {\n const { done, value } = await reader.read();\n if (done) {\n controller.close();\n return;\n }\n controller.enqueue(value);\n },\n async cancel(reason) {\n await reader.cancel?.(reason);\n },\n });\n}\n\n/**\n * Instrument a Mistral event stream in place: accumulate response attributes as it is drained and\n * end `span` when it finishes.\n *\n * The stream is patched rather than replaced because `EventStream` extends `ReadableStream`, so\n * handing back a bare async generator would drop `getReader`, `tee`, `pipeTo` and the rest of the\n * `ReadableStream` API the caller is entitled to.\n *\n * Both `for await` and `getReader()` are valid ways to drain a `ReadableStream`, and the SDK's\n * iterator polyfill reads through `getReader()`, so both are wrapped. The first path to see a chunk\n * claims accumulation and the other stays a pass-through, which keeps a chunk from being counted\n * twice when one path drives the other.\n *\n * Returns `false` for a value that is not a stream, leaving it untouched.\n */\nexport function instrumentEventStream(\n stream: unknown,\n span: Span,\n recordOutputs: boolean,\n abortSignal?: AbortSignal,\n beforeSpanEnd?: (result: GenAiSpanResult<never>) => void,\n): boolean {\n if (!isAsyncIterable(stream)) {\n return false;\n }\n\n const state = createStreamingState();\n let consumer: StreamConsumer | undefined;\n let settled = false;\n let cancelled = false;\n\n // Called for each received event.\n const claim = (candidate: StreamConsumer): boolean => {\n recordTimeToFirstChunk(span);\n consumer ??= candidate;\n return consumer === candidate;\n };\n\n // Set synchronously when the caller asks to cancel, before the underlying cancel is awaited.\n // Cancelling can reject an in-flight `read()` (it aborts the HTTP body the stream reads from), and\n // that rejection would otherwise reach `settle` first and record a deliberate abort as a failure.\n const markCancelled = (): void => {\n cancelled = true;\n };\n\n const settle = (error?: unknown): void => {\n if (settled) {\n return;\n }\n settled = true;\n if (error !== undefined && !cancelled) {\n span.setStatus(getErrorStatus(abortSignal));\n }\n\n const toolCalls = Object.values(state.toolCalls);\n\n if (recordOutputs) {\n // Set the authoritative `gen_ai.output.messages` alongside the deprecated response attributes\n // `endStreamSpan` writes, so tool calls survive Relay's lossy migration. A stream is a single\n // assistant turn, so the accumulated fragments make up one message.\n setOutputMessagesAttribute(span, {\n responseText: state.responseTexts.join(''),\n toolCalls,\n finishReason: state.finishReasons[0],\n });\n }\n\n endStreamSpan(span, { ...state, toolCalls }, recordOutputs, () =>\n beforeSpanEnd?.(error !== undefined && !cancelled ? { error } : {}),\n );\n };\n\n const iterate = stream[Symbol.asyncIterator].bind(stream);\n const instrumented = instrumentIterator(iterate, state, recordOutputs, claim, settle);\n stream[Symbol.asyncIterator] = () => instrumented;\n\n const readable = stream as ReadableStreamLike;\n\n if (typeof readable.getReader === 'function') {\n const getReader = readable.getReader.bind(readable);\n readable.getReader = (...args: unknown[]) =>\n wrapReader(getReader(...args), state, recordOutputs, claim, settle, markCancelled);\n }\n\n if (typeof readable.cancel === 'function') {\n const cancel = readable.cancel.bind(readable);\n readable.cancel = async (reason?: unknown): Promise<unknown> => {\n markCancelled();\n try {\n return await cancel(reason);\n } finally {\n settle();\n }\n };\n }\n\n // Only patched when `getReader` is present, since that is what `instrumentedSource` pulls through.\n if (typeof readable.getReader === 'function') {\n if (typeof readable.tee === 'function') {\n readable.tee = () => instrumentedSource(readable).tee();\n }\n\n if (typeof readable.pipeTo === 'function') {\n readable.pipeTo = (destination: unknown, options?: unknown) =>\n instrumentedSource(readable).pipeTo(destination as WritableStream<unknown>, options as StreamPipeOptions);\n }\n\n if (typeof readable.pipeThrough === 'function') {\n readable.pipeThrough = (transform: unknown, options?: unknown) =>\n instrumentedSource(readable).pipeThrough(\n transform as ReadableWritablePair<unknown, unknown>,\n options as StreamPipeOptions,\n );\n }\n }\n\n return true;\n}\n"],"mappings":";;;;;AAyCA,SAAgB,gBAAgB,OAA8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,QAAQ,aAAa;CACrF;CAEA,IAAI,OAAO,SAAS,WAAW,YAAY;EACzC,MAAM,SAAS,SAAS,OAAO,KAAK,QAAQ;EAC5C,SAAS,SAAS,OAAO,WAAuC;GAC9D,cAAc;GACd,IAAI;IACF,OAAO,MAAM,OAAO,MAAM;GAC5B,UAAU;IACR,OAAO;GACT;EACF;CACF;CAGA,IAAI,OAAO,SAAS,cAAc,YAAY;EAC5C,IAAI,OAAO,SAAS,QAAQ,YAC1B,SAAS,YAAY,mBAAmB,QAAQ,CAAC,CAAC,IAAI;EAGxD,IAAI,OAAO,SAAS,WAAW,YAC7B,SAAS,UAAU,aAAsB,YACvC,mBAAmB,QAAQ,CAAC,CAAC,OAAO,aAAwC,OAA4B;EAG5G,IAAI,OAAO,SAAS,gBAAgB,YAClC,SAAS,eAAe,WAAoB,YAC1C,mBAAmB,QAAQ,CAAC,CAAC,YAC3B,WACA,OACF;CAEN;CAEA,OAAO;AACT"}
@@ -1,5 +1,6 @@
1
1
  import { DEBUG_BUILD } from "../../debug-build.js";
2
- import { buildMethodPath, extractSystemInstructions, getErrorStatus, getGenAiSpanOp, getRequestSignal, resolveAIRecordingOptions, wrapPromiseWithMethods } from "../core/utils.js";
2
+ import { buildMethodPath, extractSystemInstructions, getErrorStatus, getGenAiSpanOp, getRequestSignal, resolveGenAiCallRecording, wrapPromiseWithMethods } from "../core/utils.js";
3
+ import { runGenAiSpanEnd, runGenAiSpanStart } from "../core/span-hooks.js";
3
4
  import { OPENAI_METHOD_REGISTRY } from "./constants.js";
4
5
  import { instrumentStream } from "./streaming.js";
5
6
  import { getDecisionInputMessages } from "./mapping.js";
@@ -67,9 +68,14 @@ function addRequestAttributes(span, params, operationName) {
67
68
  function instrumentMethod(originalMethod, methodPath, instrumentedMethod, context, options) {
68
69
  return function instrumentedCall(...args) {
69
70
  const operationName = instrumentedMethod.operation || "unknown";
70
- const requestAttributes = extractRequestAttributes(args, operationName, !!options.recordInputs);
71
- const model = requestAttributes[GEN_AI_REQUEST_MODEL] || "unknown";
72
71
  const params = args[0];
72
+ const call = {
73
+ operation: operationName,
74
+ request: params
75
+ };
76
+ const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);
77
+ const requestAttributes = extractRequestAttributes(args, operationName, recordInputs);
78
+ const model = requestAttributes[GEN_AI_REQUEST_MODEL] || "unknown";
73
79
  const isStreamRequested = params && typeof params === "object" && params.stream === true;
74
80
  const abortSignal = getRequestSignal(args[1]);
75
81
  const client = getClient();
@@ -82,13 +88,15 @@ function instrumentMethod(originalMethod, methodPath, instrumentedMethod, contex
82
88
  let originalResult;
83
89
  const instrumentedPromise = startSpanManual(spanConfig, (span) => {
84
90
  originalResult = originalMethod.apply(context, args);
85
- if (options.recordInputs && params) addRequestAttributes(span, params, operationName);
91
+ if (recordInputs && params) addRequestAttributes(span, params, operationName);
92
+ runGenAiSpanStart(options, span, call);
86
93
  return (async () => {
87
94
  try {
88
95
  const result = await originalResult;
89
- return instrumentStream(result, span, options.recordOutputs ?? false);
96
+ return instrumentStream(result, span, recordOutputs, (streamResult) => runGenAiSpanEnd(options, span, call, streamResult));
90
97
  } catch (error) {
91
98
  span.setStatus(getErrorStatus(abortSignal));
99
+ runGenAiSpanEnd(options, span, call, { error });
92
100
  span.end();
93
101
  throw error;
94
102
  }
@@ -99,12 +107,15 @@ function instrumentMethod(originalMethod, methodPath, instrumentedMethod, contex
99
107
  let originalResult;
100
108
  const instrumentedPromise = startSpan(spanConfig, (span) => {
101
109
  originalResult = originalMethod.apply(context, args);
102
- if (options.recordInputs && params) addRequestAttributes(span, params, operationName);
110
+ if (recordInputs && params) addRequestAttributes(span, params, operationName);
111
+ runGenAiSpanStart(options, span, call);
103
112
  return originalResult.then((result) => {
104
- addResponseAttributes(span, result, options.recordOutputs, operationName);
113
+ addResponseAttributes(span, result, recordOutputs, operationName);
114
+ runGenAiSpanEnd(options, span, call, { response: result });
105
115
  return result;
106
116
  }, (error) => {
107
117
  span.setStatus(getErrorStatus(abortSignal));
118
+ runGenAiSpanEnd(options, span, call, { error });
108
119
  throw error;
109
120
  });
110
121
  });
@@ -157,7 +168,7 @@ function createDeepProxy(target, currentPath = "", options) {
157
168
  * Can be used across Node.js, Cloudflare Workers, and Vercel Edge
158
169
  */
159
170
  function instrumentOpenAiClient(client, options) {
160
- return createDeepProxy(client, "", resolveAIRecordingOptions(options));
171
+ return createDeepProxy(client, "", options ?? {});
161
172
  }
162
173
  export { addRequestAttributes, extractRequestAttributes, instrumentOpenAiClient };
163
174
 
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../../src/ai/openai/index.ts"],"sourcesContent":["/* eslint-disable typescript-eslint/no-deprecated */\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { getClient, hasSpanStreamingEnabled, startSpan, startSpanManual, debug, stringify } from '@sentry/core';\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_TOOL_DEFINITIONS,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport type { InstrumentedMethodEntry } from '../core/utils';\nimport {\n buildMethodPath,\n extractSystemInstructions,\n getErrorStatus,\n getGenAiSpanOp,\n getRequestSignal,\n resolveAIRecordingOptions,\n wrapPromiseWithMethods,\n} from '../core/utils';\nimport { OPENAI_METHOD_REGISTRY } from './constants';\nimport { instrumentStream } from './streaming';\nimport type { ChatCompletionChunk, OpenAiOptions, OpenAIStream, ResponseStreamingEvent } from './types';\nimport { getDecisionInputMessages } from './mapping';\nimport { addResponseAttributes, extractRequestParameters } from './utils';\n\n/**\n * Extract available tools from request parameters\n */\nfunction extractAvailableTools(params: Record<string, unknown>): string | undefined {\n const tools = Array.isArray(params.tools) ? params.tools : [];\n const hasWebSearchOptions = params.web_search_options && typeof params.web_search_options === 'object';\n const webSearchOptions = hasWebSearchOptions\n ? [{ type: 'web_search_options', ...(params.web_search_options as Record<string, unknown>) }]\n : [];\n\n const availableTools = [...tools, ...webSearchOptions];\n if (availableTools.length === 0) {\n return undefined;\n }\n\n try {\n return JSON.stringify(availableTools);\n } catch (error) {\n DEBUG_BUILD && debug.error('Failed to serialize OpenAI tools:', error);\n return undefined;\n }\n}\n\n/**\n * Extract request attributes from method arguments\n */\nexport function extractRequestAttributes(\n args: unknown[],\n operationName: string,\n recordInputs: boolean,\n): Record<string, unknown> {\n const attributes: Record<string, unknown> = {\n [GEN_AI_PROVIDER_NAME]: 'openai',\n [GEN_AI_OPERATION_NAME]: operationName,\n [SENTRY_ORIGIN]: 'auto.ai.openai',\n };\n\n if (args.length > 0 && typeof args[0] === 'object' && args[0] !== null) {\n const params = args[0] as Record<string, unknown>;\n\n if (recordInputs) {\n attributes[GEN_AI_TOOL_DEFINITIONS] = extractAvailableTools(params);\n }\n\n Object.assign(attributes, extractRequestParameters(params));\n\n if (recordInputs && operationName === 'decide') {\n attributes[GEN_AI_INPUT_MESSAGES] = getDecisionInputMessages(params);\n }\n } else {\n attributes[GEN_AI_REQUEST_MODEL] = 'unknown';\n }\n\n return attributes;\n}\n\n// Extract and record AI request inputs, if present. This is intentionally separate from response attributes.\nexport function addRequestAttributes(span: Span, params: Record<string, unknown>, operationName: string): void {\n // A decision's input is recorded when its span starts, in `extractRequestAttributes`.\n if (operationName === 'decide') {\n return;\n }\n\n // Store embeddings input on a separate attribute\n if (operationName === 'embeddings' && 'input' in params) {\n const input = params.input;\n\n // No input provided\n if (input == null) {\n return;\n }\n\n // Empty input string\n if (typeof input === 'string' && input.length === 0) {\n return;\n }\n\n // Empty array input\n if (Array.isArray(input) && input.length === 0) {\n return;\n }\n\n span.setAttribute(GEN_AI_EMBEDDINGS_INPUT, stringify(input, String));\n return;\n }\n\n const src = 'input' in params ? params.input : 'messages' in params ? params.messages : undefined;\n\n if (!src) {\n return;\n }\n\n if (Array.isArray(src) && src.length === 0) {\n return;\n }\n\n const { systemInstructions, filteredMessages } = extractSystemInstructions(src);\n\n if (systemInstructions) {\n span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS, systemInstructions);\n }\n\n span.setAttribute(GEN_AI_INPUT_MESSAGES, stringify(filteredMessages));\n}\n\n/**\n * Instrument a method with Sentry spans\n * Following Sentry AI Agents Manual Instrumentation conventions\n * @see https://docs.sentry.io/platforms/javascript/guides/node/tracing/instrumentation/ai-agents-module/#manual-instrumentation\n */\nfunction instrumentMethod<T extends unknown[], R>(\n originalMethod: (...args: T) => Promise<R>,\n methodPath: string,\n instrumentedMethod: InstrumentedMethodEntry,\n context: unknown,\n options: OpenAiOptions,\n): (...args: T) => Promise<R> {\n return function instrumentedCall(...args: T): Promise<R> {\n const operationName = instrumentedMethod.operation || 'unknown';\n const requestAttributes = extractRequestAttributes(args, operationName, !!options.recordInputs);\n const model = (requestAttributes[GEN_AI_REQUEST_MODEL] as string) || 'unknown';\n\n const params = args[0] as Record<string, unknown> | undefined;\n const isStreamRequested = params && typeof params === 'object' && params.stream === true;\n const abortSignal = getRequestSignal(args[1]);\n const client = getClient();\n\n const spanConfig = {\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name:\n model !== 'unknown' || !(client && hasSpanStreamingEnabled(client))\n ? `${operationName} ${model}`\n : operationName,\n op: getGenAiSpanOp(operationName),\n attributes: requestAttributes as Record<string, SpanAttributeValue>,\n };\n\n if (isStreamRequested) {\n let originalResult!: Promise<R>;\n\n const instrumentedPromise = startSpanManual(spanConfig, (span: Span) => {\n originalResult = originalMethod.apply(context, args);\n\n if (options.recordInputs && params) {\n addRequestAttributes(span, params, operationName);\n }\n\n // Return async processing\n return (async () => {\n try {\n const result = await originalResult;\n return instrumentStream(\n result as OpenAIStream<ChatCompletionChunk | ResponseStreamingEvent>,\n span,\n options.recordOutputs ?? false,\n ) as unknown as R;\n } catch (error) {\n span.setStatus(getErrorStatus(abortSignal));\n span.end();\n throw error;\n }\n })();\n });\n\n return wrapPromiseWithMethods(originalResult, instrumentedPromise);\n }\n\n // Non-streaming\n let originalResult!: Promise<R>;\n\n const instrumentedPromise = startSpan(spanConfig, (span: Span) => {\n // Call synchronously to capture the promise\n originalResult = originalMethod.apply(context, args);\n\n if (options.recordInputs && params) {\n addRequestAttributes(span, params, operationName);\n }\n\n return originalResult.then(\n result => {\n addResponseAttributes(span, result, options.recordOutputs, operationName);\n return result;\n },\n error => {\n span.setStatus(getErrorStatus(abortSignal));\n throw error;\n },\n );\n });\n\n return wrapPromiseWithMethods(originalResult, instrumentedPromise);\n };\n}\n\n/**\n * Create a deep proxy for OpenAI client instrumentation\n */\nfunction createDeepProxy<T extends object>(target: T, currentPath = '', options: OpenAiOptions): T {\n const propertyCache = new Map<PropertyKey, { original: unknown; wrapped: unknown }>();\n\n return new Proxy(target, {\n get(obj: object, prop: string | symbol): unknown {\n const value = Reflect.get(obj, prop) as unknown;\n const cachedEntry = propertyCache.get(prop);\n if (cachedEntry) {\n if (cachedEntry.original === value) {\n return cachedEntry.wrapped;\n }\n propertyCache.delete(prop);\n }\n\n const methodPath = buildMethodPath(currentPath, String(prop));\n\n const instrumentedMethod = OPENAI_METHOD_REGISTRY[methodPath as keyof typeof OPENAI_METHOD_REGISTRY];\n if (typeof value === 'function' && instrumentedMethod) {\n const wrappedMethod = instrumentMethod(\n value as (...args: unknown[]) => Promise<unknown>,\n methodPath,\n instrumentedMethod,\n obj,\n options,\n );\n propertyCache.set(prop, { original: value, wrapped: wrappedMethod });\n return wrappedMethod;\n }\n\n if (typeof value === 'function') {\n // Bind non-instrumented functions to preserve the original `this` context,\n // which is required for accessing private class fields (e.g. #baseURL) in OpenAI SDK v5.\n const boundMethod = value.bind(obj);\n propertyCache.set(prop, { original: value, wrapped: boundMethod });\n return boundMethod;\n }\n\n if (value && typeof value === 'object') {\n const nestedProxy = createDeepProxy(value, methodPath, options);\n propertyCache.set(prop, { original: value, wrapped: nestedProxy });\n return nestedProxy;\n }\n\n return value;\n },\n }) as T;\n}\n\n/**\n * Instrument an OpenAI client with Sentry tracing\n * Can be used across Node.js, Cloudflare Workers, and Vercel Edge\n */\nexport function instrumentOpenAiClient<T extends object>(client: T, options?: OpenAiOptions): T {\n return createDeepProxy(client, '', resolveAIRecordingOptions(options));\n}\n"],"mappings":";;;;;;;;;;;;AAiCA,SAAS,sBAAsB,QAAqD;CAClF,MAAM,QAAQ,MAAM,QAAQ,OAAO,KAAK,IAAI,OAAO,QAAQ,CAAC;CAE5D,MAAM,mBADsB,OAAO,sBAAsB,OAAO,OAAO,uBAAuB,WAE1F,CAAC;EAAE,MAAM;EAAsB,GAAI,OAAO;CAA+C,CAAC,IAC1F,CAAC;CAEL,MAAM,iBAAiB,CAAC,GAAG,OAAO,GAAG,gBAAgB;CACrD,IAAI,eAAe,WAAW,GAC5B;CAGF,IAAI;EACF,OAAO,KAAK,UAAU,cAAc;CACtC,SAAS,OAAO;EACd,eAAe,MAAM,MAAM,qCAAqC,KAAK;EACrE;CACF;AACF;;;;AAKA,SAAgB,yBACd,MACA,eACA,cACyB;CACzB,MAAM,aAAsC;GACzC,uBAAuB;GACvB,wBAAwB;GACxB,gBAAgB;CACnB;CAEA,IAAI,KAAK,SAAS,KAAK,OAAO,KAAK,OAAO,YAAY,KAAK,OAAO,MAAM;EACtE,MAAM,SAAS,KAAK;EAEpB,IAAI,cACF,WAAW,2BAA2B,sBAAsB,MAAM;EAGpE,OAAO,OAAO,YAAY,yBAAyB,MAAM,CAAC;EAE1D,IAAI,gBAAgB,kBAAkB,UACpC,WAAW,yBAAyB,yBAAyB,MAAM;CAEvE,OACE,WAAW,wBAAwB;CAGrC,OAAO;AACT;AAGA,SAAgB,qBAAqB,MAAY,QAAiC,eAA6B;CAE7G,IAAI,kBAAkB,UACpB;CAIF,IAAI,kBAAkB,gBAAgB,WAAW,QAAQ;EACvD,MAAM,QAAQ,OAAO;EAGrB,IAAI,SAAS,MACX;EAIF,IA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SAAS;GAAY,CAAC;GACjE,OAAO;EACT;EAEA,IAAI,SAAS,OAAO,UAAU,UAAU;GACtC,MAAM,cAAc,gBAAgB,OAAO,YAAY,OAAO;GAC9D,cAAc,IAAI,MAAM;IAAE,UAAU;IAAO,SAAS;GAAY,CAAC;GACjE,OAAO;EACT;EAEA,OAAO;CACT,EACF,CAAC;AACH;;;;;AAMA,SAAgB,uBAAyC,QAAW,SAA4B;CAC9F,OAAO,gBAAgB,QAAQ,IAAI,0BAA0B,OAAO,CAAC;AACvE"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../../src/ai/openai/index.ts"],"sourcesContent":["/* eslint-disable typescript-eslint/no-deprecated */\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { getClient, hasSpanStreamingEnabled, startSpan, startSpanManual, debug, stringify } from '@sentry/core';\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_TOOL_DEFINITIONS,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport type { InstrumentedMethodEntry } from '../core/utils';\nimport {\n buildMethodPath,\n extractSystemInstructions,\n getErrorStatus,\n getGenAiSpanOp,\n getRequestSignal,\n resolveGenAiCallRecording,\n wrapPromiseWithMethods,\n} from '../core/utils';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport { OPENAI_METHOD_REGISTRY } from './constants';\nimport { instrumentStream } from './streaming';\nimport type { ChatCompletionChunk, OpenAiCallInfo, OpenAiOptions, OpenAIStream, ResponseStreamingEvent } from './types';\nimport { getDecisionInputMessages } from './mapping';\nimport { addResponseAttributes, extractRequestParameters } from './utils';\n\n/**\n * Extract available tools from request parameters\n */\nfunction extractAvailableTools(params: Record<string, unknown>): string | undefined {\n const tools = Array.isArray(params.tools) ? params.tools : [];\n const hasWebSearchOptions = params.web_search_options && typeof params.web_search_options === 'object';\n const webSearchOptions = hasWebSearchOptions\n ? [{ type: 'web_search_options', ...(params.web_search_options as Record<string, unknown>) }]\n : [];\n\n const availableTools = [...tools, ...webSearchOptions];\n if (availableTools.length === 0) {\n return undefined;\n }\n\n try {\n return JSON.stringify(availableTools);\n } catch (error) {\n DEBUG_BUILD && debug.error('Failed to serialize OpenAI tools:', error);\n return undefined;\n }\n}\n\n/**\n * Extract request attributes from method arguments\n */\nexport function extractRequestAttributes(\n args: unknown[],\n operationName: string,\n recordInputs: boolean,\n): Record<string, unknown> {\n const attributes: Record<string, unknown> = {\n [GEN_AI_PROVIDER_NAME]: 'openai',\n [GEN_AI_OPERATION_NAME]: operationName,\n [SENTRY_ORIGIN]: 'auto.ai.openai',\n };\n\n if (args.length > 0 && typeof args[0] === 'object' && args[0] !== null) {\n const params = args[0] as Record<string, unknown>;\n\n if (recordInputs) {\n attributes[GEN_AI_TOOL_DEFINITIONS] = extractAvailableTools(params);\n }\n\n Object.assign(attributes, extractRequestParameters(params));\n\n if (recordInputs && operationName === 'decide') {\n attributes[GEN_AI_INPUT_MESSAGES] = getDecisionInputMessages(params);\n }\n } else {\n attributes[GEN_AI_REQUEST_MODEL] = 'unknown';\n }\n\n return attributes;\n}\n\n// Extract and record AI request inputs, if present. This is intentionally separate from response attributes.\nexport function addRequestAttributes(span: Span, params: Record<string, unknown>, operationName: string): void {\n // A decision's input is recorded when its span starts, in `extractRequestAttributes`.\n if (operationName === 'decide') {\n return;\n }\n\n // Store embeddings input on a separate attribute\n if (operationName === 'embeddings' && 'input' in params) {\n const input = params.input;\n\n // No input provided\n if (input == null) {\n return;\n }\n\n // Empty input string\n if (typeof input === 'string' && input.length === 0) {\n return;\n }\n\n // Empty array input\n if (Array.isArray(input) && input.length === 0) {\n return;\n }\n\n span.setAttribute(GEN_AI_EMBEDDINGS_INPUT, stringify(input, String));\n return;\n }\n\n const src = 'input' in params ? params.input : 'messages' in params ? params.messages : undefined;\n\n if (!src) {\n return;\n }\n\n if (Array.isArray(src) && src.length === 0) {\n return;\n }\n\n const { systemInstructions, filteredMessages } = extractSystemInstructions(src);\n\n if (systemInstructions) {\n span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS, systemInstructions);\n }\n\n span.setAttribute(GEN_AI_INPUT_MESSAGES, stringify(filteredMessages));\n}\n\n/**\n * Instrument a method with Sentry spans\n * Following Sentry AI Agents Manual Instrumentation conventions\n * @see https://docs.sentry.io/platforms/javascript/guides/node/tracing/instrumentation/ai-agents-module/#manual-instrumentation\n */\nfunction instrumentMethod<T extends unknown[], R>(\n originalMethod: (...args: T) => Promise<R>,\n methodPath: string,\n instrumentedMethod: InstrumentedMethodEntry,\n context: unknown,\n options: OpenAiOptions,\n): (...args: T) => Promise<R> {\n return function instrumentedCall(...args: T): Promise<R> {\n const operationName = instrumentedMethod.operation || 'unknown';\n const params = args[0] as Record<string, unknown> | undefined;\n const call: OpenAiCallInfo = { operation: operationName, request: params };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n const requestAttributes = extractRequestAttributes(args, operationName, recordInputs);\n const model = (requestAttributes[GEN_AI_REQUEST_MODEL] as string) || 'unknown';\n\n const isStreamRequested = params && typeof params === 'object' && params.stream === true;\n const abortSignal = getRequestSignal(args[1]);\n const client = getClient();\n\n const spanConfig = {\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name:\n model !== 'unknown' || !(client && hasSpanStreamingEnabled(client))\n ? `${operationName} ${model}`\n : operationName,\n op: getGenAiSpanOp(operationName),\n attributes: requestAttributes as Record<string, SpanAttributeValue>,\n };\n\n if (isStreamRequested) {\n let originalResult!: Promise<R>;\n\n const instrumentedPromise = startSpanManual(spanConfig, (span: Span) => {\n originalResult = originalMethod.apply(context, args);\n\n if (recordInputs && params) {\n addRequestAttributes(span, params, operationName);\n }\n runGenAiSpanStart(options, span, call);\n\n // Return async processing\n return (async () => {\n try {\n const result = await originalResult;\n return instrumentStream(\n result as OpenAIStream<ChatCompletionChunk | ResponseStreamingEvent>,\n span,\n recordOutputs,\n streamResult => runGenAiSpanEnd(options, span, call, streamResult),\n ) as unknown as R;\n } catch (error) {\n span.setStatus(getErrorStatus(abortSignal));\n runGenAiSpanEnd(options, span, call, { error });\n span.end();\n throw error;\n }\n })();\n });\n\n return wrapPromiseWithMethods(originalResult, instrumentedPromise);\n }\n\n // Non-streaming\n let originalResult!: Promise<R>;\n\n const instrumentedPromise = startSpan(spanConfig, (span: Span) => {\n // Call synchronously to capture the promise\n originalResult = originalMethod.apply(context, args);\n\n if (recordInputs && params) {\n addRequestAttributes(span, params, operationName);\n }\n runGenAiSpanStart(options, span, call);\n\n return originalResult.then(\n result => {\n addResponseAttributes(span, result, recordOutputs, operationName);\n runGenAiSpanEnd(options, span, call, { response: result });\n return result;\n },\n error => {\n span.setStatus(getErrorStatus(abortSignal));\n runGenAiSpanEnd(options, span, call, { error });\n throw error;\n },\n );\n });\n\n return wrapPromiseWithMethods(originalResult, instrumentedPromise);\n };\n}\n\n/**\n * Create a deep proxy for OpenAI client instrumentation\n */\nfunction createDeepProxy<T extends object>(target: T, currentPath = '', options: OpenAiOptions): T {\n const propertyCache = new Map<PropertyKey, { original: unknown; wrapped: unknown }>();\n\n return new Proxy(target, {\n get(obj: object, prop: string | symbol): unknown {\n const value = Reflect.get(obj, prop) as unknown;\n const cachedEntry = propertyCache.get(prop);\n if (cachedEntry) {\n if (cachedEntry.original === value) {\n return cachedEntry.wrapped;\n }\n propertyCache.delete(prop);\n }\n\n const methodPath = buildMethodPath(currentPath, String(prop));\n\n const instrumentedMethod = OPENAI_METHOD_REGISTRY[methodPath as keyof typeof OPENAI_METHOD_REGISTRY];\n if (typeof value === 'function' && instrumentedMethod) {\n const wrappedMethod = instrumentMethod(\n value as (...args: unknown[]) => Promise<unknown>,\n methodPath,\n instrumentedMethod,\n obj,\n options,\n );\n propertyCache.set(prop, { original: value, wrapped: wrappedMethod });\n return wrappedMethod;\n }\n\n if (typeof value === 'function') {\n // Bind non-instrumented functions to preserve the original `this` context,\n // which is required for accessing private class fields (e.g. #baseURL) in OpenAI SDK v5.\n const boundMethod = value.bind(obj);\n propertyCache.set(prop, { original: value, wrapped: boundMethod });\n return boundMethod;\n }\n\n if (value && typeof value === 'object') {\n const nestedProxy = createDeepProxy(value, methodPath, options);\n propertyCache.set(prop, { original: value, wrapped: nestedProxy });\n return nestedProxy;\n }\n\n return value;\n },\n }) as T;\n}\n\n/**\n * Instrument an OpenAI client with Sentry tracing\n * Can be used across Node.js, Cloudflare Workers, and Vercel Edge\n */\nexport function instrumentOpenAiClient<T extends object>(client: T, options?: OpenAiOptions): T {\n return createDeepProxy(client, '', options ?? {});\n}\n"],"mappings":";;;;;;;;;;;;;AAkCA,SAAS,sBAAsB,QAAqD;CAClF,MAAM,QAAQ,MAAM,QAAQ,OAAO,KAAK,IAAI,OAAO,QAAQ,CAAC;CAE5D,MAAM,mBADsB,OAAO,sBAAsB,OAAO,OAAO,uBAAuB,WAE1F,CAAC;EAAE,MAAM;EAAsB,GAAI,OAAO;CAA+C,CAAC,IAC1F,CAAC;CAEL,MAAM,iBAAiB,CAAC,GAAG,OAAO,GAAG,gBAAgB;CACrD,IAAI,eAAe,WAAW,GAC5B;CAGF,IAAI;EACF,OAAO,KAAK,UAAU,cAAc;CACtC,SAAS,OAAO;EACd,eAAe,MAAM,MAAM,qCAAqC,KAAK;EACrE;CACF;AACF;;;;AAKA,SAAgB,yBACd,MACA,eACA,cACyB;CACzB,MAAM,aAAsC;GACzC,uBAAuB;GACvB,wBAAwB;GACxB,gBAAgB;CACnB;CAEA,IAAI,KAAK,SAAS,KAAK,OAAO,KAAK,OAAO,YAAY,KAAK,OAAO,MAAM;EACtE,MAAM,SAAS,KAAK;EAEpB,IAAI,cACF,WAAW,2BAA2B,sBAAsB,MAAM;EAGpE,OAAO,OAAO,YAAY,yBAAyB,MAAM,CAAC;EAE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AEpF,OAAO,IAAI,MAAM,QAAQ,EACvB,IAAI,KAAa,MAAgC;EAC/C,MAAM,QAAQ,QAAQ,IAAI,KAAK,IAAI;EACnC,MAAM,cAAc,cAAc,IAAI,IAAI;EAC1C,IAAI,aAAa;GACf,IAAI,YAAY,aAAa,OAC3B,OAAO,YAAY;GAErB,cAAc,OAAO,IAAI;EAC3B;EAEA,MAAM,aAAa,gBAAgB,aAAa,OAAO,IAAI,CAAC;EAE5D,MAAM,qBAAqB,uBAAuB;EAClD,IAAI,OAAO,UAAU,cAAc,oBAAoB;GACrD,MAAM,gBAAgB,iBACpB,OACA,YACA,oBACA,KACA,OACF;GACA,cAAc,IAAI,MAAM;IAAE,UAAU;IAAO,SAAS;GAAc,CAAC;GACnE,OAAO;EACT;EAEA,IAAI,OAAO,UAAU,YAAY;GAG/B,MAAM,cAAc,MAAM,KAAK,GAAG;GAClC,cAAc,IAAI,MAAM;IAAE,UAAU;IAAO,SAAS;GAAY,CAAC;GACjE,OAAO;EACT;EAEA,IAAI,SAAS,OAAO,UAAU,UAAU;GACtC,MAAM,cAAc,gBAAgB,OAAO,YAAY,OAAO;GAC9D,cAAc,IAAI,MAAM;IAAE,UAAU;IAAO,SAAS;GAAY,CAAC;GACjE,OAAO;EACT;EAEA,OAAO;CACT,EACF,CAAC;AACH;;;;;AAMA,SAAgB,uBAAyC,QAAW,SAA4B;CAC9F,OAAO,gBAAgB,QAAQ,IAAI,WAAW,CAAC,CAAC;AAClD"}
@@ -1,5 +1,6 @@
1
1
  import { getToolCallKey } from "../core/streaming-tool-calls.js";
2
2
  import { endStreamSpan } from "../core/utils.js";
3
+ import { recordTimeToFirstChunk } from "../core/time-to-first-chunk.js";
3
4
  import { RESPONSE_EVENT_TYPES } from "./constants.js";
4
5
  import { isChatCompletionChunk, isResponsesApiStreamEvent } from "./utils.js";
5
6
  import { SPAN_STATUS_ERROR, captureException } from "@sentry/core";
@@ -118,9 +119,10 @@ function processResponsesApiEvent(streamEvent, state, recordOutputs, span) {
118
119
  * @param stream - The async iterable stream of events to instrument.
119
120
  * @param span - The span to add attributes to and to finish at the end of the stream.
120
121
  * @param recordOutputs - Whether to record output text fragments in the span.
122
+ * @param beforeSpanEnd - Runs right before the span ends, with the error when the stream failed.
121
123
  * @returns An async generator yielding each event from the input stream.
122
124
  */
123
- async function* instrumentStream(stream, span, recordOutputs) {
125
+ async function* instrumentStream(stream, span, recordOutputs, beforeSpanEnd) {
124
126
  const state = {
125
127
  eventTypes: [],
126
128
  responseTexts: [],
@@ -135,8 +137,10 @@ async function* instrumentStream(stream, span, recordOutputs) {
135
137
  chatCompletionToolCalls: /* @__PURE__ */ new Map(),
136
138
  responsesApiToolCalls: []
137
139
  };
140
+ const result = {};
138
141
  try {
139
142
  for await (const event of stream) {
143
+ recordTimeToFirstChunk(span);
140
144
  if (isChatCompletionChunk(event)) processChatCompletionChunk(event, state, recordOutputs);
141
145
  else if (isResponsesApiStreamEvent(event)) processResponsesApiEvent(event, state, recordOutputs, span);
142
146
  yield event;
@@ -146,13 +150,14 @@ async function* instrumentStream(stream, span, recordOutputs) {
146
150
  code: SPAN_STATUS_ERROR,
147
151
  message: "internal_error"
148
152
  });
153
+ result.error = error;
149
154
  throw error;
150
155
  } finally {
151
156
  const allToolCalls = [...state.chatCompletionToolCalls.values(), ...state.responsesApiToolCalls];
152
157
  endStreamSpan(span, {
153
158
  ...state,
154
159
  toolCalls: allToolCalls
155
- }, recordOutputs);
160
+ }, recordOutputs, () => beforeSpanEnd?.(result));
156
161
  }
157
162
  }
158
163
  export { instrumentStream };
@@ -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,G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KAAK,UAAU;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,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iBAAiB,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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M,QAAQ,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,YA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B,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;;;;;;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;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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 { 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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