@sentry/server-utils 11.16.0 → 11.18.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 (172) hide show
  1. package/build/cjs/chunks/config.js +62 -2
  2. package/build/cjs/chunks/config.js.map +1 -1
  3. package/build/cjs/chunks/exports.js +231 -66
  4. package/build/cjs/chunks/exports.js.map +1 -1
  5. package/build/cjs/chunks/moduleInjectedTransform.js +8 -0
  6. package/build/cjs/chunks/moduleInjectedTransform.js.map +1 -1
  7. package/build/cjs/index.js +447 -199
  8. package/build/cjs/index.js.map +1 -1
  9. package/build/cjs/index.no-diagnostic-channels.js +1 -0
  10. package/build/cjs/index.request-handler.js +48 -3
  11. package/build/cjs/index.request-handler.js.map +1 -1
  12. package/build/esm/ai/langchain/embeddings.js +23 -8
  13. package/build/esm/ai/langchain/embeddings.js.map +1 -1
  14. package/build/esm/ai/langchain/index.js +41 -30
  15. package/build/esm/ai/langchain/index.js.map +1 -1
  16. package/build/esm/ai/langchain/utils.js +1 -5
  17. package/build/esm/ai/langchain/utils.js.map +1 -1
  18. package/build/esm/ai/langgraph/agent-span.js +6 -2
  19. package/build/esm/ai/langgraph/agent-span.js.map +1 -1
  20. package/build/esm/ai/langgraph/index.js +5 -1
  21. package/build/esm/ai/langgraph/index.js.map +1 -1
  22. package/build/esm/ai/langgraph/stream.js +4 -1
  23. package/build/esm/ai/langgraph/stream.js.map +1 -1
  24. package/build/esm/ai/mistral/streaming.js.map +1 -1
  25. package/build/esm/ai/pi-durable/index.js +10 -13
  26. package/build/esm/ai/pi-durable/index.js.map +1 -1
  27. package/build/esm/ai/pi-durable/runs.js +6 -5
  28. package/build/esm/ai/pi-durable/runs.js.map +1 -1
  29. package/build/esm/ai/pi-durable/tools.js +21 -17
  30. package/build/esm/ai/pi-durable/tools.js.map +1 -1
  31. package/build/esm/exports.js +2 -1
  32. package/build/esm/index.js +5 -2
  33. package/build/esm/index.js.map +1 -1
  34. package/build/esm/index.no-diagnostic-channels.js +2 -1
  35. package/build/esm/index.request-handler.js +3 -1
  36. package/build/esm/integrations/amqplib.js.map +1 -1
  37. package/build/esm/integrations/anthropic.js.map +1 -1
  38. package/build/esm/integrations/bullmq/tracer.js.map +1 -1
  39. package/build/esm/integrations/clickhouse-sql.js +31 -0
  40. package/build/esm/integrations/clickhouse-sql.js.map +1 -0
  41. package/build/esm/integrations/clickhouse.js +88 -0
  42. package/build/esm/integrations/clickhouse.js.map +1 -0
  43. package/build/esm/integrations/express/instrumentation.js +1 -0
  44. package/build/esm/integrations/express/instrumentation.js.map +1 -1
  45. package/build/esm/integrations/fastify/instrumentation.js +3 -1
  46. package/build/esm/integrations/fastify/instrumentation.js.map +1 -1
  47. package/build/esm/integrations/graphql/utils.js.map +1 -1
  48. package/build/esm/integrations/hapi/hapi-utils.js +6 -9
  49. package/build/esm/integrations/hapi/hapi-utils.js.map +1 -1
  50. package/build/esm/integrations/hapi/index.js +15 -1
  51. package/build/esm/integrations/hapi/index.js.map +1 -1
  52. package/build/esm/integrations/hono/isMiddleware.js.map +1 -1
  53. package/build/esm/integrations/hono/middlewareHandlers.js +3 -1
  54. package/build/esm/integrations/hono/middlewareHandlers.js.map +1 -1
  55. package/build/esm/integrations/hono/patchRoute.js +2 -1
  56. package/build/esm/integrations/hono/patchRoute.js.map +1 -1
  57. package/build/esm/integrations/hono/unwrapThrownValue.js +20 -0
  58. package/build/esm/integrations/hono/unwrapThrownValue.js.map +1 -0
  59. package/build/esm/integrations/index.js +2 -0
  60. package/build/esm/integrations/index.js.map +1 -1
  61. package/build/esm/integrations/langchain.js +10 -3
  62. package/build/esm/integrations/langchain.js.map +1 -1
  63. package/build/esm/integrations/mongodb/mongodb-span.js +7 -9
  64. package/build/esm/integrations/mongodb/mongodb-span.js.map +1 -1
  65. package/build/esm/integrations/pino.js +2 -2
  66. package/build/esm/integrations/pino.js.map +1 -1
  67. package/build/esm/integrations/prisma/tracing-helper.js.map +1 -1
  68. package/build/esm/integrations/serveTunnel.js +2 -2
  69. package/build/esm/integrations/serveTunnel.js.map +1 -1
  70. package/build/esm/integrations/vercel-ai/extract.js +88 -0
  71. package/build/esm/integrations/vercel-ai/extract.js.map +1 -0
  72. package/build/esm/integrations/vercel-ai/util.js +5 -1
  73. package/build/esm/integrations/vercel-ai/util.js.map +1 -1
  74. package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js +19 -9
  75. package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -1
  76. package/build/esm/integrations/winston.js +2 -2
  77. package/build/esm/integrations/winston.js.map +1 -1
  78. package/build/esm/orchestrion/channels.js +2 -0
  79. package/build/esm/orchestrion/channels.js.map +1 -1
  80. package/build/esm/orchestrion/config/channel-integration-definitions.js +8 -0
  81. package/build/esm/orchestrion/config/channel-integration-definitions.js.map +1 -1
  82. package/build/esm/orchestrion/config/clickhouse.js +51 -0
  83. package/build/esm/orchestrion/config/clickhouse.js.map +1 -0
  84. package/build/esm/orchestrion/config/hono.js +2 -2
  85. package/build/esm/orchestrion/config/hono.js.map +1 -1
  86. package/build/esm/orchestrion/config/index.js +2 -0
  87. package/build/esm/orchestrion/config/index.js.map +1 -1
  88. package/build/esm/package.json +1 -1
  89. package/build/esm/utils/installedModules.js +87 -0
  90. package/build/esm/utils/installedModules.js.map +1 -0
  91. package/build/esm/utils/module.js +29 -0
  92. package/build/esm/utils/module.js.map +1 -0
  93. package/build/esm/utils/serverTimingTraceHeader.js +49 -0
  94. package/build/esm/utils/serverTimingTraceHeader.js.map +1 -0
  95. package/build/esm/utils/sql.js +41 -19
  96. package/build/esm/utils/sql.js.map +1 -1
  97. package/build/esm/utils/tunnelServer.js +3 -3
  98. package/build/esm/utils/tunnelServer.js.map +1 -1
  99. package/build/esm/utils/wrapServerRequestHandler.js +5 -4
  100. package/build/esm/utils/wrapServerRequestHandler.js.map +1 -1
  101. package/build/types/ai/langchain/embeddings.d.ts +2 -2
  102. package/build/types/ai/langchain/embeddings.d.ts.map +1 -1
  103. package/build/types/ai/langchain/index.d.ts.map +1 -1
  104. package/build/types/ai/langchain/types.d.ts +8 -4
  105. package/build/types/ai/langchain/types.d.ts.map +1 -1
  106. package/build/types/ai/langchain/utils.d.ts.map +1 -1
  107. package/build/types/ai/langgraph/agent-span.d.ts +5 -2
  108. package/build/types/ai/langgraph/agent-span.d.ts.map +1 -1
  109. package/build/types/ai/langgraph/index.d.ts.map +1 -1
  110. package/build/types/ai/langgraph/stream.d.ts.map +1 -1
  111. package/build/types/ai/langgraph/types.d.ts +10 -2
  112. package/build/types/ai/langgraph/types.d.ts.map +1 -1
  113. package/build/types/ai/mistral/streaming.d.ts.map +1 -1
  114. package/build/types/ai/pi-durable/index.d.ts.map +1 -1
  115. package/build/types/ai/pi-durable/runs.d.ts +4 -2
  116. package/build/types/ai/pi-durable/runs.d.ts.map +1 -1
  117. package/build/types/ai/pi-durable/tools.d.ts +4 -6
  118. package/build/types/ai/pi-durable/tools.d.ts.map +1 -1
  119. package/build/types/ai/pi-durable/types.d.ts +10 -1
  120. package/build/types/ai/pi-durable/types.d.ts.map +1 -1
  121. package/build/types/exports.d.ts +1 -0
  122. package/build/types/exports.d.ts.map +1 -1
  123. package/build/types/index.d.ts +5 -3
  124. package/build/types/index.d.ts.map +1 -1
  125. package/build/types/index.request-handler.d.ts +1 -0
  126. package/build/types/index.request-handler.d.ts.map +1 -1
  127. package/build/types/integrations/amqplib.d.ts.map +1 -1
  128. package/build/types/integrations/anthropic.d.ts.map +1 -1
  129. package/build/types/integrations/bullmq/tracer.d.ts.map +1 -1
  130. package/build/types/integrations/clickhouse-sql.d.ts +8 -0
  131. package/build/types/integrations/clickhouse-sql.d.ts.map +1 -0
  132. package/build/types/integrations/clickhouse.d.ts +11 -0
  133. package/build/types/integrations/clickhouse.d.ts.map +1 -0
  134. package/build/types/integrations/express/types.d.ts +1 -0
  135. package/build/types/integrations/express/types.d.ts.map +1 -1
  136. package/build/types/integrations/fastify/instrumentation.d.ts.map +1 -1
  137. package/build/types/integrations/hapi/hapi-utils.d.ts.map +1 -1
  138. package/build/types/integrations/hapi/index.d.ts +12 -0
  139. package/build/types/integrations/hapi/index.d.ts.map +1 -1
  140. package/build/types/integrations/hono/isMiddleware.d.ts.map +1 -1
  141. package/build/types/integrations/hono/middlewareHandlers.d.ts.map +1 -1
  142. package/build/types/integrations/hono/patchRoute.d.ts.map +1 -1
  143. package/build/types/integrations/hono/unwrapThrownValue.d.ts +10 -0
  144. package/build/types/integrations/hono/unwrapThrownValue.d.ts.map +1 -0
  145. package/build/types/integrations/index.d.ts.map +1 -1
  146. package/build/types/integrations/langchain.d.ts.map +1 -1
  147. package/build/types/integrations/mongodb/mongodb-span.d.ts.map +1 -1
  148. package/build/types/integrations/prisma/tracing-helper.d.ts.map +1 -1
  149. package/build/types/integrations/vercel-ai/extract.d.ts +27 -0
  150. package/build/types/integrations/vercel-ai/extract.d.ts.map +1 -0
  151. package/build/types/integrations/vercel-ai/util.d.ts +2 -0
  152. package/build/types/integrations/vercel-ai/util.d.ts.map +1 -1
  153. package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts +1 -1
  154. package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts.map +1 -1
  155. package/build/types/orchestrion/channels.d.ts +12 -0
  156. package/build/types/orchestrion/channels.d.ts.map +1 -1
  157. package/build/types/orchestrion/config/channel-integration-definitions.d.ts +3 -0
  158. package/build/types/orchestrion/config/channel-integration-definitions.d.ts.map +1 -1
  159. package/build/types/orchestrion/config/clickhouse.d.ts +18 -0
  160. package/build/types/orchestrion/config/clickhouse.d.ts.map +1 -0
  161. package/build/types/orchestrion/config/index.d.ts.map +1 -1
  162. package/build/types/utils/installedModules.d.ts +17 -0
  163. package/build/types/utils/installedModules.d.ts.map +1 -0
  164. package/build/types/utils/module.d.ts +3 -0
  165. package/build/types/utils/module.d.ts.map +1 -0
  166. package/build/types/utils/serverTimingTraceHeader.d.ts +18 -0
  167. package/build/types/utils/serverTimingTraceHeader.d.ts.map +1 -0
  168. package/build/types/utils/sql.d.ts +28 -3
  169. package/build/types/utils/sql.d.ts.map +1 -1
  170. package/build/types/utils/tunnelServer.d.ts.map +1 -1
  171. package/build/types/utils/wrapServerRequestHandler.d.ts.map +1 -1
  172. package/package.json +4 -4
@@ -1 +1 @@
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,OAA8C;CAC5E,OAAO,CAAC,CAAC,SAAS,OAAQ,MAA8B,OAAO,mBAAmB;AACpF;AAEA,SAAS,uBAAuC;CAC9C,OAAO;EACL,e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AAS,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
+ {"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 // oxlint-disable-next-line typescript/no-non-null-assertion -- only called when `getReader` is a function\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,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,KAAA;EAClB,aAAa,KAAA;EACb,WAAW,CAAC;CACd;AACF;AAEA,SAAS,iBAAiB,WAA8B,OAA6B;CACnF,KAAK,MAAM,YAAY,WAAW;EAChC,MAAM,QAAQ,SAAS;EACvB,IAAI,UAAU,KAAA,KAAa,CAAC,SAAS,UACnC;EAGF,MAAM,WAAW,MAAM,UAAU;EACjC,IAAI,CAAC,UACH,MAAM,UAAU,SAAS;GACvB,GAAG;GACH,UAAU;IAAE,MAAM,SAAS,SAAS;IAAM,WAAW,SAAS,SAAS,aAAa;GAAG;EACzF;OACK,IAAI,SAAS,SAAS,aAAa,SAAS,UACjD,SAAS,SAAS,YAAY,GAAG,SAAS,SAAS,YAAY,SAAS,SAAS;CAErF;AACF;AAEA,SAAS,aAAa,OAA+B,OAAuB,eAA8B;CACxG,MAAM,aAAa,MAAM,MAAM,MAAM;CACrC,MAAM,gBAAgB,MAAM,SAAS,MAAM;CAE3C,IAAI,MAAM,OAAO;EAGf,MAAM,eAAe,MAAM,MAAM;EACjC,MAAM,mBAAmB,MAAM,MAAM;EACrC,MAAM,cAAc,MAAM,MAAM;CAClC;CAEA,KAAK,MAAM,UAAU,MAAM,WAAW,CAAC,GAAG;EACxC,IAAI,eAAe;GAGjB,MAAM,UAAU,gBAAgB,OAAO,OAAO,OAAO;G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,GAAG,OAAO,eAAe,OAAO,MAAM;CACpF,OAAO,OAAO,uBAAuB;CAErC,MAAM,WAAW;CAEjB,IAAI,OAAO,SAAS,cAAc,YAAY;EAC5C,MAAM,YAAY,SAAS,UAAU,KAAK,QAAQ;EAClD,SAAS,aAAa,GAAG,SACvB,WAAW,UAAU,GAAG,IAAI,GAAG,OAAO,eAAe,OAAO,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"}
@@ -92,7 +92,7 @@ function instrumentRegistry(registry, options, runs) {
92
92
  let wrapped = tasks.get(task);
93
93
  if (!wrapped) {
94
94
  const { definition } = task;
95
- const wrapPhase = (phase, receiver, isAbort = false) => (taskRecord, runtime, context) => runPhase(definition.name, (observed) => phase.call(receiver, taskRecord, observed, context), runtime, context, runs, wrapTool, isAbort, options);
95
+ const wrapPhase = (phase, receiver, isAbort = false) => (taskRecord, runtime, context) => runPhase(definition.name, taskRecord, () => phase.call(receiver, taskRecord, runtime, context), runtime, context, runs, wrapTool, isAbort, options);
96
96
  const phases = {};
97
97
  for (const [name, phase] of Object.entries(definition.phases)) phases[name] = typeof phase === "function" ? wrapPhase(phase, definition.phases) : phase;
98
98
  wrapped = {
@@ -124,18 +124,15 @@ function instrumentRegistry(registry, options, runs) {
124
124
  return bound(target, property);
125
125
  } });
126
126
  }
127
- function runPhase(kind, phase, runtime, context, runs, wrapTool, isAbort, options) {
127
+ function runPhase(kind, task, phase, runtime, context, runs, wrapTool, isAbort, options) {
128
128
  const { conversationId } = runtime;
129
129
  const isRunWork = kind === PI_TASK.GENERATION || kind === PI_TASK.TOOL;
130
130
  const run = isRunWork || kind === PI_TASK.COMPACTION ? runs.active.get(conversationId) ?? (isRunWork && !isAbort ? startRun(conversationId, runs) : void 0) : void 0;
131
- let observed = runtime;
132
- let finishToolPhase;
133
- if (run && kind === PI_TASK.GENERATION) observed = observeRunControl(runtime, run, runs);
134
- else if (kind === PI_TASK.TOOL) {
135
- const toolPhase = instrumentToolPhase(runtime, runs, wrapTool);
136
- observed = toolPhase.runtime;
137
- finishToolPhase = toolPhase.finish;
138
- }
131
+ const input = kind === PI_TASK.TOOL ? task?.input : void 0;
132
+ const callerSpan = input?.kind === "nested" ? runs.toolCalls.get(input.parent)?.find((call) => call.callId === input.parentCallId)?.span : void 0;
133
+ let finishPhase;
134
+ if (run && kind === PI_TASK.GENERATION) finishPhase = observeRunControl(runtime, run, runs);
135
+ else if (kind === PI_TASK.TOOL) finishPhase = instrumentToolPhase(runtime, runs, wrapTool, input?.kind === "nested");
139
136
  const runInScope = async (scope) => {
140
137
  let sessionId = run?.sessionId;
141
138
  if (!sessionId) {
@@ -152,7 +149,7 @@ function runPhase(kind, phase, runtime, context, runs, wrapTool, isAbort, option
152
149
  context
153
150
  });
154
151
  try {
155
- return await phase(observed);
152
+ return await phase();
156
153
  } catch (error) {
157
154
  if (!runtime.signal?.aborted) {
158
155
  captureException(error, { mechanism: {
@@ -166,11 +163,11 @@ function runPhase(kind, phase, runtime, context, runs, wrapTool, isAbort, option
166
163
  }
167
164
  throw error;
168
165
  } finally {
169
- finishToolPhase?.();
166
+ finishPhase?.();
170
167
  }
171
168
  };
172
169
  if (!run) return withCleanScopes(getDefaultIsolationScope().clone(), () => startNewTrace(() => runInScope(getCurrentScope())));
173
- return withCleanScopes(run.isolationScope, () => withActiveSpan(run.span, runInScope));
170
+ return withCleanScopes(run.isolationScope, () => withActiveSpan(callerSpan ?? run.span, runInScope));
174
171
  }
175
172
  export { endRunsOnClose, instrumentPiDurableHarnessOptions };
176
173
 
@@ -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 { 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/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AAM,UAAU,CAAC;AACvF"}
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 { 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 PiToolTaskInput,\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 taskRecord,\n () => phase.call(receiver, taskRecord, runtime, 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 task: unknown,\n phase: () => 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 // A call that a tool makes with `api.executeTool()`, as a code mode script does, is a `pi.tool`\n // task of its own. Its span belongs under the span of the calling tool.\n const input = kind === PI_TASK.TOOL ? (task as { input?: PiToolTaskInput } | undefined)?.input : undefined;\n const callerSpan =\n input?.kind === 'nested'\n ? runs.toolCalls.get(input.parent)?.find(call => call.callId === input.parentCallId)?.span\n : undefined;\n\n let finishPhase: (() => void) | undefined;\n if (run && kind === PI_TASK.GENERATION) {\n finishPhase = observeRunControl(runtime, run, runs);\n } else if (kind === PI_TASK.TOOL) {\n finishPhase = instrumentToolPhase(runtime, runs, wrapTool, input?.kind === 'nested');\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();\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 finishPhase?.();\n }\n };\n\n if (!run) {\n return withCleanScopes(getDefaultIsolationScope().clone(), () =>\n startNewTrace(() => runInScope(getCurrentScope())),\n );\n }\n return withCleanScopes(run.isolationScope, () => withActiveSpan(callerSpan ?? run.span, runInScope));\n}\n"],"mappings":";;;;;;;;;AA6CA,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,E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ACtD,oBAAoB,WAAW,gBAAgB,CAAC,CAAC,CACnD;CAEF,OAAO,gBAAgB,IAAI,sBAAsB,eAAe,cAAc,IAAI,MAAM,UAAU,CAAC;AACrG"}
@@ -95,7 +95,8 @@ function endRun(run, runs, status) {
95
95
  * function returns shows whether the run survived the commit.
96
96
  */
97
97
  function observeRunControl(runtime, run, runs) {
98
- const commit = (change, context) => {
98
+ const commit = runtime.commit.bind(runtime);
99
+ runtime.commit = (change, context, ...rest) => {
99
100
  let ended = false;
100
101
  let settlement;
101
102
  const observedChange = async (tx, current) => {
@@ -126,16 +127,16 @@ function observeRunControl(runtime, run, runs) {
126
127
  run.pendingEnd = ended ? { status: toRunStatus(settlement) } : void 0;
127
128
  return result;
128
129
  };
129
- return runtime.commit(observedChange, context).then(() => {
130
+ return commit(observedChange, context, ...rest).then(() => {
130
131
  if (ended) endRun(run, runs, toRunStatus(settlement));
131
132
  }, (error) => {
132
133
  run.pendingEnd = void 0;
133
134
  throw error;
134
135
  });
135
136
  };
136
- return new Proxy(runtime, { get(target, property) {
137
- return property === "commit" ? commit : bound(target, property);
138
- } });
137
+ return () => {
138
+ runtime.commit = commit;
139
+ };
139
140
  }
140
141
  function toRunStatus(settlement) {
141
142
  if (settlement?.status !== "unanswered") return;
@@ -1 +1 @@
1
- {"version":3,"file":"runs.js","names":[],"sources":["../../../../src/ai/pi-durable/runs.ts"],"sourcesContent":["import type { MaybeWeakRef, Scope, Span, SpanStatus } from '@sentry/core';\nimport {\n continueTrace,\n debug,\n derefWeakRef,\n getDefaultIsolationScope,\n getRootSpan,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n startNewTrace,\n uuid4,\n} from '@sentry/core';\nimport { GEN_AI_CONVERSATION_ID, GEN_AI_OPERATION_NAME, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { GEN_AI_INVOKE_AGENT } from '@sentry/conventions/op';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { MAX_TRACKED_PI_RUNS, PI_DURABLE_ORIGIN, PI_LIVE_DOC_KIND, PI_PROVIDER_DOC_KIND } from './constants';\nimport type { PiCommitChange, PiDocToken, PiLiveState, PiProviderState, PiSettlement, PiTaskRuntime } from './types';\nimport { withCleanScopes } from '../../utils/withCleanScopes';\nimport { bound } from './utils';\n\n// The definition of `pi.provider` as pi-durable checks it on a read: the address, the version and the\n// persisted semantics of the document.\nconst PROVIDER_DOC = {\n definition: { kind: PI_PROVIDER_DOC_KIND, version: 1, scope: 'conversation', history: 'latest', fork: 'initial' },\n};\n\n// Unanswered reasons that mean the run was stopped, not that it failed.\nconst CANCELLED_REASONS = new Set(['aborted', 'reset']);\n\n/**\n * One run: the work from an input to its answer. It spans several `pi.generation` tasks (run control\n * moves to a new one after every tool round) and their `pi.tool` tasks, so it is tracked per\n * conversation, which runs at most one run at a time.\n */\nexport interface PiRun {\n conversationId: unknown;\n span: Span;\n isolationScope: Scope;\n /** The run's first input submission, which identifies the run in `pi.live`. */\n firstInput?: unknown;\n /** The conversation's provider session id, read by the first phase of the run. */\n sessionId?: string;\n /**\n * The status the run ends with, set while the commit that ends it is in flight. `harness.close()`\n * can begin in that gap, because `wait()` resolves as soon as the commit settles the inputs.\n */\n pendingEnd?: { status?: SpanStatus };\n}\n\n/** Open runs of one Harness, keyed by the pi-durable conversation id. */\nexport interface PiRuns {\n /**\n * Random id of this Harness, prefixed to `gen_ai.conversation.id` until the provider session id of\n * the conversation is known. pi-durable numbers conversations per storage from 1, so the bare id\n * would merge the root conversations of every Harness into one Sentry conversation.\n */\n harnessId: string;\n active: Map<unknown, PiRun>;\n /**\n * Tool calls that created a conversation they own, keyed by that conversation. The child's first\n * run becomes a child of the call while the call's trace is in progress, and otherwise continues\n * that trace with the call as parent. This is how a subagent's run joins the trace of the run that\n * delegated to it.\n */\n owners: Map<unknown, PiOwner>;\n /**\n * Tool calls of running `pi.tool` phases, keyed by task id. Their spans end when the phase ends,\n * after it has committed the result the model receives.\n */\n toolCalls: Map<unknown, PiToolCall[]>;\n}\n\n/** A tool call that created a conversation it owns. */\nexport interface PiOwner {\n /**\n * The call's `execute_tool` span, held weakly: a conversation whose first run never starts must\n * not keep the trace of the call alive.\n */\n span: MaybeWeakRef<Span>;\n /** The `sentry-trace` value of the span, used to continue its trace once that trace has ended. */\n sentryTrace: string;\n /** The `baggage` value of the span, used together with `sentryTrace`. */\n baggage: string | undefined;\n}\n\n/** One `execute()` of a tool. */\nexport interface PiToolCall {\n span: Span;\n callId?: string;\n recordOutputs: boolean;\n /** Set once the span has a status other than ok, so the committed result does not overwrite it. */\n failed?: boolean;\n /** When `execute()` settled, used as the span's end time. */\n endTimestamp?: number;\n /** Set once `execute()` settled. Runs `onSpanEnd` with its result. */\n onSpanEnd?: () => void;\n}\n\nexport function createRuns(): PiRuns {\n return {\n harnessId: uuid4(),\n active: new Map(),\n owners: new Map(),\n toolCalls: new Map(),\n };\n}\n\nexport function toSentryConversationId(runs: PiRuns, conversationId: unknown): string {\n return runs.active.get(conversationId)?.sessionId ?? `${runs.harnessId}:${String(conversationId)}`;\n}\n\n/**\n * Read the provider session id of the conversation, or `undefined` when pi-durable keeps none.\n *\n * pi-durable 1.0.2 and later keep a UUIDv7 per conversation in the `pi.provider` document, stored with\n * the conversation. Unlike the harness prefix, it stays the same when a Harness opens the storage\n * again, for example after a Durable Object restarts, and it is unique across storages.\n */\nexport async function readProviderSessionId(runtime: PiTaskRuntime, context: unknown): Promise<string | undefined> {\n try {\n const provider = (await runtime.snapshot?.(PROVIDER_DOC, runtime.conversationId, context)) as\n | PiProviderState\n | undefined;\n return typeof provider?.sessionId === 'string' && provider.sessionId ? provider.sessionId : undefined;\n } catch (error) {\n // A later version of the document fails the read. The harness prefix is used then.\n DEBUG_BUILD && debug.warn('[pi-durable] failed to read the provider session id', error);\n return undefined;\n }\n}\n\n/** Start a run of `conversationId`: a new trace, or a child of the tool call that owns the conversation. */\nexport function startRun(conversationId: unknown, runs: PiRuns): PiRun {\n if (runs.active.size >= MAX_TRACKED_PI_RUNS) {\n const oldest = runs.active.keys().next().value;\n runs.active.get(oldest)?.span.end();\n runs.active.delete(oldest);\n }\n\n const owner = runs.owners.get(conversationId);\n runs.owners.delete(conversationId);\n const ownerSpan = derefWeakRef(owner?.span);\n // Under a trace that has ended, the run would be split into one transaction per span when spans are\n // not streamed. Continuing the trace instead also gives the same result whether or not GC ran.\n const parentSpan = ownerSpan && getRootSpan(ownerSpan).isRecording() ? ownerSpan : undefined;\n\n const isolationScope = getDefaultIsolationScope().clone();\n const startRunSpan = (): Span =>\n startInactiveSpan({\n name: 'invoke_agent',\n op: GEN_AI_INVOKE_AGENT,\n ...(parentSpan ? { parentSpan } : {}),\n attributes: {\n [SENTRY_ORIGIN]: PI_DURABLE_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'invoke_agent',\n [GEN_AI_CONVERSATION_ID]: toSentryConversationId(runs, conversationId),\n },\n });\n const span = withCleanScopes(isolationScope, () => {\n if (parentSpan) {\n return startRunSpan();\n }\n return owner\n ? continueTrace({ sentryTrace: owner.sentryTrace, baggage: owner.baggage }, startRunSpan)\n : startNewTrace(startRunSpan);\n });\n\n const run: PiRun = { conversationId, span, isolationScope };\n runs.active.set(conversationId, run);\n DEBUG_BUILD && debug.log(`[pi-durable] run of conversation ${String(conversationId)} started`);\n return run;\n}\n\nexport function endRun(run: PiRun, runs: PiRuns, status?: SpanStatus): void {\n if (runs.active.get(run.conversationId) !== run) {\n return;\n }\n runs.active.delete(run.conversationId);\n DEBUG_BUILD && debug.log(`[pi-durable] run of conversation ${String(run.conversationId)} ended`, status ?? 'ok');\n if (status) {\n run.span.setStatus(status);\n }\n run.span.end();\n}\n\n/**\n * Watch the generation task's commits for the end of its run.\n *\n * pi-durable keeps run control in the conversation's `pi.live` document: `run` names the task that\n * owns the run and the run's inputs, it moves to the next generation after every tool round, and it\n * is removed, in the same commit that settles the inputs, when the run ends. Every commit that moves\n * or ends a run edits `pi.live` through `tx.doc()`, so reading that draft after the commit's change\n * function returns shows whether the run survived the commit.\n */\nexport function observeRunControl(runtime: PiTaskRuntime, run: PiRun, runs: PiRuns): PiTaskRuntime {\n const commit = (change: PiCommitChange, context: unknown): Promise<void> => {\n let ended = false;\n let settlement: PiSettlement | undefined;\n\n const observedChange: PiCommitChange = async (tx, current) => {\n // A commit can run its change again, so only the attempt that committed counts.\n ended = false;\n settlement = undefined;\n let live: Promise<unknown> | undefined;\n const observedTx = new Proxy(tx, {\n get(target, property) {\n const value = bound(target, property);\n if (typeof value !== 'function') {\n return value;\n }\n if (property === 'doc') {\n return (token: PiDocToken, id: unknown, ...rest: unknown[]) => {\n const draft = value(token, id, ...rest);\n if (token?.definition?.kind === PI_LIVE_DOC_KIND && id === run.conversationId) {\n live = Promise.resolve(draft);\n }\n return draft;\n };\n }\n if (property === 'settleSubmission') {\n return (id: unknown, submissionSettlement: PiSettlement, ...rest: unknown[]) => {\n if (run.firstInput === undefined || id === run.firstInput) {\n settlement = submissionSettlement;\n }\n return value(id, submissionSettlement, ...rest);\n };\n }\n return value;\n },\n });\n\n const result = await change(observedTx, current);\n const draft = (await live) as PiLiveState | undefined;\n if (draft) {\n const firstInput = draft.run?.inputs?.[0];\n if (firstInput === undefined) {\n ended = true;\n } else if (run.firstInput === undefined) {\n run.firstInput = firstInput;\n } else if (firstInput !== run.firstInput) {\n // The run ended and a queued input started the next one in the same commit.\n ended = true;\n }\n }\n run.pendingEnd = ended ? { status: toRunStatus(settlement) } : undefined;\n return result;\n };\n\n return runtime.commit(observedChange, context).then(\n () => {\n if (ended) {\n endRun(run, runs, toRunStatus(settlement));\n }\n },\n error => {\n run.pendingEnd = undefined;\n throw error;\n },\n );\n };\n\n return new Proxy(runtime, {\n get(target, property) {\n return property === 'commit' ? commit : bound(target, property);\n },\n });\n}\n\nfunction toRunStatus(settlement: PiSettlement | undefined): SpanStatus | undefined {\n if (settlement?.status !== 'unanswered') {\n return undefined;\n }\n const reason = settlement.reason ?? 'internal_error';\n return { code: SPAN_STATUS_ERROR, message: CANCELLED_REASONS.has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YAAY,SAAA,aAA6B,OAAO,IAAI,gBAC7D,OAAO,QAAQ,QAAQ,KAAK;KAE9B,OAAO;IACT;IAEF,IAAI,aAAa,oBACf,QAAQ,IAAa,sBAAoC,GAAG,SAAoB;KAC9E,IAAI,IAAI,eAAe,KAAA,KAAa,OAAO,IAAI,YAC7C,aAAa;KAEf,OAAO,MAAM,IAAI,sBAAsB,GAAG,IAAI;IAChD;IAEF,OAAO;GACT,EACF,CAEqC,GAAG,OAAO;GAC/C,MAAM,QAAS,MAAM;GACrB,IAAI,OAAO;IACT,MAAM,aAAa,MAAM,KAAK,SAAS;IACvC,IAAI,eAAe,KAAA,GACjB,QAAQ;SACH,IAAI,IAAI,eAAe,KAAA,GAC5B,IAAI,aAAa;SACZ,IAAI,eAAe,IAAI,YAE5B,QAAQ;GAEZ;GACA,IAAI,aAAa,QAAQ,EAAE,QAAQ,YAAY,UAAU,EAAE,IAAI,KAAA;GAC/D,OAAO;EACT;EAEA,OAAO,QAAQ,OAAO,gBAAgB,OAAO,CAAC,CAAC,WACvC;GACJ,IAAI,OACF,OAAO,KAAK,MAAM,YAAY,UAAU,CAAC;EAE7C,IACA,UAAS;GACP,IAAI,aAAa,KAAA;GACjB,MAAM;EACR,CACF;CACF;CAEA,OAAO,IAAI,MAAM,SAAS,EACxB,IAAI,QAAQ,UAAU;EACpB,OAAO,aAAa,WAAW,SAAS,MAAM,QAAQ,QAAQ;CAChE,EACF,CAAC;AACH;AAEA,SAAS,YAAY,YAA8D;CACjF,IAAI,YAAY,WAAW,cACzB;CAEF,MAAM,SAAS,WAAW,UAAU;CACpC,OAAO;EAAE,MAAM;EAAmB,SAAS,kBAAkB,IAAI,MAAM,IAAI,cAAc;CAAO;AAClG"}
1
+ {"version":3,"file":"runs.js","names":[],"sources":["../../../../src/ai/pi-durable/runs.ts"],"sourcesContent":["import type { MaybeWeakRef, Scope, Span, SpanStatus } from '@sentry/core';\nimport {\n continueTrace,\n debug,\n derefWeakRef,\n getDefaultIsolationScope,\n getRootSpan,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n startNewTrace,\n uuid4,\n} from '@sentry/core';\nimport { GEN_AI_CONVERSATION_ID, GEN_AI_OPERATION_NAME, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { GEN_AI_INVOKE_AGENT } from '@sentry/conventions/op';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { MAX_TRACKED_PI_RUNS, PI_DURABLE_ORIGIN, PI_LIVE_DOC_KIND, PI_PROVIDER_DOC_KIND } from './constants';\nimport type {\n PiCommitChange,\n PiDocToken,\n PiLiveState,\n PiProviderState,\n PiSettlement,\n PiTaskRuntime,\n PiToolResultMessage,\n} from './types';\nimport { withCleanScopes } from '../../utils/withCleanScopes';\nimport { bound } from './utils';\n\n// The definition of `pi.provider` as pi-durable checks it on a read: the address, the version and the\n// persisted semantics of the document.\nconst PROVIDER_DOC = {\n definition: { kind: PI_PROVIDER_DOC_KIND, version: 1, scope: 'conversation', history: 'latest', fork: 'initial' },\n};\n\n// Unanswered reasons that mean the run was stopped, not that it failed.\nconst CANCELLED_REASONS = new Set(['aborted', 'reset']);\n\n/**\n * One run: the work from an input to its answer. It spans several `pi.generation` tasks (run control\n * moves to a new one after every tool round) and their `pi.tool` tasks, so it is tracked per\n * conversation, which runs at most one run at a time.\n */\nexport interface PiRun {\n conversationId: unknown;\n span: Span;\n isolationScope: Scope;\n /** The run's first input submission, which identifies the run in `pi.live`. */\n firstInput?: unknown;\n /** The conversation's provider session id, read by the first phase of the run. */\n sessionId?: string;\n /**\n * The status the run ends with, set while the commit that ends it is in flight. `harness.close()`\n * can begin in that gap, because `wait()` resolves as soon as the commit settles the inputs.\n */\n pendingEnd?: { status?: SpanStatus };\n}\n\n/** Open runs of one Harness, keyed by the pi-durable conversation id. */\nexport interface PiRuns {\n /**\n * Random id of this Harness, prefixed to `gen_ai.conversation.id` until the provider session id of\n * the conversation is known. pi-durable numbers conversations per storage from 1, so the bare id\n * would merge the root conversations of every Harness into one Sentry conversation.\n */\n harnessId: string;\n active: Map<unknown, PiRun>;\n /**\n * Tool calls that created a conversation they own, keyed by that conversation. The child's first\n * run becomes a child of the call while the call's trace is in progress, and otherwise continues\n * that trace with the call as parent. This is how a subagent's run joins the trace of the run that\n * delegated to it.\n */\n owners: Map<unknown, PiOwner>;\n /**\n * Tool calls of running `pi.tool` phases, keyed by task id. Their spans end when the phase ends,\n * after it has committed the result the model receives.\n */\n toolCalls: Map<unknown, PiToolCall[]>;\n}\n\n/** A tool call that created a conversation it owns. */\nexport interface PiOwner {\n /**\n * The call's `execute_tool` span, held weakly: a conversation whose first run never starts must\n * not keep the trace of the call alive.\n */\n span: MaybeWeakRef<Span>;\n /** The `sentry-trace` value of the span, used to continue its trace once that trace has ended. */\n sentryTrace: string;\n /** The `baggage` value of the span, used together with `sentryTrace`. */\n baggage: string | undefined;\n}\n\n/** One `execute()` of a tool. */\nexport interface PiToolCall {\n span: Span;\n callId?: string;\n recordOutputs: boolean;\n /** Set once the span has a status other than ok, so the committed result does not overwrite it. */\n failed?: boolean;\n /** When `execute()` settled, used as the span's end time. */\n endTimestamp?: number;\n /** Set once `execute()` settled. Runs `onSpanEnd` with its result. */\n onSpanEnd?: () => void;\n /** What `execute()` returned, the result of a call that commits no result entry. */\n returned?: PiToolResultMessage;\n}\n\nexport function createRuns(): PiRuns {\n return {\n harnessId: uuid4(),\n active: new Map(),\n owners: new Map(),\n toolCalls: new Map(),\n };\n}\n\nexport function toSentryConversationId(runs: PiRuns, conversationId: unknown): string {\n return runs.active.get(conversationId)?.sessionId ?? `${runs.harnessId}:${String(conversationId)}`;\n}\n\n/**\n * Read the provider session id of the conversation, or `undefined` when pi-durable keeps none.\n *\n * pi-durable 1.0.2 and later keep a UUIDv7 per conversation in the `pi.provider` document, stored with\n * the conversation. Unlike the harness prefix, it stays the same when a Harness opens the storage\n * again, for example after a Durable Object restarts, and it is unique across storages.\n */\nexport async function readProviderSessionId(runtime: PiTaskRuntime, context: unknown): Promise<string | undefined> {\n try {\n const provider = (await runtime.snapshot?.(PROVIDER_DOC, runtime.conversationId, context)) as\n | PiProviderState\n | undefined;\n return typeof provider?.sessionId === 'string' && provider.sessionId ? provider.sessionId : undefined;\n } catch (error) {\n // A later version of the document fails the read. The harness prefix is used then.\n DEBUG_BUILD && debug.warn('[pi-durable] failed to read the provider session id', error);\n return undefined;\n }\n}\n\n/** Start a run of `conversationId`: a new trace, or a child of the tool call that owns the conversation. */\nexport function startRun(conversationId: unknown, runs: PiRuns): PiRun {\n if (runs.active.size >= MAX_TRACKED_PI_RUNS) {\n const oldest = runs.active.keys().next().value;\n runs.active.get(oldest)?.span.end();\n runs.active.delete(oldest);\n }\n\n const owner = runs.owners.get(conversationId);\n runs.owners.delete(conversationId);\n const ownerSpan = derefWeakRef(owner?.span);\n // Under a trace that has ended, the run would be split into one transaction per span when spans are\n // not streamed. Continuing the trace instead also gives the same result whether or not GC ran.\n const parentSpan = ownerSpan && getRootSpan(ownerSpan).isRecording() ? ownerSpan : undefined;\n\n const isolationScope = getDefaultIsolationScope().clone();\n const startRunSpan = (): Span =>\n startInactiveSpan({\n name: 'invoke_agent',\n op: GEN_AI_INVOKE_AGENT,\n ...(parentSpan ? { parentSpan } : {}),\n attributes: {\n [SENTRY_ORIGIN]: PI_DURABLE_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'invoke_agent',\n [GEN_AI_CONVERSATION_ID]: toSentryConversationId(runs, conversationId),\n },\n });\n const span = withCleanScopes(isolationScope, () => {\n if (parentSpan) {\n return startRunSpan();\n }\n return owner\n ? continueTrace({ sentryTrace: owner.sentryTrace, baggage: owner.baggage }, startRunSpan)\n : startNewTrace(startRunSpan);\n });\n\n const run: PiRun = { conversationId, span, isolationScope };\n runs.active.set(conversationId, run);\n DEBUG_BUILD && debug.log(`[pi-durable] run of conversation ${String(conversationId)} started`);\n return run;\n}\n\nexport function endRun(run: PiRun, runs: PiRuns, status?: SpanStatus): void {\n if (runs.active.get(run.conversationId) !== run) {\n return;\n }\n runs.active.delete(run.conversationId);\n DEBUG_BUILD && debug.log(`[pi-durable] run of conversation ${String(run.conversationId)} ended`, status ?? 'ok');\n if (status) {\n run.span.setStatus(status);\n }\n run.span.end();\n}\n\n/**\n * Watch the generation task's commits for the end of its run.\n *\n * pi-durable keeps run control in the conversation's `pi.live` document: `run` names the task that\n * owns the run and the run's inputs, it moves to the next generation after every tool round, and it\n * is removed, in the same commit that settles the inputs, when the run ends. Every commit that moves\n * or ends a run edits `pi.live` through `tx.doc()`, so reading that draft after the commit's change\n * function returns shows whether the run survived the commit.\n */\nexport function observeRunControl(runtime: PiTaskRuntime, run: PiRun, runs: PiRuns): () => void {\n const commit: PiTaskRuntime['commit'] = runtime.commit.bind(runtime);\n // Replaced on the runtime itself: pi-durable 1.6.0 finds the state it keeps for a runtime by\n // that object, so a phase that gets a Proxy of it faults. The returned function puts `commit`\n // back, as pi-durable can keep the runtime after the phase, and with it the run and its spans.\n runtime.commit = (change: PiCommitChange, context: unknown, ...rest: unknown[]): Promise<void> => {\n let ended = false;\n let settlement: PiSettlement | undefined;\n\n const observedChange: PiCommitChange = async (tx, current) => {\n // A commit can run its change again, so only the attempt that committed counts.\n ended = false;\n settlement = undefined;\n let live: Promise<unknown> | undefined;\n const observedTx = new Proxy(tx, {\n get(target, property) {\n const value = bound(target, property);\n if (typeof value !== 'function') {\n return value;\n }\n if (property === 'doc') {\n return (token: PiDocToken, id: unknown, ...rest: unknown[]) => {\n const draft = value(token, id, ...rest);\n if (token?.definition?.kind === PI_LIVE_DOC_KIND && id === run.conversationId) {\n live = Promise.resolve(draft);\n }\n return draft;\n };\n }\n if (property === 'settleSubmission') {\n return (id: unknown, submissionSettlement: PiSettlement, ...rest: unknown[]) => {\n if (run.firstInput === undefined || id === run.firstInput) {\n settlement = submissionSettlement;\n }\n return value(id, submissionSettlement, ...rest);\n };\n }\n return value;\n },\n });\n\n const result = await change(observedTx, current);\n const draft = (await live) as PiLiveState | undefined;\n if (draft) {\n const firstInput = draft.run?.inputs?.[0];\n if (firstInput === undefined) {\n ended = true;\n } else if (run.firstInput === undefined) {\n run.firstInput = firstInput;\n } else if (firstInput !== run.firstInput) {\n // The run ended and a queued input started the next one in the same commit.\n ended = true;\n }\n }\n run.pendingEnd = ended ? { status: toRunStatus(settlement) } : undefined;\n return result;\n };\n\n return commit(observedChange, context, ...rest).then(\n () => {\n if (ended) {\n endRun(run, runs, toRunStatus(settlement));\n }\n },\n error => {\n run.pendingEnd = undefined;\n throw error;\n },\n );\n };\n\n return () => {\n runtime.commit = commit;\n };\n}\n\nfunction toRunStatus(settlement: PiSettlement | undefined): SpanStatus | undefined {\n if (settlement?.status !== 'unanswered') {\n return undefined;\n }\n const reason = settlement.reason ?? 'internal_error';\n return { code: SPAN_STATUS_ERROR, message: CANCELLED_REASONS.has(reason) ? 'cancelled' : reason };\n}\n"],"mappings":";;;;;;;;AA8BA,MAAM,eAAe,EACnB,YAAY;CAAE,MAAM;CAAsB,SAAS;CAAG,OAAO;CAAgB,SAAS;CAAU,MAAM;AAAU,EAClH;AAGA,MAAM,oCAAoB,IAAI,IAAI,CAAC,WAAW,OAAO,CAAC;AAyEtD,SAAgB,aAAqB;CACnC,OAAO;EACL,WAAW,MAAM;EACjB,wBAAQ,IAAI,IAAI;EAChB,wBAAQ,IAAI,IAAI;EAChB,2BAAW,IAAI,IAAI;CACrB;AACF;AAEA,SAAgB,uBAAuB,MAAc,gBAAiC;CACpF,OAAO,KAAK,OAAO,IAAI,cAAc,CAAC,EAAE,aAAa,GAAG,KAAK,UAAU,GAAG,OAAO,cAAc;AACjG;;;;;;;;AASA,eAAsB,sBAAsB,SAAwB,SAA+C;CACjH,IAAI;EACF,MAAM,WAAY,MAAM,QAAQ,WAAW,cAAc,QAAQ,gBAAgB,OAAO;EAGxF,OAAO,OAAO,UAAU,cAAc,YAAY,SAAS,YAAY,SAAS,YAAY,KAAA;CAC9F,SAAS,OAAO;EAEd,eAAe,MAAM,KAAK,uDAAuD,KAAK;EACtF;CAC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AO,KAAK,MAAM,YAAY,UAAU,CAAC;EAE7C,IACA,UAAS;GACP,IAAI,aAAa,KAAA;GACjB,MAAM;EACR,CACF;CACF;CAEA,aAAa;EACX,QAAQ,SAAS;CACnB;AACF;AAEA,SAAS,YAAY,YAA8D;CACjF,IAAI,YAAY,WAAW,cACzB;CAEF,MAAM,SAAS,WAAW,UAAU;CACpC,OAAO;EAAE,MAAM;EAAmB,SAAS,kBAAkB,IAAI,MAAM,IAAI,cAAc;CAAO;AAClG"}
@@ -22,35 +22,38 @@ function markBuiltInTool(tool) {
22
22
  /**
23
23
  * Prepare the runtime of a `pi.tool` phase. The tool task resolves the called tool from its agent,
24
24
  * so the runtime hands out traced tools, and it collects the result entries the phase commits.
25
- * `finish` ends the phase's tool spans with the result the model receives, which pi-durable builds
26
- * after `execute()` returns: from `api.output()`, through `afterTool` hooks and output limits.
25
+ * The returned function ends the phase's tool spans with the result the model receives, which
26
+ * pi-durable builds after `execute()` returns: from `api.output()`, through `afterTool` hooks and
27
+ * output limits.
27
28
  */
28
- function instrumentToolPhase(runtime, runs, wrapTool) {
29
+ function instrumentToolPhase(runtime, runs, wrapTool, isNested) {
29
30
  const results = /* @__PURE__ */ new Map();
30
31
  runs.toolCalls.set(runtime.taskId, []);
31
- const agent = (context) => runtime.agent(context).then((resolved) => resolved?.tools ? {
32
+ const agent = runtime.agent.bind(runtime);
33
+ const commit = runtime.commit.bind(runtime);
34
+ runtime.agent = (context) => agent(context).then((resolved) => resolved?.tools ? {
32
35
  ...resolved,
33
- tools: resolved.tools.map(wrapTool)
36
+ tools: resolved.tools.map(wrapTool),
37
+ ...resolved.callable ? { callable: resolved.callable.map(wrapTool) } : {}
34
38
  } : resolved);
35
- const commit = (change, context) => {
39
+ runtime.commit = (change, context, ...rest) => {
36
40
  let committed = [];
37
41
  const observedChange = (tx, current) => {
38
42
  committed = [];
39
43
  return change(observeToolResultEntries(tx, committed), current);
40
44
  };
41
- return runtime.commit(observedChange, context).then(() => {
45
+ return commit(observedChange, context, ...rest).then(() => {
42
46
  for (const message of committed) results.set(message.toolCallId, message);
43
47
  });
44
48
  };
45
- return {
46
- runtime: new Proxy(runtime, { get(target, property) {
47
- if (property === "agent") return agent;
48
- return property === "commit" ? commit : bound(target, property);
49
- } }),
50
- finish: () => {
51
- for (const call of runs.toolCalls.get(runtime.taskId) ?? []) finishToolCall(call, call.callId !== void 0 ? results.get(call.callId) : void 0);
52
- runs.toolCalls.delete(runtime.taskId);
49
+ return () => {
50
+ runtime.agent = agent;
51
+ runtime.commit = commit;
52
+ for (const call of runs.toolCalls.get(runtime.taskId) ?? []) {
53
+ const committed = call.callId !== void 0 ? results.get(call.callId) : void 0;
54
+ finishToolCall(call, isNested ? call.returned : committed);
53
55
  }
56
+ runs.toolCalls.delete(runtime.taskId);
54
57
  };
55
58
  }
56
59
  /** Wrap a tool so each call gets a `gen_ai.execute_tool` span. */
@@ -90,10 +93,11 @@ function instrumentTool(tool, runs, options) {
90
93
  const result = await tool.execute(args, trackOwnedConversations(api, span, runs), context);
91
94
  call.endTimestamp = timestampInSeconds();
92
95
  call.onSpanEnd = () => runGenAiSpanEnd(options, span, toolCall, { response: result });
93
- if (!calls) finishToolCall(call, {
96
+ call.returned = {
94
97
  content: result?.output ?? result?.content,
95
98
  isError: result?.isError
96
- });
99
+ };
100
+ if (!calls) finishToolCall(call, call.returned);
97
101
  return result;
98
102
  } catch (error) {
99
103
  call.endTimestamp = timestampInSeconds();
@@ -1 +1 @@
1
- {"version":3,"file":"tools.js","names":[],"sources":["../../../../src/ai/pi-durable/tools.ts"],"sourcesContent":["import type { Span } from '@sentry/core';\nimport {\n captureException,\n isObjectLike,\n makeWeakRef,\n SPAN_STATUS_ERROR,\n spanToBaggageHeader,\n spanToTraceHeader,\n startSpanManual,\n stringify,\n timestampInSeconds,\n} from '@sentry/core';\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_OPERATION_NAME,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DESCRIPTION,\n GEN_AI_TOOL_NAME,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_EXECUTE_TOOL } from '@sentry/conventions/op';\nimport { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport type { GenAiSpanHooks } from '../core/span-hooks';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { GenAiCallOptions } from '../core/utils';\nimport { resolveGenAiCallRecording } from '../core/utils';\nimport { piAiContentToString } from '../pi-ai/messages';\nimport { MAX_TRACKED_PI_RUNS, PI_DURABLE_ORIGIN, PI_TOOL_RESULT_ENTRY_KIND } from './constants';\nimport type { PiRuns, PiToolCall } from './runs';\nimport { toSentryConversationId } from './runs';\nimport type {\n PiAgent,\n PiCommitChange,\n PiDurableCallInfo,\n PiEntryToken,\n PiTaskRuntime,\n PiTool,\n PiToolExecutionApi,\n PiToolExecutionResult,\n PiToolResultMessage,\n} from './types';\nimport { bound } from './utils';\n\n/**\n * The tools pi-durable's `createBashTool`, `createReadTool`, `createEditTool` and `createWriteTool`\n * factories return. They throw to report expected failures to the model, such as a command that\n * exits non-zero, so their throws are not captured. Filled by the integration from the factories'\n * channels, which also covers the tools an app registers in an extension of its own.\n */\nconst BUILT_IN_TOOLS = new WeakSet<object>();\n\nexport function markBuiltInTool(tool: unknown): void {\n if (isObjectLike(tool)) {\n BUILT_IN_TOOLS.add(tool);\n }\n}\n\n/**\n * Prepare the runtime of a `pi.tool` phase. The tool task resolves the called tool from its agent,\n * so the runtime hands out traced tools, and it collects the result entries the phase commits.\n * `finish` ends the phase's tool spans with the result the model receives, which pi-durable builds\n * after `execute()` returns: from `api.output()`, through `afterTool` hooks and output limits.\n */\nexport function instrumentToolPhase(\n runtime: PiTaskRuntime,\n runs: PiRuns,\n wrapTool: (tool: PiTool) => PiTool,\n): { runtime: PiTaskRuntime; finish: () => void } {\n const results = new Map<unknown, PiToolResultMessage>();\n runs.toolCalls.set(runtime.taskId, []);\n\n const agent = (context: unknown): Promise<PiAgent> =>\n runtime\n .agent(context)\n .then(resolved => (resolved?.tools ? { ...resolved, tools: resolved.tools.map(wrapTool) } : resolved));\n\n const commit = (change: PiCommitChange, context: unknown): Promise<void> => {\n let committed: PiToolResultMessage[] = [];\n const observedChange: PiCommitChange = (tx, current) => {\n // A commit can run its change again, so only the attempt that committed counts.\n committed = [];\n return change(observeToolResultEntries(tx, committed), current);\n };\n return runtime.commit(observedChange, context).then(() => {\n for (const message of committed) {\n results.set(message.toolCallId, message);\n }\n });\n };\n\n return {\n runtime: new Proxy(runtime, {\n get(target, property) {\n if (property === 'agent') {\n return agent;\n }\n return property === 'commit' ? commit : bound(target, property);\n },\n }),\n finish: () => {\n for (const call of runs.toolCalls.get(runtime.taskId) ?? []) {\n finishToolCall(call, call.callId !== undefined ? results.get(call.callId) : undefined);\n }\n runs.toolCalls.delete(runtime.taskId);\n },\n };\n}\n\n/** Wrap a tool so each call gets a `gen_ai.execute_tool` span. */\nexport function instrumentTool(\n tool: PiTool,\n runs: PiRuns,\n options: GenAiCallOptions<PiDurableCallInfo> & GenAiSpanHooks<PiDurableCallInfo, PiToolExecutionResult>,\n): PiTool {\n const execute = (args: unknown, api: PiToolExecutionApi, context: unknown): Promise<unknown> => {\n const toolCall: PiDurableCallInfo = { operation: 'execute_tool', tool, args, api, context };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, toolCall);\n const phaseCalls = runs.toolCalls.get(api?.taskId);\n // A tool that runs another tool of its agent passes its own `api` on, so the inner call shares\n // the call id. Only the outer call gets the committed result; the inner one ends with its own.\n const calls = phaseCalls?.some(call => call.callId !== undefined && call.callId === api?.callId)\n ? undefined\n : phaseCalls;\n\n return startSpanManual(\n {\n name: `execute_tool ${tool.name}`,\n op: GEN_AI_EXECUTE_TOOL,\n attributes: {\n [SENTRY_ORIGIN]: PI_DURABLE_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'execute_tool',\n [GEN_AI_TOOL_NAME]: tool.name,\n [GEN_AI_TOOL_DESCRIPTION]: tool.description,\n [GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: api?.callId,\n ...(api?.conversationId !== undefined\n ? { [GEN_AI_CONVERSATION_ID]: toSentryConversationId(runs, api.conversationId) }\n : {}),\n ...(recordInputs && args !== undefined ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(args) } : {}),\n },\n },\n async span => {\n const call: PiToolCall = { span, callId: api?.callId, recordOutputs };\n calls?.push(call);\n runGenAiSpanStart(options, span, toolCall);\n try {\n const result = await tool.execute(args, trackOwnedConversations(api, span, runs), context);\n call.endTimestamp = timestampInSeconds();\n call.onSpanEnd = () => runGenAiSpanEnd(options, span, toolCall, { response: result });\n if (!calls) {\n // No result entry follows a call outside a tool task phase, nor a nested call.\n finishToolCall(call, { content: result?.output ?? result?.content, isError: result?.isError });\n }\n return result;\n } catch (error) {\n call.endTimestamp = timestampInSeconds();\n call.failed = true;\n call.onSpanEnd = () => runGenAiSpanEnd(options, span, toolCall, { error });\n // pi-durable turns the throw into an error result for the model, so the app never gets a\n // chance to handle it. An aborted call is not a failure.\n if ((context as { abortSignal?: AbortSignal } | undefined)?.abortSignal?.aborted) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n } else {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n if (!BUILT_IN_TOOLS.has(tool)) {\n captureException(error, { mechanism: { handled: false, type: PI_DURABLE_ORIGIN } });\n }\n }\n if (!calls) {\n call.onSpanEnd();\n span.end(call.endTimestamp);\n }\n throw error;\n }\n },\n );\n };\n\n // The proxy's target is an empty object with the tool as prototype, not the tool itself, so a\n // frozen tool does not break the proxy invariants. Members are read bound to the tool, so a\n // method that reads a private field works.\n return new Proxy(Object.create(tool) as PiTool, {\n get(_target, property) {\n return property === 'execute' ? execute : bound(tool, property);\n },\n });\n}\n\nfunction finishToolCall(call: PiToolCall, message: PiToolResultMessage | undefined): void {\n if (message) {\n const result = call.recordOutputs ? piAiContentToString(message.content) : undefined;\n if (result !== undefined) {\n call.span.setAttribute(GEN_AI_TOOL_CALL_RESULT, result);\n }\n if (message.isError && !call.failed) {\n call.span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n }\n call.onSpanEnd?.();\n call.span.end(call.endTimestamp);\n}\n\nfunction observeToolResultEntries(tx: object, committed: PiToolResultMessage[]): object {\n return new Proxy(tx, {\n get(target, property) {\n const value = bound(target, property);\n if (property !== 'appendEntry' || typeof value !== 'function') {\n return value;\n }\n return (\n token: PiEntryToken,\n conversationId: unknown,\n draft: { model?: unknown[] } | undefined,\n ...rest: unknown[]\n ) => {\n const message = token?.kind === PI_TOOL_RESULT_ENTRY_KIND ? draft?.model?.[0] : undefined;\n if (isObjectLike(message)) {\n committed.push(message);\n }\n return value(token, conversationId, draft, ...rest);\n };\n },\n });\n}\n\n/**\n * Record the conversations a tool call creates for itself, the subagent pattern: `api.commit()` with\n * `tx.createConversation()` or `tx.forkConversation()` and `ownership: { kind: 'task', taskId: api.taskId }`.\n */\nfunction trackOwnedConversations(api: PiToolExecutionApi, span: Span, runs: PiRuns): PiToolExecutionApi {\n if (typeof api?.commit !== 'function') {\n return api;\n }\n const commit = api.commit.bind(api);\n\n const trackCreatedConversations = (tx: object): object =>\n new Proxy(tx, {\n get(target, property) {\n const value = bound(target, property);\n if ((property !== 'createConversation' && property !== 'forkConversation') || typeof value !== 'function') {\n return value;\n }\n return async (...args: unknown[]) => {\n const record = (await value(...args)) as { id?: unknown } | undefined;\n const ownership = args.find(\n (arg): arg is { ownership: { kind?: string } } => isObjectLike(arg) && isObjectLike(arg.ownership),\n )?.ownership;\n if (ownership?.kind === 'task' && record?.id !== undefined) {\n if (runs.owners.size >= MAX_TRACKED_PI_RUNS) {\n runs.owners.delete(runs.owners.keys().next().value);\n }\n runs.owners.set(record.id, {\n span: makeWeakRef(span),\n sentryTrace: spanToTraceHeader(span),\n baggage: spanToBaggageHeader(span),\n });\n }\n return record;\n };\n },\n });\n\n return new Proxy(api, {\n get(target, property) {\n if (property !== 'commit') {\n return bound(target, property);\n }\n return (change: (tx: object) => unknown, context: unknown) =>\n commit((tx: object) => change(trackCreatedConversations(tx)), context);\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAkDA,MAAM,iCAAiB,IAAI,QAAgB;AAE3C,SAAgB,gBAAgB,MAAqB;CACnD,IAAI,aAAa,IAAI,GACnB,eAAe,IAAI,IAAI;AAE3B;;;;;;;AAQA,SAAgB,oBACd,SACA,MACA,UACgD;CAChD,MAAM,0BAAU,IAAI,IAAkC;CACtD,KAAK,UAAU,IAAI,QAAQ,QAAQ,CAAC,CAAC;CAErC,MAAM,SAAS,YACb,QACG,MAAM,OAAO,CAAC,CACd,MAAK,aAAa,UAAU,QAAQ;EAAE,GAAG;EAAU,OAAO,SAAS,MAAM,IAAI,QAAQ;CAAE,IAAI,QAAS;CAEzG,MAAM,UAAU,QAAwB,YAAoC;EAC1E,IAAI,YAAmC,CAAC;EACxC,MAAM,kBAAkC,IAAI,YAAY;GAEtD,YAAY,CAAC;GACb,OAAO,OAAO,yBAAyB,IAAI,SAAS,GAAG,OAAO;EAChE;EACA,OAAO,QAAQ,OAAO,gBAAgB,OAAO,CAAC,CAAC,WAAW;GACxD,KAAK,MAAM,WAAW,WACpB,QAAQ,IAAI,QAAQ,YAAY,OAAO;EAE3C,CAAC;CACH;CAEA,OAAO;EACL,SAAS,IAAI,MAAM,SAAS,EAC1B,IAAI,QAAQ,UAAU;GACpB,IAAI,aAAa,SACf,OAAO;GAET,OAAO,aAAa,WAAW,SAAS,MAAM,QAAQ,QAAQ;EAChE,EACF,CAAC;EACD,cAAc;GACZ,KAAK,MAAM,QAAQ,KAAK,UAAU,IAAI,QAAQ,MAAM,KAAK,CAAC,GACxD,eAAe,MAAM,KAAK,WAAW,KAAA,IAAY,QAAQ,IAAI,KAAK,MAAM,IAAI,KAAA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,IAAI,aAAa,OAAO,GACtB,UAAU,KAAK,OAAO;GAExB,OAAO,MAAM,OAAO,gBAAgB,OAAO,GAAG,IAAI;EACpD;CACF,EACF,CAAC;AACH;;;;;AAMA,SAAS,wBAAwB,KAAyB,MAAY,MAAkC;CACtG,IAAI,OAAO,KAAK,WAAW,YACzB,OAAO;CAET,MAAM,SAAS,IAAI,OAAO,KAAK,GAAG;CAElC,MAAM,6BAA6B,OACjC,IAAI,MAAM,IAAI,EACZ,IAAI,QAAQ,UAAU;EACpB,MAAM,QAAQ,MAAM,QAAQ,QAAQ;EACpC,IAAK,aAAa,wBAAwB,aAAa,sBAAuB,OAAO,UAAU,YAC7F,OAAO;EAET,OAAO,OAAO,GAAG,SAAoB;GACnC,MAAM,SAAU,MAAM,MAAM,GAAG,IAAI;GAInC,KAHkB,KAAK,MACpB,QAAiD,aAAa,GAAG,KAAK,aAAa,IAAI,SAAS,CACnG,CAAC,EAAE,UAAA,EACY,SAAS,UAAU,QAAQ,OAAO,KAAA,GAAW;IAC1D,IAAI,KAAK,OAAO,QAAA,KACd,KAAK,OAAO,OAAO,KAAK,OAAO,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK;IAEpD,KAAK,OAAO,IAAI,OAAO,IAAI;KACzB,MAAM,YAAY,IAAI;KACtB,aAAa,kBAAkB,IAAI;KACnC,SAAS,oBAAoB,IAAI;IACnC,CAAC;GACH;GACA,OAAO;EACT;CACF,EACF,CAAC;CAEH,OAAO,IAAI,MAAM,KAAK,EACpB,IAAI,QAAQ,UAAU;EACpB,IAAI,aAAa,UACf,OAAO,MAAM,QAAQ,QAAQ;EAE/B,QAAQ,QAAiC,YACvC,QAAQ,OAAe,OAAO,0BAA0B,EAAE,CAAC,GAAG,OAAO;CACzE,EACF,CAAC;AACH"}
1
+ {"version":3,"file":"tools.js","names":[],"sources":["../../../../src/ai/pi-durable/tools.ts"],"sourcesContent":["import type { Span } from '@sentry/core';\nimport {\n captureException,\n isObjectLike,\n makeWeakRef,\n SPAN_STATUS_ERROR,\n spanToBaggageHeader,\n spanToTraceHeader,\n startSpanManual,\n stringify,\n timestampInSeconds,\n} from '@sentry/core';\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_OPERATION_NAME,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DESCRIPTION,\n GEN_AI_TOOL_NAME,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_EXECUTE_TOOL } from '@sentry/conventions/op';\nimport { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport type { GenAiSpanHooks } from '../core/span-hooks';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { GenAiCallOptions } from '../core/utils';\nimport { resolveGenAiCallRecording } from '../core/utils';\nimport { piAiContentToString } from '../pi-ai/messages';\nimport { MAX_TRACKED_PI_RUNS, PI_DURABLE_ORIGIN, PI_TOOL_RESULT_ENTRY_KIND } from './constants';\nimport type { PiRuns, PiToolCall } from './runs';\nimport { toSentryConversationId } from './runs';\nimport type {\n PiAgent,\n PiCommitChange,\n PiDurableCallInfo,\n PiEntryToken,\n PiTaskRuntime,\n PiTool,\n PiToolExecutionApi,\n PiToolExecutionResult,\n PiToolResultMessage,\n} from './types';\nimport { bound } from './utils';\n\n/**\n * The tools pi-durable's `createBashTool`, `createReadTool`, `createEditTool` and `createWriteTool`\n * factories return. They throw to report expected failures to the model, such as a command that\n * exits non-zero, so their throws are not captured. Filled by the integration from the factories'\n * channels, which also covers the tools an app registers in an extension of its own.\n */\nconst BUILT_IN_TOOLS = new WeakSet<object>();\n\nexport function markBuiltInTool(tool: unknown): void {\n if (isObjectLike(tool)) {\n BUILT_IN_TOOLS.add(tool);\n }\n}\n\n/**\n * Prepare the runtime of a `pi.tool` phase. The tool task resolves the called tool from its agent,\n * so the runtime hands out traced tools, and it collects the result entries the phase commits.\n * The returned function ends the phase's tool spans with the result the model receives, which\n * pi-durable builds after `execute()` returns: from `api.output()`, through `afterTool` hooks and\n * output limits.\n */\nexport function instrumentToolPhase(\n runtime: PiTaskRuntime,\n runs: PiRuns,\n wrapTool: (tool: PiTool) => PiTool,\n isNested: boolean,\n): () => void {\n const results = new Map<unknown, PiToolResultMessage>();\n runs.toolCalls.set(runtime.taskId, []);\n\n const agent: PiTaskRuntime['agent'] = runtime.agent.bind(runtime);\n const commit: PiTaskRuntime['commit'] = runtime.commit.bind(runtime);\n\n // Replaced on the runtime itself and put back when the phase ends, see `observeRunControl`.\n runtime.agent = (context: unknown): Promise<PiAgent> =>\n agent(context).then(resolved =>\n resolved?.tools\n ? {\n ...resolved,\n tools: resolved.tools.map(wrapTool),\n // A call made with `api.executeTool()` resolves its tool among these.\n ...(resolved.callable ? { callable: resolved.callable.map(wrapTool) } : {}),\n }\n : resolved,\n );\n\n runtime.commit = (change: PiCommitChange, context: unknown, ...rest: unknown[]): Promise<void> => {\n let committed: PiToolResultMessage[] = [];\n const observedChange: PiCommitChange = (tx, current) => {\n // A commit can run its change again, so only the attempt that committed counts.\n committed = [];\n return change(observeToolResultEntries(tx, committed), current);\n };\n return commit(observedChange, context, ...rest).then(() => {\n for (const message of committed) {\n results.set(message.toolCallId, message);\n }\n });\n };\n\n return () => {\n runtime.agent = agent;\n runtime.commit = commit;\n for (const call of runs.toolCalls.get(runtime.taskId) ?? []) {\n // A nested call gives its result to the calling tool and commits no result entry.\n const committed = call.callId !== undefined ? results.get(call.callId) : undefined;\n finishToolCall(call, isNested ? call.returned : committed);\n }\n runs.toolCalls.delete(runtime.taskId);\n };\n}\n\n/** Wrap a tool so each call gets a `gen_ai.execute_tool` span. */\nexport function instrumentTool(\n tool: PiTool,\n runs: PiRuns,\n options: GenAiCallOptions<PiDurableCallInfo> & GenAiSpanHooks<PiDurableCallInfo, PiToolExecutionResult>,\n): PiTool {\n const execute = (args: unknown, api: PiToolExecutionApi, context: unknown): Promise<unknown> => {\n const toolCall: PiDurableCallInfo = { operation: 'execute_tool', tool, args, api, context };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, toolCall);\n const phaseCalls = runs.toolCalls.get(api?.taskId);\n // A tool that runs another tool of its agent passes its own `api` on, so the inner call shares\n // the call id. Only the outer call gets the committed result; the inner one ends with its own.\n const calls = phaseCalls?.some(call => call.callId !== undefined && call.callId === api?.callId)\n ? undefined\n : phaseCalls;\n\n return startSpanManual(\n {\n name: `execute_tool ${tool.name}`,\n op: GEN_AI_EXECUTE_TOOL,\n attributes: {\n [SENTRY_ORIGIN]: PI_DURABLE_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'execute_tool',\n [GEN_AI_TOOL_NAME]: tool.name,\n [GEN_AI_TOOL_DESCRIPTION]: tool.description,\n [GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: api?.callId,\n ...(api?.conversationId !== undefined\n ? { [GEN_AI_CONVERSATION_ID]: toSentryConversationId(runs, api.conversationId) }\n : {}),\n ...(recordInputs && args !== undefined ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(args) } : {}),\n },\n },\n async span => {\n const call: PiToolCall = { span, callId: api?.callId, recordOutputs };\n calls?.push(call);\n runGenAiSpanStart(options, span, toolCall);\n try {\n const result = await tool.execute(args, trackOwnedConversations(api, span, runs), context);\n call.endTimestamp = timestampInSeconds();\n call.onSpanEnd = () => runGenAiSpanEnd(options, span, toolCall, { response: result });\n call.returned = { content: result?.output ?? result?.content, isError: result?.isError };\n if (!calls) {\n // No result entry follows a call outside a tool task phase, nor a call that got the api of another call.\n finishToolCall(call, call.returned);\n }\n return result;\n } catch (error) {\n call.endTimestamp = timestampInSeconds();\n call.failed = true;\n call.onSpanEnd = () => runGenAiSpanEnd(options, span, toolCall, { error });\n // pi-durable turns the throw into an error result for the model, so the app never gets a\n // chance to handle it. An aborted call is not a failure.\n if ((context as { abortSignal?: AbortSignal } | undefined)?.abortSignal?.aborted) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n } else {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n if (!BUILT_IN_TOOLS.has(tool)) {\n captureException(error, { mechanism: { handled: false, type: PI_DURABLE_ORIGIN } });\n }\n }\n if (!calls) {\n call.onSpanEnd();\n span.end(call.endTimestamp);\n }\n throw error;\n }\n },\n );\n };\n\n // The proxy's target is an empty object with the tool as prototype, not the tool itself, so a\n // frozen tool does not break the proxy invariants. Members are read bound to the tool, so a\n // method that reads a private field works.\n return new Proxy(Object.create(tool) as PiTool, {\n get(_target, property) {\n return property === 'execute' ? execute : bound(tool, property);\n },\n });\n}\n\nfunction finishToolCall(call: PiToolCall, message: PiToolResultMessage | undefined): void {\n if (message) {\n const result = call.recordOutputs ? piAiContentToString(message.content) : undefined;\n if (result !== undefined) {\n call.span.setAttribute(GEN_AI_TOOL_CALL_RESULT, result);\n }\n if (message.isError && !call.failed) {\n call.span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n }\n call.onSpanEnd?.();\n call.span.end(call.endTimestamp);\n}\n\nfunction observeToolResultEntries(tx: object, committed: PiToolResultMessage[]): object {\n return new Proxy(tx, {\n get(target, property) {\n const value = bound(target, property);\n if (property !== 'appendEntry' || typeof value !== 'function') {\n return value;\n }\n return (\n token: PiEntryToken,\n conversationId: unknown,\n draft: { model?: unknown[] } | undefined,\n ...rest: unknown[]\n ) => {\n const message = token?.kind === PI_TOOL_RESULT_ENTRY_KIND ? draft?.model?.[0] : undefined;\n if (isObjectLike(message)) {\n committed.push(message);\n }\n return value(token, conversationId, draft, ...rest);\n };\n },\n });\n}\n\n/**\n * Record the conversations a tool call creates for itself, the subagent pattern: `api.commit()` with\n * `tx.createConversation()` or `tx.forkConversation()` and `ownership: { kind: 'task', taskId: api.taskId }`.\n */\nfunction trackOwnedConversations(api: PiToolExecutionApi, span: Span, runs: PiRuns): PiToolExecutionApi {\n if (typeof api?.commit !== 'function') {\n return api;\n }\n const commit = api.commit.bind(api);\n\n const trackCreatedConversations = (tx: object): object =>\n new Proxy(tx, {\n get(target, property) {\n const value = bound(target, property);\n if ((property !== 'createConversation' && property !== 'forkConversation') || typeof value !== 'function') {\n return value;\n }\n return async (...args: unknown[]) => {\n const record = (await value(...args)) as { id?: unknown } | undefined;\n const ownership = args.find(\n (arg): arg is { ownership: { kind?: string } } => isObjectLike(arg) && isObjectLike(arg.ownership),\n )?.ownership;\n if (ownership?.kind === 'task' && record?.id !== undefined) {\n if (runs.owners.size >= MAX_TRACKED_PI_RUNS) {\n runs.owners.delete(runs.owners.keys().next().value);\n }\n runs.owners.set(record.id, {\n span: makeWeakRef(span),\n sentryTrace: spanToTraceHeader(span),\n baggage: spanToBaggageHeader(span),\n });\n }\n return record;\n };\n },\n });\n\n return new Proxy(api, {\n get(target, property) {\n if (property !== 'commit') {\n return bound(target, property);\n }\n return (change: (tx: object) => unknown, context: unknown) =>\n commit((tx: object) => change(trackCreatedConversations(tx)), context);\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAkDA,MAAM,iCAAiB,IAAI,QAAgB;AAE3C,SAAgB,gBAAgB,MAAqB;CACnD,IAAI,aAAa,IAAI,GACnB,eAAe,IAAI,IAAI;AAE3B;;;;;;;;AASA,SAAgB,oBACd,SACA,MACA,UACA,UACY;CACZ,MAAM,0BAAU,IAAI,IAAkC;CACtD,KAAK,UAAU,IAAI,QAAQ,QAAQ,CAAC,CAAC;CAErC,MAAM,QAAgC,QAAQ,MAAM,KAAK,OAAO;CAChE,MAAM,SAAkC,QAAQ,OAAO,KAAK,OAAO;CAGnE,QAAQ,SAAS,YACf,MAAM,OAAO,CAAC,CAAC,MAAK,aAClB,UAAU,QACN;EACE,GAAG;EACH,OAAO,SAAS,MAAM,IAAI,QAAQ;EAElC,GAAI,SAAS,WAAW,EAAE,UAAU,SAAS,SAAS,IAAI,QAAQ,EAAE,IAAI,CAAC;CAC3E,IACA,QACN;CAEF,QAAQ,UAAU,QAAwB,SAAkB,GA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AAO,KAAK,OAAO,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK;IAEpD,KAAK,OAAO,IAAI,OAAO,IAAI;KACzB,MAAM,YAAY,IAAI;KACtB,aAAa,kBAAkB,IAAI;KACnC,SAAS,oBAAoB,IAAI;IACnC,CAAC;GACH;GACA,OAAO;EACT;CACF,EACF,CAAC;CAEH,OAAO,IAAI,MAAM,KAAK,EACpB,IAAI,QAAQ,UAAU;EACpB,IAAI,aAAa,UACf,OAAO,MAAM,QAAQ,QAAQ;EAE/B,QAAQ,QAAiC,YACvC,QAAQ,OAAe,OAAO,0BAA0B,EAAE,CAAC,GAAG,OAAO;CACzE,EACF,CAAC;AACH"}
@@ -15,7 +15,8 @@ import "./ai/index.js";
15
15
  import { createFlueInstrumentation } from "./ai/flue/index.js";
16
16
  import { getSqlQueryAttributes, getSqlQuerySummary, getSqlSpanName, sanitizeSqlQuery } from "./utils/sql.js";
17
17
  import { isBun, isCloudflareWorkers, isDeno } from "./utils/runtime.js";
18
+ import { collectInstalledModules } from "./utils/installedModules.js";
18
19
  import { instrumentPostgresJsSql } from "./integrations/postgresjs-wrapper.js";
19
20
  import { applyHonoPatches, earlyPatchHono } from "./integrations/hono/applyPatches.js";
20
21
  import { createHonoRequestMiddleware } from "./integrations/hono/createHonoMiddleware.js";
21
- export { SentryMastraExporter, applyHonoPatches, createFlueInstrumentation, createHonoRequestMiddleware, createLangChainCallbackHandler, earlyPatchHono, getOtlpTracesEndpoint, getSqlQueryAttributes, getSqlQuerySummary, getSqlSpanName, instrumentAnthropicAiClient, instrumentCreateReactAgent, instrumentGoogleGenAIClient, instrumentLangChainEmbeddings, instrumentMistralAiClient, instrumentOpenAiClient, instrumentPostgresJsSql, instrumentStateGraph, instrumentStateGraphCompile, instrumentTypeSafeClient, instrumentWorkersAiClient, isBun, isCloudflareWorkers, isDeno, openTelemetryIntegration, sanitizeSqlQuery, setAsyncLocalStorageAsyncContextStrategy, setHttpServerSpanRouteAttribute };
22
+ export { SentryMastraExporter, applyHonoPatches, collectInstalledModules, createFlueInstrumentation, createHonoRequestMiddleware, createLangChainCallbackHandler, earlyPatchHono, getOtlpTracesEndpoint, getSqlQueryAttributes, getSqlQuerySummary, getSqlSpanName, instrumentAnthropicAiClient, instrumentCreateReactAgent, instrumentGoogleGenAIClient, instrumentLangChainEmbeddings, instrumentMistralAiClient, instrumentOpenAiClient, instrumentPostgresJsSql, instrumentStateGraph, instrumentStateGraphCompile, instrumentTypeSafeClient, instrumentWorkersAiClient, isBun, isCloudflareWorkers, isDeno, openTelemetryIntegration, sanitizeSqlQuery, setAsyncLocalStorageAsyncContextStrategy, setHttpServerSpanRouteAttribute };
@@ -15,6 +15,7 @@ import { isBun, isCloudflareWorkers, isDeno } from "./utils/runtime.js";
15
15
  import { detectOrchestrionSetup } from "./orchestrion/detect.js";
16
16
  import { attachKoaErrorHandler } from "./integrations/koa/koa-error-handler.js";
17
17
  import { getSqlQueryAttributes, getSqlQuerySummary, getSqlSpanName, sanitizeSqlQuery } from "./utils/sql.js";
18
+ import { collectInstalledModules } from "./utils/installedModules.js";
18
19
  import { instrumentPostgresJsSql } from "./integrations/postgresjs-wrapper.js";
19
20
  import { applyHonoPatches, earlyPatchHono } from "./integrations/hono/applyPatches.js";
20
21
  import { createHonoRequestMiddleware } from "./integrations/hono/createHonoMiddleware.js";
@@ -39,7 +40,7 @@ import { cron } from "./cron/index.js";
39
40
  import { BullMQTelemetry } from "./integrations/bullmq/index.js";
40
41
  import { googleGenAIIntegration } from "./integrations/google-genai.js";
41
42
  import { graphqlIntegration } from "./integrations/graphql/index.js";
42
- import { hapiIntegration } from "./integrations/hapi/index.js";
43
+ import { hapiIntegration, setupHapiErrorHandler } from "./integrations/hapi/index.js";
43
44
  import "./integrations/hono/index.js";
44
45
  import { koaIntegration } from "./integrations/koa/index.js";
45
46
  import { honoIntegration, honoMiddleware } from "./integrations/hono/honoIntegration.js";
@@ -56,6 +57,7 @@ import { mastraIntegration } from "./integrations/mastra.js";
56
57
  import { mcpServerIntegration } from "./integrations/mcp-server.js";
57
58
  import { instrumentTunnelServers, makeServeTunnelIntegration } from "./integrations/serveTunnel.js";
58
59
  import { instrumentTunnelServer } from "./utils/tunnelServer.js";
60
+ import { createGetModuleFromFilename } from "./utils/module.js";
59
61
  import { SentryMastraExporter } from "./ai/mastra/index.js";
60
62
  import { lruMemoizerIntegration } from "./integrations/lru-memoizer.js";
61
63
  import { mongoIntegration } from "./integrations/mongodb/index.js";
@@ -72,6 +74,7 @@ import { openAIIntegration } from "./integrations/openai.js";
72
74
  import { postgresIntegration } from "./integrations/pg.js";
73
75
  import { postgresJsIntegration } from "./integrations/postgresjs/index.js";
74
76
  import { neonIntegration } from "./integrations/neon.js";
77
+ import { clickhouseIntegration } from "./integrations/clickhouse.js";
75
78
  import { tediousIntegration } from "./integrations/tedious.js";
76
79
  import { vercelAIIntegration } from "./integrations/vercel-ai/index.js";
77
80
  import { expressIntegration } from "./integrations/express/index.js";
@@ -84,6 +87,6 @@ import { getErrorIntegrations, getTracingIntegrations } from "./integrations/ind
84
87
  * @deprecated This is a temporary export to avoid breaking changes. It will be removed in the next major version.
85
88
  */
86
89
  const attachHapiErrorHandler = attachHapiErrorHandler$1;
87
- export { BullMQTelemetry, SentryMastraExporter, cronExpressionToMonitorConfig as _INTERNAL_cronExpressionToMonitorConfig, instrumentTunnelServer as _INTERNAL_instrumentTunnelServer, instrumentTunnelServers as _INTERNAL_instrumentTunnelServers, amqplibIntegration, anthropicAIIntegration, applyHonoPatches, attachHapiErrorHandler, attachKoaErrorHandler, awsIntegration, bindTracingChannelToSpan, createFlueInstrumentation, createHonoRequestMiddleware, createLangChainCallbackHandler, createSentryWinstonTransport, cron, cronJobIntegration, dataloaderIntegration, detectOrchestrionSetup, tracingChannel as diagnosticsTracingChannel, earlyPatchHono, eveConversationHook, eveIntegration, eveTracePolicy, expressErrorHandler, expressIntegration, fastifyIntegration, firebaseIntegration, flueIntegration, genericPoolIntegration, getErrorIntegrations, getInstrumentedModuleNames, getOtlpTracesEndpoint, getSqlQueryAttributes, getSqlQuerySummary, getSqlSpanName, getTracingIntegrations, googleGenAIIntegration, graphqlIntegration, groqIntegration, hapiIntegration, honoIntegration, honoMiddleware, instrumentAnthropicAiClient, instrumentCreateReactAgent, instrumentGoogleGenAIClient, instrumentLangChainEmbeddings, instrumentMistralAiClient, instrumentOpenAiClient, instrumentPostgresJsSql, instrumentStateGraph, instrumentStateGraphCompile, instrumentTypeSafeClient, instrumentWorkersAiClient, isBun, isCloudflareWorkers, isDeno, kafkaIntegration, knexIntegration, koaIntegration, langChainIntegration, langGraphIntegration, lruMemoizerIntegration, makeServeTunnelIntegration, mastraIntegration, mcpServerIntegration, mistralAIIntegration, mongoIntegration, mongooseIntegration, mysql2Integration, mysqlIntegration, neonIntegration, nitroIntegration, nodeCronIntegration, nodeScheduleIntegration, openAIIntegration, openTelemetryIntegration, orchestrionModuleInjected, piAiIntegration, piDurableIntegration, pinoIntegration, postgresIntegration, postgresJsIntegration, prismaIntegration, redisIntegration, sanitizeSqlQuery, setAsyncLocalStorageAsyncContextStrategy, setHttpServerSpanRouteAttribute, setupExpressErrorHandler, setupFastifyErrorHandler, subscribe as subscribeDiagnosticsChannel, tediousIntegration, togetherAIIntegration, typesafeIntegration, vercelAIIntegration };
90
+ export { BullMQTelemetry, SentryMastraExporter, cronExpressionToMonitorConfig as _INTERNAL_cronExpressionToMonitorConfig, amqplibIntegration, anthropicAIIntegration, applyHonoPatches, attachHapiErrorHandler, attachKoaErrorHandler, awsIntegration, bindTracingChannelToSpan, clickhouseIntegration, collectInstalledModules, createFlueInstrumentation, createGetModuleFromFilename, createHonoRequestMiddleware, createLangChainCallbackHandler, createSentryWinstonTransport, cron, cronJobIntegration, dataloaderIntegration, detectOrchestrionSetup, tracingChannel as diagnosticsTracingChannel, earlyPatchHono, eveConversationHook, eveIntegration, eveTracePolicy, expressErrorHandler, expressIntegration, fastifyIntegration, firebaseIntegration, flueIntegration, genericPoolIntegration, getErrorIntegrations, getInstrumentedModuleNames, getOtlpTracesEndpoint, getSqlQueryAttributes, getSqlQuerySummary, getSqlSpanName, getTracingIntegrations, googleGenAIIntegration, graphqlIntegration, groqIntegration, hapiIntegration, honoIntegration, honoMiddleware, instrumentAnthropicAiClient, instrumentCreateReactAgent, instrumentGoogleGenAIClient, instrumentLangChainEmbeddings, instrumentMistralAiClient, instrumentOpenAiClient, instrumentPostgresJsSql, instrumentStateGraph, instrumentStateGraphCompile, instrumentTunnelServer, instrumentTunnelServers, instrumentTypeSafeClient, instrumentWorkersAiClient, isBun, isCloudflareWorkers, isDeno, kafkaIntegration, knexIntegration, koaIntegration, langChainIntegration, langGraphIntegration, lruMemoizerIntegration, makeServeTunnelIntegration, mastraIntegration, mcpServerIntegration, mistralAIIntegration, mongoIntegration, mongooseIntegration, mysql2Integration, mysqlIntegration, neonIntegration, nitroIntegration, nodeCronIntegration, nodeScheduleIntegration, openAIIntegration, openTelemetryIntegration, orchestrionModuleInjected, piAiIntegration, piDurableIntegration, pinoIntegration, postgresIntegration, postgresJsIntegration, prismaIntegration, redisIntegration, sanitizeSqlQuery, setAsyncLocalStorageAsyncContextStrategy, setHttpServerSpanRouteAttribute, setupExpressErrorHandler, setupFastifyErrorHandler, setupHapiErrorHandler, subscribe as subscribeDiagnosticsChannel, tediousIntegration, togetherAIIntegration, typesafeIntegration, vercelAIIntegration };
88
91
 
89
92
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["_attachHapiErrorHandler"],"sources":["../../src/index.ts"],"sourcesContent":["export * from './exports';\n\n// Exports using diagnostics channels\nexport { detectOrchestrionSetup } from './orchestrion/detect';\n// oxlint-disable-next-line typescript/no-deprecated -- re-exported so the deprecated `setupKoaErrorHandler` can delegate\nexport { attachKoaErrorHandler } from './integrations/koa/koa-error-handler';\nimport { attachHapiErrorHandler as _attachHapiErrorHandler } from './integrations/hapi/hapi-error-handler';\nexport { bindTracingChannelToSpan } from './tracing-channel';\nexport type { TracingChannelPayloadWithSpan } from './tracing-channel';\nexport type { InstrumentationConfig } from './orchestrion/apmTypes';\nexport type { OrchestrionChannelContext } from './orchestrion/types';\n// Runtime target of the bundler-injected module snippet. The snippet imports it\n// from this entry alongside the module's subscriber factory (see\n// `orchestrion/bundler/moduleInjectedTransform.ts`); it is a plain runtime\n// helper with no orchestrion build-time dependency.\nexport { orchestrionModuleInjected } from './utils/moduleInjected';\nexport {\n subscribe as subscribeDiagnosticsChannel,\n tracingChannel as diagnosticsTracingChannel,\n} from './utils/diagnosticsChannel';\nexport { eveConversationHook, eveIntegration, eveTracePolicy } from './eve';\nexport { getInstrumentedModuleNames } from './orchestrion/config';\nexport {\n fastifyIntegration,\n // oxlint-disable-next-line typescript/no-deprecated\n setupFastifyErrorHandler,\n} from './integrations/fastify';\n\n/**\n * @deprecated This is a temporary export to avoid breaking changes. It will be removed in the next major version.\n */\nexport const attachHapiErrorHandler = _attachHapiErrorHandler;\n\n// Integrations\nexport { prismaIntegration } from './integrations/prisma';\nexport { amqplibIntegration } from './integrations/amqplib';\nexport { anthropicAIIntegration } from './integrations/anthropic';\nexport { awsIntegration } from './integrations/aws-sdk';\nexport { dataloaderIntegration } from './integrations/dataloader';\nexport { genericPoolIntegration } from './integrations/generic-pool';\nexport { cronJobIntegration } from './integrations/cron';\nexport type { CronJobIntegrationOptions } from './integrations/cron';\nexport { nodeCronIntegration } from './integrations/node-cron';\nexport type { NodeCronIntegrationOptions } from './integrations/node-cron';\nexport { nodeScheduleIntegration } from './integrations/node-schedule';\nexport type { NodeScheduleIntegrationOptions } from './integrations/node-schedule';\nexport { cronExpressionToMonitorConfig as _INTERNAL_cronExpressionToMonitorConfig } from './utils/cronMonitoring';\nexport { cron } from './cron';\nexport { BullMQTelemetry } from './integrations/bullmq';\nexport { googleGenAIIntegration } from './integrations/google-genai';\nexport { graphqlIntegration } from './integrations/graphql';\nexport { hapiIntegration } from './integrations/hapi';\nexport { honoIntegration, honoMiddleware } from './integrations/hono';\nexport type { HonoIntegrationOptions } from './integrations/hono';\nexport { koaIntegration } from './integrations/koa';\nexport { redisIntegration } from './integrations/redis';\nexport { kafkaIntegration } from './integrations/kafkajs';\nexport { knexIntegration } from './integrations/knex';\nexport { langChainIntegration } from './integrations/langchain';\nexport { langGraphIntegration } from './integrations/langgraph';\nexport { createFlueInstrumentation } from './ai/flue';\nexport { flueIntegration } from './integrations/flue';\nexport { piAiIntegration } from './integrations/pi-ai';\nexport { piDurableIntegration } from './integrations/pi-durable';\nexport type { FlueOptions } from './ai/flue';\nexport { mastraIntegration } from './integrations/mastra';\nexport { mcpServerIntegration } from './integrations/mcp-server';\nexport {\n instrumentTunnelServers as _INTERNAL_instrumentTunnelServers,\n makeServeTunnelIntegration,\n} from './integrations/serveTunnel';\nexport { instrumentTunnelServer as _INTERNAL_instrumentTunnelServer } from './utils/tunnelServer';\nexport { SentryMastraExporter } from './ai/mastra';\nexport { lruMemoizerIntegration } from './integrations/lru-memoizer';\nexport { mongoIntegration } from './integrations/mongodb';\nexport { mongooseIntegration } from './integrations/mongoose';\nexport { mistralAIIntegration } from './integrations/mistral';\nexport { groqIntegration } from './integrations/groq';\nexport { togetherAIIntegration } from './integrations/together-ai';\nexport { typesafeIntegration } from './integrations/typesafe';\nexport { mysqlIntegration } from './integrations/mysql';\nexport { mysql2Integration } from './integrations/mysql2';\nexport { pinoIntegration } from './integrations/pino';\nexport { createSentryWinstonTransport } from './integrations/winston';\nexport { openAIIntegration } from './integrations/openai';\nexport { postgresIntegration } from './integrations/pg';\nexport { postgresJsIntegration } from './integrations/postgresjs';\nexport { neonIntegration } from './integrations/neon';\nexport { tediousIntegration } from './integrations/tedious';\nexport { vercelAIIntegration } from './integrations/vercel-ai';\nexport { expressIntegration } from './integrations/express';\nexport type { ExpressIntegrationOptions } from './integrations/express/types';\n/* oxlint-disable typescript/no-deprecated -- deprecated Express error-handler exports, kept until the next major */\nexport { expressErrorHandler, setupExpressErrorHandler } from './integrations/express/error-handler';\n/* oxlint-enable typescript/no-deprecated */\nexport { firebaseIntegration } from './integrations/firebase';\nexport { nitroIntegration } from './integrations/nitro';\nexport type { NitroIntegrationOptions } from './integrations/nitro';\n\nexport { getTracingIntegrations, getErrorIntegrations } from './integrations';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,yBAAyBA"}
1
+ {"version":3,"file":"index.js","names":["_attachHapiErrorHandler"],"sources":["../../src/index.ts"],"sourcesContent":["export * from './exports';\n\n// Exports using diagnostics channels\nexport { detectOrchestrionSetup } from './orchestrion/detect';\n// oxlint-disable-next-line typescript/no-deprecated -- re-exported so the deprecated `setupKoaErrorHandler` can delegate\nexport { attachKoaErrorHandler } from './integrations/koa/koa-error-handler';\nimport { attachHapiErrorHandler as _attachHapiErrorHandler } from './integrations/hapi/hapi-error-handler';\nexport { bindTracingChannelToSpan } from './tracing-channel';\nexport type { TracingChannelPayloadWithSpan } from './tracing-channel';\nexport type { InstrumentationConfig } from './orchestrion/apmTypes';\nexport type { OrchestrionChannelContext } from './orchestrion/types';\n// Runtime target of the bundler-injected module snippet. The snippet imports it\n// from this entry alongside the module's subscriber factory (see\n// `orchestrion/bundler/moduleInjectedTransform.ts`); it is a plain runtime\n// helper with no orchestrion build-time dependency.\nexport { orchestrionModuleInjected } from './utils/moduleInjected';\nexport {\n subscribe as subscribeDiagnosticsChannel,\n tracingChannel as diagnosticsTracingChannel,\n} from './utils/diagnosticsChannel';\nexport { eveConversationHook, eveIntegration, eveTracePolicy } from './eve';\nexport { getInstrumentedModuleNames } from './orchestrion/config';\nexport {\n fastifyIntegration,\n // oxlint-disable-next-line typescript/no-deprecated\n setupFastifyErrorHandler,\n} from './integrations/fastify';\n\n/**\n * @deprecated This is a temporary export to avoid breaking changes. It will be removed in the next major version.\n */\nexport const attachHapiErrorHandler = _attachHapiErrorHandler;\n\n// Integrations\nexport { prismaIntegration } from './integrations/prisma';\nexport { amqplibIntegration } from './integrations/amqplib';\nexport { anthropicAIIntegration } from './integrations/anthropic';\nexport { awsIntegration } from './integrations/aws-sdk';\nexport { dataloaderIntegration } from './integrations/dataloader';\nexport { genericPoolIntegration } from './integrations/generic-pool';\nexport { cronJobIntegration } from './integrations/cron';\nexport type { CronJobIntegrationOptions } from './integrations/cron';\nexport { nodeCronIntegration } from './integrations/node-cron';\nexport type { NodeCronIntegrationOptions } from './integrations/node-cron';\nexport { nodeScheduleIntegration } from './integrations/node-schedule';\nexport type { NodeScheduleIntegrationOptions } from './integrations/node-schedule';\nexport { cronExpressionToMonitorConfig as _INTERNAL_cronExpressionToMonitorConfig } from './utils/cronMonitoring';\nexport { cron } from './cron';\nexport { BullMQTelemetry } from './integrations/bullmq';\nexport { googleGenAIIntegration } from './integrations/google-genai';\nexport { graphqlIntegration } from './integrations/graphql';\nexport {\n hapiIntegration,\n // oxlint-disable-next-line typescript/no-deprecated\n setupHapiErrorHandler,\n} from './integrations/hapi';\nexport { honoIntegration, honoMiddleware } from './integrations/hono';\nexport type { HonoIntegrationOptions } from './integrations/hono';\nexport { koaIntegration } from './integrations/koa';\nexport { redisIntegration } from './integrations/redis';\nexport { kafkaIntegration } from './integrations/kafkajs';\nexport { knexIntegration } from './integrations/knex';\nexport { langChainIntegration } from './integrations/langchain';\nexport { langGraphIntegration } from './integrations/langgraph';\nexport { createFlueInstrumentation } from './ai/flue';\nexport { flueIntegration } from './integrations/flue';\nexport { piAiIntegration } from './integrations/pi-ai';\nexport { piDurableIntegration } from './integrations/pi-durable';\nexport type { FlueOptions } from './ai/flue';\nexport { mastraIntegration } from './integrations/mastra';\nexport { mcpServerIntegration } from './integrations/mcp-server';\nexport { instrumentTunnelServers, makeServeTunnelIntegration } from './integrations/serveTunnel';\nexport { instrumentTunnelServer } from './utils/tunnelServer';\nexport { createGetModuleFromFilename } from './utils/module';\nexport { SentryMastraExporter } from './ai/mastra';\nexport { lruMemoizerIntegration } from './integrations/lru-memoizer';\nexport { mongoIntegration } from './integrations/mongodb';\nexport { mongooseIntegration } from './integrations/mongoose';\nexport { mistralAIIntegration } from './integrations/mistral';\nexport { groqIntegration } from './integrations/groq';\nexport { togetherAIIntegration } from './integrations/together-ai';\nexport { typesafeIntegration } from './integrations/typesafe';\nexport { mysqlIntegration } from './integrations/mysql';\nexport { mysql2Integration } from './integrations/mysql2';\nexport { pinoIntegration } from './integrations/pino';\nexport { createSentryWinstonTransport } from './integrations/winston';\nexport { openAIIntegration } from './integrations/openai';\nexport { postgresIntegration } from './integrations/pg';\nexport { postgresJsIntegration } from './integrations/postgresjs';\nexport { neonIntegration } from './integrations/neon';\nexport { clickhouseIntegration } from './integrations/clickhouse';\nexport { tediousIntegration } from './integrations/tedious';\nexport { vercelAIIntegration } from './integrations/vercel-ai';\nexport { expressIntegration } from './integrations/express';\nexport type { ExpressIntegrationOptions } from './integrations/express/types';\n/* oxlint-disable typescript/no-deprecated -- deprecated Express error-handler exports, kept until the next major */\nexport { expressErrorHandler, setupExpressErrorHandler } from './integrations/express/error-handler';\n/* oxlint-enable typescript/no-deprecated */\nexport { firebaseIntegration } from './integrations/firebase';\nexport { nitroIntegration } from './integrations/nitro';\nexport type { NitroIntegrationOptions } from './integrations/nitro';\n\nexport { getTracingIntegrations, getErrorIntegrations } from './integrations';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,yBAAyBA"}
@@ -14,8 +14,9 @@ import { SentryMastraExporter } from "./ai/mastra/index.js";
14
14
  import { isBun, isCloudflareWorkers, isDeno } from "./utils/runtime.js";
15
15
  import { createFlueInstrumentation } from "./ai/flue/index.js";
16
16
  import { getSqlQueryAttributes, getSqlQuerySummary, getSqlSpanName, sanitizeSqlQuery } from "./utils/sql.js";
17
+ import { collectInstalledModules } from "./utils/installedModules.js";
17
18
  import { instrumentPostgresJsSql } from "./integrations/postgresjs-wrapper.js";
18
19
  import { applyHonoPatches, earlyPatchHono } from "./integrations/hono/applyPatches.js";
19
20
  import { createHonoRequestMiddleware } from "./integrations/hono/createHonoMiddleware.js";
20
21
  import "./exports.js";
21
- export { SentryMastraExporter, applyHonoPatches, createFlueInstrumentation, createHonoRequestMiddleware, createLangChainCallbackHandler, earlyPatchHono, getOtlpTracesEndpoint, getSqlQueryAttributes, getSqlQuerySummary, getSqlSpanName, instrumentAnthropicAiClient, instrumentCreateReactAgent, instrumentGoogleGenAIClient, instrumentLangChainEmbeddings, instrumentMistralAiClient, instrumentOpenAiClient, instrumentPostgresJsSql, instrumentStateGraph, instrumentStateGraphCompile, instrumentTypeSafeClient, instrumentWorkersAiClient, isBun, isCloudflareWorkers, isDeno, openTelemetryIntegration, sanitizeSqlQuery, setAsyncLocalStorageAsyncContextStrategy, setHttpServerSpanRouteAttribute };
22
+ export { SentryMastraExporter, applyHonoPatches, collectInstalledModules, createFlueInstrumentation, createHonoRequestMiddleware, createLangChainCallbackHandler, earlyPatchHono, getOtlpTracesEndpoint, getSqlQueryAttributes, getSqlQuerySummary, getSqlSpanName, instrumentAnthropicAiClient, instrumentCreateReactAgent, instrumentGoogleGenAIClient, instrumentLangChainEmbeddings, instrumentMistralAiClient, instrumentOpenAiClient, instrumentPostgresJsSql, instrumentStateGraph, instrumentStateGraphCompile, instrumentTypeSafeClient, instrumentWorkersAiClient, isBun, isCloudflareWorkers, isDeno, openTelemetryIntegration, sanitizeSqlQuery, setAsyncLocalStorageAsyncContextStrategy, setHttpServerSpanRouteAttribute };
@@ -1 +1,3 @@
1
- export { wrapServerRequestHandler } from "./utils/wrapServerRequestHandler.js";
1
+ import { wrapServerRequestHandler } from "./utils/wrapServerRequestHandler.js";
2
+ import { addServerTimingTraceHeader } from "./utils/serverTimingTraceHeader.js";
3
+ export { addServerTimingTraceHeader, wrapServerRequestHandler };