@sentry/server-utils 11.15.0 → 11.17.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 (108) hide show
  1. package/build/cjs/chunks/config.js +60 -0
  2. package/build/cjs/chunks/config.js.map +1 -1
  3. package/build/cjs/chunks/exports.js +194 -58
  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 +299 -168
  8. package/build/cjs/index.js.map +1 -1
  9. package/build/cjs/index.request-handler.js +1 -0
  10. package/build/cjs/index.request-handler.js.map +1 -1
  11. package/build/esm/ai/flue/utils.js +1 -0
  12. package/build/esm/ai/flue/utils.js.map +1 -1
  13. package/build/esm/ai/google-genai/decisions.js +29 -1
  14. package/build/esm/ai/google-genai/decisions.js.map +1 -1
  15. package/build/esm/ai/langchain/embeddings.js +23 -8
  16. package/build/esm/ai/langchain/embeddings.js.map +1 -1
  17. package/build/esm/ai/langchain/index.js +41 -30
  18. package/build/esm/ai/langchain/index.js.map +1 -1
  19. package/build/esm/ai/langgraph/agent-span.js +6 -2
  20. package/build/esm/ai/langgraph/agent-span.js.map +1 -1
  21. package/build/esm/ai/langgraph/index.js +5 -1
  22. package/build/esm/ai/langgraph/index.js.map +1 -1
  23. package/build/esm/ai/langgraph/stream.js +4 -1
  24. package/build/esm/ai/langgraph/stream.js.map +1 -1
  25. package/build/esm/ai/openai/mapping.js +48 -1
  26. package/build/esm/ai/openai/mapping.js.map +1 -1
  27. package/build/esm/ai/pi-durable/index.js +10 -13
  28. package/build/esm/ai/pi-durable/index.js.map +1 -1
  29. package/build/esm/ai/pi-durable/runs.js +6 -5
  30. package/build/esm/ai/pi-durable/runs.js.map +1 -1
  31. package/build/esm/ai/pi-durable/tools.js +21 -17
  32. package/build/esm/ai/pi-durable/tools.js.map +1 -1
  33. package/build/esm/index.js +3 -2
  34. package/build/esm/index.js.map +1 -1
  35. package/build/esm/integrations/clickhouse-sql.js +31 -0
  36. package/build/esm/integrations/clickhouse-sql.js.map +1 -0
  37. package/build/esm/integrations/clickhouse.js +88 -0
  38. package/build/esm/integrations/clickhouse.js.map +1 -0
  39. package/build/esm/integrations/express/instrumentation.js +1 -0
  40. package/build/esm/integrations/express/instrumentation.js.map +1 -1
  41. package/build/esm/integrations/fastify/instrumentation.js +3 -1
  42. package/build/esm/integrations/fastify/instrumentation.js.map +1 -1
  43. package/build/esm/integrations/hapi/index.js +15 -1
  44. package/build/esm/integrations/hapi/index.js.map +1 -1
  45. package/build/esm/integrations/index.js +2 -0
  46. package/build/esm/integrations/index.js.map +1 -1
  47. package/build/esm/integrations/langchain.js +10 -3
  48. package/build/esm/integrations/langchain.js.map +1 -1
  49. package/build/esm/orchestrion/channels.js +2 -0
  50. package/build/esm/orchestrion/channels.js.map +1 -1
  51. package/build/esm/orchestrion/config/channel-integration-definitions.js +8 -0
  52. package/build/esm/orchestrion/config/channel-integration-definitions.js.map +1 -1
  53. package/build/esm/orchestrion/config/clickhouse.js +51 -0
  54. package/build/esm/orchestrion/config/clickhouse.js.map +1 -0
  55. package/build/esm/orchestrion/config/index.js +2 -0
  56. package/build/esm/orchestrion/config/index.js.map +1 -1
  57. package/build/esm/package.json +1 -1
  58. package/build/esm/utils/sql.js +37 -16
  59. package/build/esm/utils/sql.js.map +1 -1
  60. package/build/esm/utils/wrapServerRequestHandler.js +2 -1
  61. package/build/esm/utils/wrapServerRequestHandler.js.map +1 -1
  62. package/build/types/ai/flue/utils.d.ts.map +1 -1
  63. package/build/types/ai/google-genai/decisions.d.ts.map +1 -1
  64. package/build/types/ai/langchain/embeddings.d.ts +2 -2
  65. package/build/types/ai/langchain/embeddings.d.ts.map +1 -1
  66. package/build/types/ai/langchain/index.d.ts.map +1 -1
  67. package/build/types/ai/langchain/types.d.ts +8 -4
  68. package/build/types/ai/langchain/types.d.ts.map +1 -1
  69. package/build/types/ai/langgraph/agent-span.d.ts +5 -2
  70. package/build/types/ai/langgraph/agent-span.d.ts.map +1 -1
  71. package/build/types/ai/langgraph/index.d.ts.map +1 -1
  72. package/build/types/ai/langgraph/stream.d.ts.map +1 -1
  73. package/build/types/ai/langgraph/types.d.ts +10 -2
  74. package/build/types/ai/langgraph/types.d.ts.map +1 -1
  75. package/build/types/ai/openai/mapping.d.ts.map +1 -1
  76. package/build/types/ai/pi-durable/index.d.ts.map +1 -1
  77. package/build/types/ai/pi-durable/runs.d.ts +4 -2
  78. package/build/types/ai/pi-durable/runs.d.ts.map +1 -1
  79. package/build/types/ai/pi-durable/tools.d.ts +4 -6
  80. package/build/types/ai/pi-durable/tools.d.ts.map +1 -1
  81. package/build/types/ai/pi-durable/types.d.ts +10 -1
  82. package/build/types/ai/pi-durable/types.d.ts.map +1 -1
  83. package/build/types/ai/types.d.ts +1 -1
  84. package/build/types/ai/types.d.ts.map +1 -1
  85. package/build/types/index.d.ts +2 -1
  86. package/build/types/index.d.ts.map +1 -1
  87. package/build/types/integrations/clickhouse-sql.d.ts +8 -0
  88. package/build/types/integrations/clickhouse-sql.d.ts.map +1 -0
  89. package/build/types/integrations/clickhouse.d.ts +11 -0
  90. package/build/types/integrations/clickhouse.d.ts.map +1 -0
  91. package/build/types/integrations/express/types.d.ts +1 -0
  92. package/build/types/integrations/express/types.d.ts.map +1 -1
  93. package/build/types/integrations/fastify/instrumentation.d.ts.map +1 -1
  94. package/build/types/integrations/hapi/index.d.ts +12 -0
  95. package/build/types/integrations/hapi/index.d.ts.map +1 -1
  96. package/build/types/integrations/index.d.ts.map +1 -1
  97. package/build/types/integrations/langchain.d.ts.map +1 -1
  98. package/build/types/orchestrion/channels.d.ts +12 -0
  99. package/build/types/orchestrion/channels.d.ts.map +1 -1
  100. package/build/types/orchestrion/config/channel-integration-definitions.d.ts +3 -0
  101. package/build/types/orchestrion/config/channel-integration-definitions.d.ts.map +1 -1
  102. package/build/types/orchestrion/config/clickhouse.d.ts +18 -0
  103. package/build/types/orchestrion/config/clickhouse.d.ts.map +1 -0
  104. package/build/types/orchestrion/config/index.d.ts.map +1 -1
  105. package/build/types/utils/sql.d.ts +28 -3
  106. package/build/types/utils/sql.d.ts.map +1 -1
  107. package/build/types/utils/wrapServerRequestHandler.d.ts.map +1 -1
  108. package/package.json +4 -4
@@ -162,6 +162,7 @@ async function wrapServerRequestHandler(config, handler) {
162
162
  Object.assign(attributes, (0, _sentry_core.httpHeadersToSpanAttributes)(headers, dataCollection));
163
163
  Object.assign(attributes, config.attributes);
164
164
  attributes[_sentry_conventions_attributes.SENTRY_OP] = _sentry_conventions_op.HTTP_SERVER;
165
+ attributes[_sentry_conventions_attributes.SENTRY_KIND] = "server";
165
166
  return (0, _sentry_core.startSpanManual)({
166
167
  name,
167
168
  attributes
@@ -1 +1 @@
1
- {"version":3,"file":"index.request-handler.js","names":["isError","DEBUG_BUILD","debug","captureException","winterCGRequestToRequestData","isServedTunnelRequest","startRequestSession","classifyResponseStreaming","safeCallback","DEBUG_BUILD","captureBodyFromWinterCGRequest","parseStringToURLObject","continueTrace","getHttpSpanDetailsFromUrlObject","SENTRY_SEGMENT_NAME_SOURCE","hasSpanStreamingEnabled","HTTP_SPAN_NAME_FALLBACK","HTTP_REQUEST_BODY_SIZE","USER_AGENT_ORIGINAL","winterCGHeadersToDict","getClientIPAddress","CLIENT_ADDRESS","CLIENT_PORT","NETWORK_PROTOCOL_NAME","httpHeadersToSpanAttributes","SENTRY_OP","HTTP_SERVER","startSpanManual","SPAN_STATUS_ERROR","setHttpStatus","getCurrentScope","withIsolationScope","withScope","hasSpansEnabled","isStaticAssetRequest"],"sources":["../../src/utils/monitorStream.ts","../../src/utils/wrapServerRequestHandler.ts"],"sourcesContent":["import { debug, isError } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\n\n/**\n * Monitor the source without reading ahead or treating cancellation as a source failure.\n *\n * `onDone` runs once, while the returned stream is still open: before it closes, before it errors,\n * or when the consumer cancels it. A runtime can end the request when the response body closes\n * (Cloudflare Workers then reject `waitUntil`), so work that `onDone` starts must begin first.\n */\nexport function monitorStream(\n stream: ReadableStream<Uint8Array>,\n onDone: () => void,\n onError: (error: unknown) => void,\n): ReadableStream<Uint8Array> {\n let reader: ReadableStreamDefaultReader<Uint8Array>;\n let finished = false;\n const finish = (error?: { error: unknown }): void => {\n if (finished) {\n return;\n }\n finished = true;\n // A callback that throws must not fail the response body.\n try {\n // A source that stops on `request.signal` errors with an `AbortError` when the client\n // disconnects, which is a cancellation too.\n if (error && !(isError(error.error) && error.error.name === 'AbortError')) {\n onError(error.error);\n }\n onDone();\n } catch (e) {\n DEBUG_BUILD && debug.error('Error when a monitored stream finished:', e);\n }\n };\n\n return new ReadableStream<Uint8Array>(\n {\n // Locks the source only once the stream exists, so a constructor that throws leaves it usable.\n start() {\n reader = stream.getReader();\n // A source can fail while no one reads from it. A cancelled reader closes normally; only a\n // source failure should be captured as an error.\n void reader.closed.then(\n () => finish(),\n error => finish({ error }),\n );\n },\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n finish();\n controller.close();\n reader.releaseLock();\n } else {\n controller.enqueue(value);\n }\n } catch (error) {\n finish({ error });\n controller.error(error);\n reader.releaseLock();\n }\n },\n async cancel(reason) {\n finish();\n try {\n await reader.cancel(reason);\n } finally {\n reader.releaseLock();\n }\n },\n },\n { highWaterMark: 0 },\n );\n}\n","import {\n CLIENT_ADDRESS,\n CLIENT_PORT,\n HTTP_REQUEST_BODY_SIZE,\n NETWORK_PROTOCOL_NAME,\n SENTRY_OP,\n SENTRY_SEGMENT_NAME_SOURCE,\n USER_AGENT_ORIGINAL,\n} from '@sentry/conventions/attributes';\nimport { HTTP_SERVER } from '@sentry/conventions/op';\nimport type { Client, Mechanism, Scope, SpanAttributes } from '@sentry/core';\nimport {\n captureBodyFromWinterCGRequest,\n captureException,\n continueTrace,\n getCurrentScope,\n getHttpSpanDetailsFromUrlObject,\n hasSpansEnabled,\n hasSpanStreamingEnabled,\n httpHeadersToSpanAttributes,\n HTTP_SPAN_NAME_FALLBACK,\n parseStringToURLObject,\n safeCallback,\n setHttpStatus,\n SPAN_STATUS_ERROR,\n startSpanManual,\n winterCGHeadersToDict,\n winterCGRequestToRequestData,\n withIsolationScope,\n withScope,\n} from '@sentry/core';\nimport type { ServerRequestOptions } from '@sentry/core/server';\nimport {\n _INTERNAL_isServedTunnelRequest as isServedTunnelRequest,\n classifyResponseStreaming,\n getClientIPAddress,\n isStaticAssetRequest,\n startRequestSession,\n} from '@sentry/core/server';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { monitorStream } from './monitorStream';\n\nexport interface ServerRequestHandlerConfig {\n request: Request;\n client: Client;\n /** The isolation scope of this request. */\n isolationScope: Scope;\n /** The options of the runtime's integration for incoming requests. */\n options: ServerRequestOptions<Request, Response> | undefined;\n /** Origin of the span, e.g. `auto.http.deno`. */\n origin: string;\n /** Mechanism of errors that the handler or the response stream throws. Omit to not capture them. */\n mechanism?: Mechanism;\n /** The address and port of the socket, if the runtime knows them. */\n getSocketAddress?: () => { address: string; port?: number } | undefined;\n /** The matched route of the server framework, e.g. `/users/:id`. Sets `http.route` and the span name. */\n routeName?: string;\n /** Span attributes that only the runtime knows, e.g. the route parameters. */\n attributes?: SpanAttributes;\n /**\n * Called in the scope of the continued trace, before the span starts. Lets the runtime continue\n * its own trace, e.g. the trace that Cloudflare exports for the invocation.\n */\n onTraceContinued?: () => void;\n /** Whether the response streams. Return `undefined` to use the default classification. */\n isStreamingResponse?: (response: Response) => boolean | undefined;\n /**\n * Called once when the request is done: when the response is returned, when a streamed body\n * finishes, or when the handler throws (then without a response).\n */\n onDone?: (response: Response | undefined) => void;\n}\n\n/**\n * Wraps a handler of a web `Request`, as used by `Deno.serve`, `Bun.serve` and Cloudflare Workers.\n *\n * It records the request session, attaches the request data and body, continues the incoming\n * trace, creates the `http.server` span, and captures errors that the handler throws. The rules\n * follow core's `node:http` server code:\n *\n * - `OPTIONS` and `HEAD` requests get no span and no body capture.\n * - The static asset filter applies only to `GET`.\n * - The span and the session of a streamed response end when the stream finishes.\n *\n * The handler can return no response, as Bun's `fetch` does after a WebSocket upgrade.\n */\nexport async function wrapServerRequestHandler<R extends Response | undefined = Response>(\n config: ServerRequestHandlerConfig,\n handler: () => R | Promise<R>,\n): Promise<R> {\n const { request, client, isolationScope, options, mechanism } = config;\n\n const method = request.method.toUpperCase();\n const captureError = (error: unknown): void => {\n if (mechanism) {\n captureException(error, { mechanism });\n }\n };\n\n const socketAddress = config.getSocketAddress?.();\n // Without `AsyncLocalStorage`, all requests share one isolation scope, so clear what an earlier\n // request left on it: the merge keeps its body, and its response context would stay set.\n isolationScope.setSDKProcessingMetadata({\n normalizedRequest: { ...winterCGRequestToRequestData(request), data: undefined },\n ipAddress: socketAddress?.address,\n });\n isolationScope.setContext('response', null);\n\n // Tunnel requests get no session, body or span, whether the SDK or the app answers them. The app answers them with\n // `intercept: false`, from its own code, so its errors are still captured.\n if (isServedTunnelRequest(request, client)) {\n let response: R | undefined;\n try {\n response = await handler();\n return response;\n } catch (e) {\n captureError(e);\n throw e;\n } finally {\n config.onDone?.(response);\n }\n }\n\n const endSession = options?.sessions\n ? startRequestSession(client, {\n requestIsolationScope: isolationScope,\n sessionFlushingDelayMS: options.sessionFlushingDelayMS,\n })\n : undefined;\n const finish = (response: Response | undefined): void => {\n endSession?.();\n config.onDone?.(response);\n };\n const isStreamingResponse = (response: Response): boolean => {\n const classification = config.isStreamingResponse?.(response);\n return typeof classification === 'boolean' ? classification : classifyResponseStreaming(response).isStreaming;\n };\n\n if (method === 'OPTIONS' || method === 'HEAD') {\n let response: R | undefined;\n try {\n response = await handler();\n return response;\n } catch (e) {\n captureError(e);\n throw e;\n } finally {\n finish(response);\n }\n }\n\n const dataCollection = client.getDataCollectionOptions();\n const effectiveBodySize =\n options?.maxRequestBodySize ?? (dataCollection.httpBodies.includes('incomingRequest') ? 'medium' : 'none');\n const ignoreRequestBody = options?.ignoreRequestBody;\n if (\n method !== 'GET' &&\n effectiveBodySize !== 'none' &&\n // If the filter throws, skip the body so it cannot leak data the filter was meant to hide.\n !(\n ignoreRequestBody &&\n safeCallback(\n DEBUG_BUILD ? 'Error in `ignoreRequestBody`, skipping the body:' : '',\n () => ignoreRequestBody(request.url, request),\n () => true,\n )\n )\n ) {\n await captureBodyFromWinterCGRequest(request, isolationScope, effectiveBodySize);\n }\n\n const urlObject = parseStringToURLObject(request.url);\n const urlPath = urlObject ? `${urlObject.pathname}${urlObject.search}` : '/';\n const createSpan = shouldCreateSpan(client, options, request, urlPath);\n\n return continueTrace(\n {\n sentryTrace: request.headers.get('sentry-trace') || '',\n baggage: request.headers.get('baggage'),\n },\n async () => {\n config.onTraceContinued?.();\n\n if (!createSpan) {\n let response: R;\n try {\n response = await handler();\n } catch (e) {\n captureError(e);\n finish(undefined);\n throw e;\n }\n if (response) {\n isolationScope.setContext('response', { status_code: response.status });\n }\n const inRequestScope = bindToRequestScope(isolationScope);\n return onResponseDone(\n response,\n !!response && isStreamingResponse(response),\n inRequestScope(() => finish(response)),\n inRequestScope(captureError),\n );\n }\n\n const [rawName, attributes] = getHttpSpanDetailsFromUrlObject(\n urlObject,\n 'server',\n config.origin,\n request,\n config.routeName,\n client,\n );\n // With span streaming, span names have to be low cardinality, so we can't fall back to the URL.\n // A `route` source means the name already is (e.g. the `/` path), so it is kept as-is.\n const name =\n attributes[SENTRY_SEGMENT_NAME_SOURCE] === 'route' || !hasSpanStreamingEnabled(client)\n ? rawName\n : method || HTTP_SPAN_NAME_FALLBACK;\n\n const contentLength = request.headers.get('content-length');\n if (contentLength) {\n attributes[HTTP_REQUEST_BODY_SIZE] = parseInt(contentLength, 10);\n }\n const userAgent = request.headers.get('user-agent');\n if (userAgent) {\n attributes[USER_AGENT_ORIGINAL] = userAgent;\n }\n\n const headers = winterCGHeadersToDict(request.headers);\n if (dataCollection.userInfo) {\n // `client.address` is the originating client, so a forwarding header wins over the socket, which\n // behind a proxy holds the proxy's address. The socket port is the proxy's too, so `client.port`\n // stays unset then.\n const forwardedAddress = getClientIPAddress(headers);\n if (forwardedAddress) {\n attributes[CLIENT_ADDRESS] = forwardedAddress;\n } else if (socketAddress) {\n attributes[CLIENT_ADDRESS] = socketAddress.address;\n if (socketAddress.port !== undefined) {\n attributes[CLIENT_PORT] = socketAddress.port;\n }\n }\n }\n\n // describes the OSI application-layer protocol (http), not the scheme (might be https)\n attributes[NETWORK_PROTOCOL_NAME] = 'http';\n Object.assign(attributes, httpHeadersToSpanAttributes(headers, dataCollection));\n Object.assign(attributes, config.attributes);\n attributes[SENTRY_OP] = HTTP_SERVER;\n\n return startSpanManual({ name, attributes }, async span => {\n const { onSpanCreated, onSpanEnd } = options ?? {};\n if (onSpanCreated) {\n safeCallback(\n DEBUG_BUILD ? 'Error in `onSpanCreated`:' : '',\n () => onSpanCreated(span, request),\n () => undefined,\n );\n }\n\n let response: R;\n try {\n response = await handler();\n } catch (e) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n span.end();\n captureError(e);\n finish(undefined);\n throw e;\n }\n\n if (response) {\n setHttpStatus(span, response.status);\n isolationScope.setContext('response', { status_code: response.status });\n span.setAttributes(\n httpHeadersToSpanAttributes(responseHeadersToDict(response.headers), dataCollection, 'response'),\n );\n }\n\n const inRequestScope = bindToRequestScope(isolationScope);\n return onResponseDone(\n response,\n !!response && isStreamingResponse(response),\n inRequestScope(() => {\n if (onSpanEnd && response) {\n safeCallback(\n DEBUG_BUILD ? 'Error in `onSpanEnd`:' : '',\n () => onSpanEnd(span, request, response),\n () => undefined,\n );\n }\n span.end();\n finish(response);\n }),\n inRequestScope((error: unknown) => {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n captureError(error);\n }),\n );\n });\n },\n );\n}\n\n/**\n * Returns a function that binds a callback to the request's isolation scope and the current scope.\n *\n * A streamed body finishes after the handler returns. Without `AsyncLocalStorage` (Cloudflare\n * Workers without `nodejs_compat`), its callbacks then run outside the request's scopes, where\n * `getClient()` finds no client: the segment span would be sent as a transaction, and a captured\n * error would not update the request session.\n */\nfunction bindToRequestScope(\n isolationScope: Scope,\n): <A extends unknown[]>(fn: (...args: A) => void) => (...args: A) => void {\n const scope = getCurrentScope();\n return fn =>\n (...args) =>\n withIsolationScope(isolationScope, () => withScope(scope, () => fn(...args)));\n}\n\nfunction shouldCreateSpan(\n client: Client,\n options: ServerRequestOptions<Request, Response> | undefined,\n request: Request,\n urlPath: string,\n): boolean {\n if (!(options?.spans ?? hasSpansEnabled(client.getOptions()))) {\n return false;\n }\n if (options?.ignoreStaticAssets && request.method.toUpperCase() === 'GET' && isStaticAssetRequest(urlPath)) {\n return false;\n }\n const ignoreIncomingRequests = options?.ignoreIncomingRequests;\n return !(\n ignoreIncomingRequests &&\n safeCallback(\n DEBUG_BUILD ? 'Error in `ignoreIncomingRequests`, creating the span:' : '',\n () => ignoreIncomingRequests(urlPath, request),\n () => false,\n )\n );\n}\n\n/**\n * Calls `onDone` when the response is done: at once, or when a streamed body finishes.\n * Returns the response to send.\n */\nfunction onResponseDone<R extends Response | undefined>(\n response: R,\n isStreaming: boolean,\n onDone: () => void,\n onStreamError: (error: unknown) => void,\n): R {\n if (isStreaming && response?.body && !response.body.locked) {\n try {\n // Passing the original response as the init keeps its status, status text and headers, and\n // on Cloudflare also `encodeBody: 'manual'`, so workerd does not compress a compressed body again.\n return new Response(monitorStream(response.body, onDone, onStreamError), response) as R;\n } catch {\n // Workers with a compatibility date before 2022-11-30 and without the\n // `streams_enable_constructors` flag cannot construct a `ReadableStream`, so end at once.\n }\n }\n onDone();\n return response;\n}\n\n// `Headers.forEach` lists each `Set-Cookie` header on its own, so a plain dict keeps only the last one.\nfunction responseHeadersToDict(headers: Headers): Record<string, string | string[]> {\n const dict: Record<string, string | string[]> = winterCGHeadersToDict(headers);\n const setCookie = typeof headers.getSetCookie === 'function' ? headers.getSetCookie() : [];\n if (setCookie.length) {\n dict['set-cookie'] = setCookie;\n }\n return dict;\n}\n"],"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ACzF,IAAI,UAAU,QACZ,KAAK,gBAAgB;CAEvB,OAAO;AACT"}
1
+ {"version":3,"file":"index.request-handler.js","names":["isError","DEBUG_BUILD","debug","captureException","winterCGRequestToRequestData","isServedTunnelRequest","startRequestSession","classifyResponseStreaming","safeCallback","DEBUG_BUILD","captureBodyFromWinterCGRequest","parseStringToURLObject","continueTrace","getHttpSpanDetailsFromUrlObject","SENTRY_SEGMENT_NAME_SOURCE","hasSpanStreamingEnabled","HTTP_SPAN_NAME_FALLBACK","HTTP_REQUEST_BODY_SIZE","USER_AGENT_ORIGINAL","winterCGHeadersToDict","getClientIPAddress","CLIENT_ADDRESS","CLIENT_PORT","NETWORK_PROTOCOL_NAME","httpHeadersToSpanAttributes","SENTRY_OP","HTTP_SERVER","SENTRY_KIND","startSpanManual","SPAN_STATUS_ERROR","setHttpStatus","getCurrentScope","withIsolationScope","withScope","hasSpansEnabled","isStaticAssetRequest"],"sources":["../../src/utils/monitorStream.ts","../../src/utils/wrapServerRequestHandler.ts"],"sourcesContent":["import { debug, isError } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\n\n/**\n * Monitor the source without reading ahead or treating cancellation as a source failure.\n *\n * `onDone` runs once, while the returned stream is still open: before it closes, before it errors,\n * or when the consumer cancels it. A runtime can end the request when the response body closes\n * (Cloudflare Workers then reject `waitUntil`), so work that `onDone` starts must begin first.\n */\nexport function monitorStream(\n stream: ReadableStream<Uint8Array>,\n onDone: () => void,\n onError: (error: unknown) => void,\n): ReadableStream<Uint8Array> {\n let reader: ReadableStreamDefaultReader<Uint8Array>;\n let finished = false;\n const finish = (error?: { error: unknown }): void => {\n if (finished) {\n return;\n }\n finished = true;\n // A callback that throws must not fail the response body.\n try {\n // A source that stops on `request.signal` errors with an `AbortError` when the client\n // disconnects, which is a cancellation too.\n if (error && !(isError(error.error) && error.error.name === 'AbortError')) {\n onError(error.error);\n }\n onDone();\n } catch (e) {\n DEBUG_BUILD && debug.error('Error when a monitored stream finished:', e);\n }\n };\n\n return new ReadableStream<Uint8Array>(\n {\n // Locks the source only once the stream exists, so a constructor that throws leaves it usable.\n start() {\n reader = stream.getReader();\n // A source can fail while no one reads from it. A cancelled reader closes normally; only a\n // source failure should be captured as an error.\n void reader.closed.then(\n () => finish(),\n error => finish({ error }),\n );\n },\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n finish();\n controller.close();\n reader.releaseLock();\n } else {\n controller.enqueue(value);\n }\n } catch (error) {\n finish({ error });\n controller.error(error);\n reader.releaseLock();\n }\n },\n async cancel(reason) {\n finish();\n try {\n await reader.cancel(reason);\n } finally {\n reader.releaseLock();\n }\n },\n },\n { highWaterMark: 0 },\n );\n}\n","import {\n CLIENT_ADDRESS,\n CLIENT_PORT,\n HTTP_REQUEST_BODY_SIZE,\n NETWORK_PROTOCOL_NAME,\n SENTRY_KIND,\n SENTRY_OP,\n SENTRY_SEGMENT_NAME_SOURCE,\n USER_AGENT_ORIGINAL,\n} from '@sentry/conventions/attributes';\nimport { HTTP_SERVER } from '@sentry/conventions/op';\nimport type { Client, Mechanism, Scope, SpanAttributes } from '@sentry/core';\nimport {\n captureBodyFromWinterCGRequest,\n captureException,\n continueTrace,\n getCurrentScope,\n getHttpSpanDetailsFromUrlObject,\n hasSpansEnabled,\n hasSpanStreamingEnabled,\n httpHeadersToSpanAttributes,\n HTTP_SPAN_NAME_FALLBACK,\n parseStringToURLObject,\n safeCallback,\n setHttpStatus,\n SPAN_STATUS_ERROR,\n startSpanManual,\n winterCGHeadersToDict,\n winterCGRequestToRequestData,\n withIsolationScope,\n withScope,\n} from '@sentry/core';\nimport type { ServerRequestOptions } from '@sentry/core/server';\nimport {\n _INTERNAL_isServedTunnelRequest as isServedTunnelRequest,\n classifyResponseStreaming,\n getClientIPAddress,\n isStaticAssetRequest,\n startRequestSession,\n} from '@sentry/core/server';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { monitorStream } from './monitorStream';\n\nexport interface ServerRequestHandlerConfig {\n request: Request;\n client: Client;\n /** The isolation scope of this request. */\n isolationScope: Scope;\n /** The options of the runtime's integration for incoming requests. */\n options: ServerRequestOptions<Request, Response> | undefined;\n /** Origin of the span, e.g. `auto.http.deno`. */\n origin: string;\n /** Mechanism of errors that the handler or the response stream throws. Omit to not capture them. */\n mechanism?: Mechanism;\n /** The address and port of the socket, if the runtime knows them. */\n getSocketAddress?: () => { address: string; port?: number } | undefined;\n /** The matched route of the server framework, e.g. `/users/:id`. Sets `http.route` and the span name. */\n routeName?: string;\n /** Span attributes that only the runtime knows, e.g. the route parameters. */\n attributes?: SpanAttributes;\n /**\n * Called in the scope of the continued trace, before the span starts. Lets the runtime continue\n * its own trace, e.g. the trace that Cloudflare exports for the invocation.\n */\n onTraceContinued?: () => void;\n /** Whether the response streams. Return `undefined` to use the default classification. */\n isStreamingResponse?: (response: Response) => boolean | undefined;\n /**\n * Called once when the request is done: when the response is returned, when a streamed body\n * finishes, or when the handler throws (then without a response).\n */\n onDone?: (response: Response | undefined) => void;\n}\n\n/**\n * Wraps a handler of a web `Request`, as used by `Deno.serve`, `Bun.serve` and Cloudflare Workers.\n *\n * It records the request session, attaches the request data and body, continues the incoming\n * trace, creates the `http.server` span, and captures errors that the handler throws. The rules\n * follow core's `node:http` server code:\n *\n * - `OPTIONS` and `HEAD` requests get no span and no body capture.\n * - The static asset filter applies only to `GET`.\n * - The span and the session of a streamed response end when the stream finishes.\n *\n * The handler can return no response, as Bun's `fetch` does after a WebSocket upgrade.\n */\nexport async function wrapServerRequestHandler<R extends Response | undefined = Response>(\n config: ServerRequestHandlerConfig,\n handler: () => R | Promise<R>,\n): Promise<R> {\n const { request, client, isolationScope, options, mechanism } = config;\n\n const method = request.method.toUpperCase();\n const captureError = (error: unknown): void => {\n if (mechanism) {\n captureException(error, { mechanism });\n }\n };\n\n const socketAddress = config.getSocketAddress?.();\n // Without `AsyncLocalStorage`, all requests share one isolation scope, so clear what an earlier\n // request left on it: the merge keeps its body, and its response context would stay set.\n isolationScope.setSDKProcessingMetadata({\n normalizedRequest: { ...winterCGRequestToRequestData(request), data: undefined },\n ipAddress: socketAddress?.address,\n });\n isolationScope.setContext('response', null);\n\n // Tunnel requests get no session, body or span, whether the SDK or the app answers them. The app answers them with\n // `intercept: false`, from its own code, so its errors are still captured.\n if (isServedTunnelRequest(request, client)) {\n let response: R | undefined;\n try {\n response = await handler();\n return response;\n } catch (e) {\n captureError(e);\n throw e;\n } finally {\n config.onDone?.(response);\n }\n }\n\n const endSession = options?.sessions\n ? startRequestSession(client, {\n requestIsolationScope: isolationScope,\n sessionFlushingDelayMS: options.sessionFlushingDelayMS,\n })\n : undefined;\n const finish = (response: Response | undefined): void => {\n endSession?.();\n config.onDone?.(response);\n };\n const isStreamingResponse = (response: Response): boolean => {\n const classification = config.isStreamingResponse?.(response);\n return typeof classification === 'boolean' ? classification : classifyResponseStreaming(response).isStreaming;\n };\n\n if (method === 'OPTIONS' || method === 'HEAD') {\n let response: R | undefined;\n try {\n response = await handler();\n return response;\n } catch (e) {\n captureError(e);\n throw e;\n } finally {\n finish(response);\n }\n }\n\n const dataCollection = client.getDataCollectionOptions();\n const effectiveBodySize =\n options?.maxRequestBodySize ?? (dataCollection.httpBodies.includes('incomingRequest') ? 'medium' : 'none');\n const ignoreRequestBody = options?.ignoreRequestBody;\n if (\n method !== 'GET' &&\n effectiveBodySize !== 'none' &&\n // If the filter throws, skip the body so it cannot leak data the filter was meant to hide.\n !(\n ignoreRequestBody &&\n safeCallback(\n DEBUG_BUILD ? 'Error in `ignoreRequestBody`, skipping the body:' : '',\n () => ignoreRequestBody(request.url, request),\n () => true,\n )\n )\n ) {\n await captureBodyFromWinterCGRequest(request, isolationScope, effectiveBodySize);\n }\n\n const urlObject = parseStringToURLObject(request.url);\n const urlPath = urlObject ? `${urlObject.pathname}${urlObject.search}` : '/';\n const createSpan = shouldCreateSpan(client, options, request, urlPath);\n\n return continueTrace(\n {\n sentryTrace: request.headers.get('sentry-trace') || '',\n baggage: request.headers.get('baggage'),\n },\n async () => {\n config.onTraceContinued?.();\n\n if (!createSpan) {\n let response: R;\n try {\n response = await handler();\n } catch (e) {\n captureError(e);\n finish(undefined);\n throw e;\n }\n if (response) {\n isolationScope.setContext('response', { status_code: response.status });\n }\n const inRequestScope = bindToRequestScope(isolationScope);\n return onResponseDone(\n response,\n !!response && isStreamingResponse(response),\n inRequestScope(() => finish(response)),\n inRequestScope(captureError),\n );\n }\n\n const [rawName, attributes] = getHttpSpanDetailsFromUrlObject(\n urlObject,\n 'server',\n config.origin,\n request,\n config.routeName,\n client,\n );\n // With span streaming, span names have to be low cardinality, so we can't fall back to the URL.\n // A `route` source means the name already is (e.g. the `/` path), so it is kept as-is.\n const name =\n attributes[SENTRY_SEGMENT_NAME_SOURCE] === 'route' || !hasSpanStreamingEnabled(client)\n ? rawName\n : method || HTTP_SPAN_NAME_FALLBACK;\n\n const contentLength = request.headers.get('content-length');\n if (contentLength) {\n attributes[HTTP_REQUEST_BODY_SIZE] = parseInt(contentLength, 10);\n }\n const userAgent = request.headers.get('user-agent');\n if (userAgent) {\n attributes[USER_AGENT_ORIGINAL] = userAgent;\n }\n\n const headers = winterCGHeadersToDict(request.headers);\n if (dataCollection.userInfo) {\n // `client.address` is the originating client, so a forwarding header wins over the socket, which\n // behind a proxy holds the proxy's address. The socket port is the proxy's too, so `client.port`\n // stays unset then.\n const forwardedAddress = getClientIPAddress(headers);\n if (forwardedAddress) {\n attributes[CLIENT_ADDRESS] = forwardedAddress;\n } else if (socketAddress) {\n attributes[CLIENT_ADDRESS] = socketAddress.address;\n if (socketAddress.port !== undefined) {\n attributes[CLIENT_PORT] = socketAddress.port;\n }\n }\n }\n\n // describes the OSI application-layer protocol (http), not the scheme (might be https)\n attributes[NETWORK_PROTOCOL_NAME] = 'http';\n Object.assign(attributes, httpHeadersToSpanAttributes(headers, dataCollection));\n Object.assign(attributes, config.attributes);\n attributes[SENTRY_OP] = HTTP_SERVER;\n attributes[SENTRY_KIND] = 'server';\n\n return startSpanManual({ name, attributes }, async span => {\n const { onSpanCreated, onSpanEnd } = options ?? {};\n if (onSpanCreated) {\n safeCallback(\n DEBUG_BUILD ? 'Error in `onSpanCreated`:' : '',\n () => onSpanCreated(span, request),\n () => undefined,\n );\n }\n\n let response: R;\n try {\n response = await handler();\n } catch (e) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n span.end();\n captureError(e);\n finish(undefined);\n throw e;\n }\n\n if (response) {\n setHttpStatus(span, response.status);\n isolationScope.setContext('response', { status_code: response.status });\n span.setAttributes(\n httpHeadersToSpanAttributes(responseHeadersToDict(response.headers), dataCollection, 'response'),\n );\n }\n\n const inRequestScope = bindToRequestScope(isolationScope);\n return onResponseDone(\n response,\n !!response && isStreamingResponse(response),\n inRequestScope(() => {\n if (onSpanEnd && response) {\n safeCallback(\n DEBUG_BUILD ? 'Error in `onSpanEnd`:' : '',\n () => onSpanEnd(span, request, response),\n () => undefined,\n );\n }\n span.end();\n finish(response);\n }),\n inRequestScope((error: unknown) => {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n captureError(error);\n }),\n );\n });\n },\n );\n}\n\n/**\n * Returns a function that binds a callback to the request's isolation scope and the current scope.\n *\n * A streamed body finishes after the handler returns. Without `AsyncLocalStorage` (Cloudflare\n * Workers without `nodejs_compat`), its callbacks then run outside the request's scopes, where\n * `getClient()` finds no client: the segment span would be sent as a transaction, and a captured\n * error would not update the request session.\n */\nfunction bindToRequestScope(\n isolationScope: Scope,\n): <A extends unknown[]>(fn: (...args: A) => void) => (...args: A) => void {\n const scope = getCurrentScope();\n return fn =>\n (...args) =>\n withIsolationScope(isolationScope, () => withScope(scope, () => fn(...args)));\n}\n\nfunction shouldCreateSpan(\n client: Client,\n options: ServerRequestOptions<Request, Response> | undefined,\n request: Request,\n urlPath: string,\n): boolean {\n if (!(options?.spans ?? hasSpansEnabled(client.getOptions()))) {\n return false;\n }\n if (options?.ignoreStaticAssets && request.method.toUpperCase() === 'GET' && isStaticAssetRequest(urlPath)) {\n return false;\n }\n const ignoreIncomingRequests = options?.ignoreIncomingRequests;\n return !(\n ignoreIncomingRequests &&\n safeCallback(\n DEBUG_BUILD ? 'Error in `ignoreIncomingRequests`, creating the span:' : '',\n () => ignoreIncomingRequests(urlPath, request),\n () => false,\n )\n );\n}\n\n/**\n * Calls `onDone` when the response is done: at once, or when a streamed body finishes.\n * Returns the response to send.\n */\nfunction onResponseDone<R extends Response | undefined>(\n response: R,\n isStreaming: boolean,\n onDone: () => void,\n onStreamError: (error: unknown) => void,\n): R {\n if (isStreaming && response?.body && !response.body.locked) {\n try {\n // Passing the original response as the init keeps its status, status text and headers, and\n // on Cloudflare also `encodeBody: 'manual'`, so workerd does not compress a compressed body again.\n return new Response(monitorStream(response.body, onDone, onStreamError), response) as R;\n } catch {\n // Workers with a compatibility date before 2022-11-30 and without the\n // `streams_enable_constructors` flag cannot construct a `ReadableStream`, so end at once.\n }\n }\n onDone();\n return response;\n}\n\n// `Headers.forEach` lists each `Set-Cookie` header on its own, so a plain dict keeps only the last one.\nfunction responseHeadersToDict(headers: Headers): Record<string, string | string[]> {\n const dict: Record<string, string | string[]> = winterCGHeadersToDict(headers);\n const setCookie = typeof headers.getSetCookie === 'function' ? headers.getSetCookie() : [];\n if (setCookie.length) {\n dict['set-cookie'] = setCookie;\n }\n return dict;\n}\n"],"mappings":";;;;;;;;;;;;;;AAUA,SAAgB,cACd,QACA,QACA,SAC4B;CAC5B,IAAI;CACJ,IAAI,WAAW;CACf,MAAM,UAAU,UAAqC;EACnD,IAAI,UACF;EAEF,WAAW;EAEX,IAAI;GAGF,IAAI,SAAS,GAAA,GAAEA,aAAAA,QAAAA,CAAQ,MAAM,KAAK,KAAK,MAAM,MAAM,SAAS,eAC1D,QAAQ,MAAM,KAAK;GAErB,OAAO;EACT,SAAS,GAAG;GACVC,oBAAAA,eAAeC,aAAAA,MAAM,MAAM,2CAA2C,CAAC;EACzE;CACF;CAEA,OAAO,IAAI,eACT;EAEE,QAAQ;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,UAAA,GACFC,aAAAA,mBAAAA,CAAmB,uBAAA,GAAsBC,aAAAA,UAAAA,CAAU,aAAa,GAAG,GAAG,IAAI,CAAC,CAAC;AAClF;AAEA,SAAS,iBACP,QACA,SACA,SACA,SACS;CACT,IAAI,EAAE,SAAS,UAAA,GAASC,aAAAA,gBAAAA,CAAgB,OAAO,WAAW,CAAC,IACzD,OAAO;CAET,IAAI,SAAS,sBAAsB,QAAQ,OAAO,YAAY,MAAM,UAAA,GAASC,oBAAAA,qBAAAA,CAAqB,OAAO,GACvG,OAAO;CAET,MAAM,yBAAyB,SAAS;CACxC,OAAO,EACL,2BAAA,GACA3B,aAAAA,aAAAA,CACEC,oBAAAA,cAAc,0DAA0D,UAClE,uBAAuB,SAAS,OAAO,SACvC,KACR;AAEJ;;;;;AAMA,SAAS,eACP,UACA,aACA,QACA,eACG;CACH,IAAI,eAAe,UAAU,QAAQ,CAAC,SAAS,KAAK,QAClD,IAAI;EAGF,OAAO,IAAI,SAAS,cAAc,SAAS,MAAM,QAAQ,aAAa,GAAG,QAAQ;CACnF,QAAQ,CAGR;CAEF,OAAO;CACP,OAAO;AACT;AAGA,SAAS,sBAAsB,SAAqD;CAClF,MAAM,QAAA,GAA0CU,aAAAA,sBAAAA,CAAsB,OAAO;CAC7E,MAAM,YAAY,OAAO,QAAQ,iBAAiB,aAAa,QAAQ,aAAa,IAAI,CAAC;CACzF,IAAI,UAAU,QACZ,KAAK,gBAAgB;CAEvB,OAAO;AACT"}
@@ -67,6 +67,7 @@ function startToolSpan(observation, context, toolSpans, options) {
67
67
  ...recordInputs && observation.args !== void 0 ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(observation.args) } : {}
68
68
  }
69
69
  });
70
+ if (observation.conversationId) span.setAttribute(GEN_AI_CONVERSATION_ID, observation.conversationId);
70
71
  if (recordOutputs) TOOL_SPANS_RECORDING_OUTPUTS.add(span);
71
72
  runGenAiSpanStart(options, span, call);
72
73
  TOOL_SPAN_END_HOOKS.set(span, (end) => runGenAiSpanEnd(options, span, call, end.isError ? {
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","names":[],"sources":["../../../../src/ai/flue/utils.ts"],"sourcesContent":["import type { LRUMap, Span } from '@sentry/core';\nimport {\n captureException,\n isObjectLike,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n stringify,\n withActiveSpan,\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_NAME,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport type { GenAiSpanHooks } from '../core/span-hooks';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { GenAiCallOptions } from '../core/utils';\nimport { getGenAiSpanOp, resolveGenAiCallRecording } from '../core/utils';\nimport { piAiContentToString } from '../pi-ai/messages';\nimport { FLUE_ORIGIN, MAX_TRACKED_FLUE_SPANS } from './constants';\nimport type { FlueCallInfo, FlueErrorInfo, FlueEventContext, FlueObservation } from './types';\n\n/**\n * Turn and tool spans, keyed by the id of the work they cover. Bounded, because the key is only\n * removed when the matching end observation arrives and an abandoned stream never emits one.\n */\nexport type SpanTracker = LRUMap<string, Span>;\n\nconst TOOL_SPANS_RECORDING_OUTPUTS = new WeakSet<Span>();\nconst TOOL_SPAN_END_HOOKS = new WeakMap<Span, (observation: FlueObservation) => void>();\n\n/**\n * Store a span under `key`. Callers only reach this with a key the tracker does not hold, so the\n * one span at risk of being dropped without `end()` is the oldest entry, which `LRUMap.set` silently\n * evicts once the tracker is full.\n */\nfunction trackSpan(tracker: SpanTracker, key: string, span: Span): void {\n if (tracker.size >= MAX_TRACKED_FLUE_SPANS) {\n const oldestKey = tracker.keys()[0];\n if (oldestKey !== undefined) {\n tracker.remove(oldestKey)?.end();\n }\n }\n\n tracker.set(key, span);\n}\n\n/**\n * Report a failed tool as an error event.\n *\n * Flue catches whatever the tool threw and hands it back to the model as a tool result, so nothing\n * propagates for the SDK's global handlers to see: without this a throwing tool produces an errored\n * span and no issue at all. `errorInfo` carries the original name, message and stack, so rebuild an\n * `Error` from it rather than capturing the serialized shape.\n *\n * Tools only. A failed turn carries no `errorInfo` — a provider auth failure produces an errored\n * `chat` span and nothing to rebuild from — so there is no turn equivalent to capture.\n */\nfunction captureToolError(span: Span, errorInfo: FlueErrorInfo | undefined): void {\n if (!errorInfo) {\n return;\n }\n\n const error = new Error(errorInfo.message ?? 'Flue tool failed');\n error.name = errorInfo.name ?? errorInfo.type ?? 'Error';\n if (errorInfo.stack) {\n error.stack = errorInfo.stack;\n }\n\n // Captured under the operation's own span so the issue lands on the right trace, matching how the\n // Mastra integration attaches its captures.\n withActiveSpan(span, () => {\n // Handled: this is not a rejection observed on a tracing channel, where the handled state is\n // unknowable. Flue caught the throw and returned it to the model as a tool result, so it is\n // definitively handled and no global hook will ever see it.\n captureException(error, { mechanism: { handled: true, type: FLUE_ORIGIN } });\n });\n}\n\n/**\n * Tool spans hang off the agent invocation rather than the turn, matching how Flue's own\n * OpenTelemetry adapter projects them: siblings of `chat`, correlated to model output by tool call\n * id. Keyed by `toolCallId` so concurrent tool calls in one turn cannot cross-attribute.\n */\nexport function startToolSpan(\n observation: FlueObservation,\n context: FlueEventContext,\n toolSpans: SpanTracker,\n options: GenAiCallOptions<FlueCallInfo> & GenAiSpanHooks<FlueCallInfo, FlueObservation>,\n): void {\n const { toolCallId, toolName } = observation;\n if (!toolCallId || toolSpans.get(toolCallId)) {\n return;\n }\n\n const call: FlueCallInfo = { operation: 'execute_tool', observation, context };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n const span = startInactiveSpan({\n name: `execute_tool ${toolName ?? 'unknown'}`,\n op: getGenAiSpanOp('execute_tool'),\n attributes: {\n [SENTRY_ORIGIN]: FLUE_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'execute_tool',\n [GEN_AI_TOOL_NAME]: toolName,\n [GEN_AI_CONVERSATION_ID]: observation.conversationId,\n ...(recordInputs && observation.args !== undefined\n ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(observation.args) }\n : {}),\n },\n });\n if (recordOutputs) {\n TOOL_SPANS_RECORDING_OUTPUTS.add(span);\n }\n runGenAiSpanStart(options, span, call);\n TOOL_SPAN_END_HOOKS.set(span, end =>\n runGenAiSpanEnd(options, span, call, end.isError ? { response: end, error: end.errorInfo } : { response: end }),\n );\n trackSpan(toolSpans, toolCallId, span);\n}\n\nexport function endToolSpan(observation: FlueObservation, toolSpans: SpanTracker): void {\n const { toolCallId } = observation;\n const span = toolCallId ? toolSpans.get(toolCallId) : undefined;\n if (!span || !toolCallId) {\n return;\n }\n toolSpans.remove(toolCallId);\n\n if (TOOL_SPANS_RECORDING_OUTPUTS.has(span)) {\n const result = toolResultForModel(observation);\n if (result !== undefined) {\n span.setAttribute(GEN_AI_TOOL_CALL_RESULT, result);\n }\n }\n\n if (observation.isError) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n captureToolError(span, observation.errorInfo);\n }\n TOOL_SPAN_END_HOOKS.get(span)?.(observation);\n span.end();\n}\n\n/**\n * The result the model receives: Flue's `effectiveResult` when it has one, else the content blocks\n * of its harness-level `result` (`{ content, details }`, whose `details` payload is tool-specific).\n */\nfunction toolResultForModel(observation: FlueObservation): string | undefined {\n const { effectiveResult } = observation;\n if (effectiveResult !== undefined) {\n if (typeof effectiveResult === 'string') {\n return effectiveResult;\n }\n return Array.isArray(effectiveResult) ? piAiContentToString(effectiveResult) : stringify(effectiveResult);\n }\n const { result } = observation;\n if (isObjectLike(result) && Array.isArray(result.content)) {\n return piAiContentToString(result.content);\n }\n return result === undefined ? undefined : stringify(result);\n}\n"],"mappings":";;;;;;;AA+BA,MAAM,+CAA+B,IAAI,QAAc;AACvD,MAAM,sCAAsB,IAAI,QAAsD;;;;;;AAOtF,SAAS,UAAU,SAAsB,KAAa,MAAkB;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AW,YAAY,IAAI;AACvC;AAEA,SAAgB,YAAY,aAA8B,WAA8B;CACtF,MAAM,EAAE,eAAe;CACvB,MAAM,OAAO,aAAa,UAAU,IAAI,UAAU,IAAI,KAAA;CACtD,IAAI,CAAC,QAAQ,CAAC,YACZ;CAEF,UAAU,OAAO,UAAU;CAE3B,IAAI,6BAA6B,IAAI,IAAI,GAAG;EAC1C,MAAM,SAAS,mBAAmB,WAAW;EAC7C,IAAI,WAAW,KAAA,GACb,KAAK,aAAa,yBAAyB,MAAM;CAErD;CAEA,IAAI,YAAY,SAAS;EACvB,KAAK,UAAU;GAAE,MAAM;GAAmB,SAAS;EAAiB,CAAC;EACrE,iBAAiB,MAAM,YAAY,SAAS;CAC9C;CACA,oBAAoB,IAAI,IAAI,CAAC,GAAG,WAAW;CAC3C,KAAK,IAAI;AACX;;;;;AAMA,SAAS,mBAAmB,aAAkD;CAC5E,MAAM,EAAE,oBAAoB;CAC5B,IAAI,oBAAoB,KAAA,GAAW;EACjC,IAAI,OAAO,oBAAoB,UAC7B,OAAO;EAET,OAAO,MAAM,QAAQ,eAAe,IAAI,oBAAoB,eAAe,IAAI,UAAU,eAAe;CAC1G;CACA,MAAM,EAAE,WAAW;CACnB,IAAI,aAAa,MAAM,KAAK,MAAM,QAAQ,OAAO,OAAO,GACtD,OAAO,oBAAoB,OAAO,OAAO;CAE3C,OAAO,WAAW,KAAA,IAAY,KAAA,IAAY,UAAU,MAAM;AAC5D"}
1
+ {"version":3,"file":"utils.js","names":[],"sources":["../../../../src/ai/flue/utils.ts"],"sourcesContent":["import type { LRUMap, Span } from '@sentry/core';\nimport {\n captureException,\n isObjectLike,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n stringify,\n withActiveSpan,\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_NAME,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport type { GenAiSpanHooks } from '../core/span-hooks';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { GenAiCallOptions } from '../core/utils';\nimport { getGenAiSpanOp, resolveGenAiCallRecording } from '../core/utils';\nimport { piAiContentToString } from '../pi-ai/messages';\nimport { FLUE_ORIGIN, MAX_TRACKED_FLUE_SPANS } from './constants';\nimport type { FlueCallInfo, FlueErrorInfo, FlueEventContext, FlueObservation } from './types';\n\n/**\n * Turn and tool spans, keyed by the id of the work they cover. Bounded, because the key is only\n * removed when the matching end observation arrives and an abandoned stream never emits one.\n */\nexport type SpanTracker = LRUMap<string, Span>;\n\nconst TOOL_SPANS_RECORDING_OUTPUTS = new WeakSet<Span>();\nconst TOOL_SPAN_END_HOOKS = new WeakMap<Span, (observation: FlueObservation) => void>();\n\n/**\n * Store a span under `key`. Callers only reach this with a key the tracker does not hold, so the\n * one span at risk of being dropped without `end()` is the oldest entry, which `LRUMap.set` silently\n * evicts once the tracker is full.\n */\nfunction trackSpan(tracker: SpanTracker, key: string, span: Span): void {\n if (tracker.size >= MAX_TRACKED_FLUE_SPANS) {\n const oldestKey = tracker.keys()[0];\n if (oldestKey !== undefined) {\n tracker.remove(oldestKey)?.end();\n }\n }\n\n tracker.set(key, span);\n}\n\n/**\n * Report a failed tool as an error event.\n *\n * Flue catches whatever the tool threw and hands it back to the model as a tool result, so nothing\n * propagates for the SDK's global handlers to see: without this a throwing tool produces an errored\n * span and no issue at all. `errorInfo` carries the original name, message and stack, so rebuild an\n * `Error` from it rather than capturing the serialized shape.\n *\n * Tools only. A failed turn carries no `errorInfo` — a provider auth failure produces an errored\n * `chat` span and nothing to rebuild from — so there is no turn equivalent to capture.\n */\nfunction captureToolError(span: Span, errorInfo: FlueErrorInfo | undefined): void {\n if (!errorInfo) {\n return;\n }\n\n const error = new Error(errorInfo.message ?? 'Flue tool failed');\n error.name = errorInfo.name ?? errorInfo.type ?? 'Error';\n if (errorInfo.stack) {\n error.stack = errorInfo.stack;\n }\n\n // Captured under the operation's own span so the issue lands on the right trace, matching how the\n // Mastra integration attaches its captures.\n withActiveSpan(span, () => {\n // Handled: this is not a rejection observed on a tracing channel, where the handled state is\n // unknowable. Flue caught the throw and returned it to the model as a tool result, so it is\n // definitively handled and no global hook will ever see it.\n captureException(error, { mechanism: { handled: true, type: FLUE_ORIGIN } });\n });\n}\n\n/**\n * Tool spans hang off the agent invocation rather than the turn, matching how Flue's own\n * OpenTelemetry adapter projects them: siblings of `chat`, correlated to model output by tool call\n * id. Keyed by `toolCallId` so concurrent tool calls in one turn cannot cross-attribute.\n */\nexport function startToolSpan(\n observation: FlueObservation,\n context: FlueEventContext,\n toolSpans: SpanTracker,\n options: GenAiCallOptions<FlueCallInfo> & GenAiSpanHooks<FlueCallInfo, FlueObservation>,\n): void {\n const { toolCallId, toolName } = observation;\n if (!toolCallId || toolSpans.get(toolCallId)) {\n return;\n }\n\n const call: FlueCallInfo = { operation: 'execute_tool', observation, context };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n const span = startInactiveSpan({\n name: `execute_tool ${toolName ?? 'unknown'}`,\n op: getGenAiSpanOp('execute_tool'),\n attributes: {\n [SENTRY_ORIGIN]: FLUE_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'execute_tool',\n [GEN_AI_TOOL_NAME]: toolName,\n [GEN_AI_CONVERSATION_ID]: observation.conversationId,\n ...(recordInputs && observation.args !== undefined\n ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(observation.args) }\n : {}),\n },\n });\n // Again after start, so the Flue id wins over one from `Sentry.setConversationId()`, as on the agent and chat spans.\n if (observation.conversationId) {\n span.setAttribute(GEN_AI_CONVERSATION_ID, observation.conversationId);\n }\n if (recordOutputs) {\n TOOL_SPANS_RECORDING_OUTPUTS.add(span);\n }\n runGenAiSpanStart(options, span, call);\n TOOL_SPAN_END_HOOKS.set(span, end =>\n runGenAiSpanEnd(options, span, call, end.isError ? { response: end, error: end.errorInfo } : { response: end }),\n );\n trackSpan(toolSpans, toolCallId, span);\n}\n\nexport function endToolSpan(observation: FlueObservation, toolSpans: SpanTracker): void {\n const { toolCallId } = observation;\n const span = toolCallId ? toolSpans.get(toolCallId) : undefined;\n if (!span || !toolCallId) {\n return;\n }\n toolSpans.remove(toolCallId);\n\n if (TOOL_SPANS_RECORDING_OUTPUTS.has(span)) {\n const result = toolResultForModel(observation);\n if (result !== undefined) {\n span.setAttribute(GEN_AI_TOOL_CALL_RESULT, result);\n }\n }\n\n if (observation.isError) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n captureToolError(span, observation.errorInfo);\n }\n TOOL_SPAN_END_HOOKS.get(span)?.(observation);\n span.end();\n}\n\n/**\n * The result the model receives: Flue's `effectiveResult` when it has one, else the content blocks\n * of its harness-level `result` (`{ content, details }`, whose `details` payload is tool-specific).\n */\nfunction toolResultForModel(observation: FlueObservation): string | undefined {\n const { effectiveResult } = observation;\n if (effectiveResult !== undefined) {\n if (typeof effectiveResult === 'string') {\n return effectiveResult;\n }\n return Array.isArray(effectiveResult) ? piAiContentToString(effectiveResult) : stringify(effectiveResult);\n }\n const { result } = observation;\n if (isObjectLike(result) && Array.isArray(result.content)) {\n return piAiContentToString(result.content);\n }\n return result === undefined ? undefined : stringify(result);\n}\n"],"mappings":";;;;;;;AA+BA,MAAM,+CAA+B,IAAI,QAAc;AACvD,MAAM,sCAAsB,IAAI,QAAsD;;;;;;AAOtF,SAAS,UAAU,SAAsB,KAAa,MAAkB;CACtE,IAAI,QAAQ,QAAA,KAAgC;EAC1C,MAAM,YAAY,QAAQ,KAAK,CAAC,CAAC;EACjC,IAAI,cAAc,KAAA,GAChB,QAAQ,OAAO,SAAS,CAAC,EAAE,IAAI;CAEnC;CAEA,QAAQ,IAAI,KAAK,IAAI;AACvB;;;;;;;;;;;;AAaA,SAAS,iBAAiB,MAAY,WAA4C;CAChF,IAAI,CAAC,WACH;CAGF,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,6BAA6B,IAAI,IAAI,GAAG;EAC1C,MAAM,SAAS,mBAAmB,WAAW;EAC7C,IAAI,WAAW,KAAA,GACb,KAAK,aAAa,yBAAyB,MAAM;CAErD;CAEA,IAAI,YAAY,SAAS;EACvB,KAAK,UAAU;GAAE,MAAM;GAAmB,SAAS;EAAiB,CAAC;EACrE,iBAAiB,MAAM,YAAY,SAAS;CAC9C;CACA,oBAAoB,IAAI,IAAI,CAAC,GAAG,WAAW;CAC3C,KAAK,IAAI;AACX;;;;;AAMA,SAAS,mBAAmB,aAAkD;CAC5E,MAAM,EAAE,oBAAoB;CAC5B,IAAI,oBAAoB,KAAA,GAAW;EACjC,IAAI,OAAO,oBAAoB,UAC7B,OAAO;EAET,OAAO,MAAM,QAAQ,eAAe,IAAI,oBAAoB,eAAe,IAAI,UAAU,eAAe;CAC1G;CACA,MAAM,EAAE,WAAW;CACnB,IAAI,aAAa,MAAM,KAAK,MAAM,QAAQ,OAAO,OAAO,GACtD,OAAO,oBAAoB,OAAO,OAAO;CAE3C,OAAO,WAAW,KAAA,IAAY,KAAA,IAAY,UAAU,MAAM;AAC5D"}
@@ -8,10 +8,38 @@ import { isObjectLike } from "@sentry/core";
8
8
  */
9
9
  function getDecisionInputMessages(params) {
10
10
  return getEvaluationInputMessages({
11
- state: params.input,
11
+ state: toStateMessages(params.input),
12
12
  questions: params.questions
13
13
  });
14
14
  }
15
+ /**
16
+ * Multimodal evidence is one part or a list of parts, recorded as one user message so it renders like OpenAI's.
17
+ * Inline media is reported by modality and media type only: its `data` is base64, which the conventions require
18
+ * to be dropped.
19
+ */
20
+ function toStateMessages(input) {
21
+ if (typeof input === "string") return input;
22
+ return [{
23
+ role: "user",
24
+ parts: (Array.isArray(input) ? input : [input]).filter(isObjectLike).map((part) => {
25
+ if (part.type === "text") return {
26
+ type: "text",
27
+ content: part.text
28
+ };
29
+ if (typeof part.uri === "string") return {
30
+ type: "uri",
31
+ modality: part.type,
32
+ mime_type: part.mime_type,
33
+ uri: part.uri
34
+ };
35
+ return {
36
+ type: "blob",
37
+ modality: part.type,
38
+ mime_type: part.mime_type
39
+ };
40
+ })
41
+ }];
42
+ }
15
43
  function addDecisionResponseAttributes(span, response, recordOutputs) {
16
44
  if (!isObjectLike(response)) return;
17
45
  if (isObjectLike(response.usage)) {
@@ -1 +1 @@
1
- {"version":3,"file":"decisions.js","names":[],"sources":["../../../../src/ai/google-genai/decisions.ts"],"sourcesContent":["// Google's questions and answers already use Jev's layout, so only the evaluated input is renamed.\nimport { GEN_AI_OUTPUT_MESSAGES } from '@sentry/conventions/attributes';\nimport type { Span } from '@sentry/core';\nimport { isObjectLike } from '@sentry/core';\nimport { getEvaluationInputMessages, getEvaluationOutputMessages, getTokenUsageAttributes } from '../core/utils';\n\n/**\n * Serialize a decisions request. Its evidence is `input` where Jev's is `state`; it is recorded as `state`\n * so both render the same.\n */\nexport function getDecisionInputMessages(params: Record<string, unknown>): string | undefined {\n return getEvaluationInputMessages({ state: params.input, questions: params.questions });\n}\n\nexport function addDecisionResponseAttributes(span: Span, response: unknown, recordOutputs: boolean): void {\n if (!isObjectLike(response)) {\n return;\n }\n\n if (isObjectLike(response.usage)) {\n const usage = response.usage as Record<string, number | undefined>;\n span.setAttributes(\n getTokenUsageAttributes(\n usage.total_input_tokens,\n usage.total_output_tokens,\n undefined,\n usage.total_cached_tokens,\n usage.total_tokens,\n ),\n );\n }\n\n if (recordOutputs && response.answers !== undefined) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, getEvaluationOutputMessages(response.answers));\n }\n}\n"],"mappings":";;;;;;;;AAUA,SAAgB,yBAAyB,QAAqD;CAC5F,OAAO,2BAA2B;EAAE,OAAO,OAAO;EAAO,WAAW,OAAO;CAAU,CAAC;AACxF;AAEA,SAAgB,8BAA8B,MAAY,UAAmB,eAA8B;CACzG,IAAI,CAAC,aAAa,QAAQ,GACxB;CAGF,IAAI,aAAa,SAAS,KAAK,GAAG;EAChC,MAAM,QAAQ,SAAS;EACvB,KAAK,cACH,wBACE,MAAM,oBACN,MAAM,qBACN,KAAA,GACA,MAAM,qBACN,MAAM,YACR,CACF;CACF;CAEA,IAAI,iBAAiB,SAAS,YAAY,KAAA,GACxC,KAAK,aAAa,wBAAwB,4BAA4B,SAAS,OAAO,CAAC;AAE3F"}
1
+ {"version":3,"file":"decisions.js","names":[],"sources":["../../../../src/ai/google-genai/decisions.ts"],"sourcesContent":["// Google's questions and answers already use Jev's layout, so only the evaluated input is mapped.\nimport { GEN_AI_OUTPUT_MESSAGES } from '@sentry/conventions/attributes';\nimport type { Span } from '@sentry/core';\nimport { isObjectLike } from '@sentry/core';\nimport { getEvaluationInputMessages, getEvaluationOutputMessages, getTokenUsageAttributes } from '../core/utils';\nimport type { GenAiMessage, GenAiMessagePart } from '../types';\n\n/**\n * Serialize a decisions request. Its evidence is `input` where Jev's is `state`; it is recorded as `state`\n * so both render the same.\n */\nexport function getDecisionInputMessages(params: Record<string, unknown>): string | undefined {\n return getEvaluationInputMessages({ state: toStateMessages(params.input), questions: params.questions });\n}\n\n/**\n * Multimodal evidence is one part or a list of parts, recorded as one user message so it renders like OpenAI's.\n * Inline media is reported by modality and media type only: its `data` is base64, which the conventions require\n * to be dropped.\n */\nfunction toStateMessages(input: unknown): unknown {\n if (typeof input === 'string') {\n return input;\n }\n\n const parts = (Array.isArray(input) ? input : [input]).filter(isObjectLike).map((part): GenAiMessagePart => {\n if (part.type === 'text') {\n return { type: 'text', content: part.text };\n }\n if (typeof part.uri === 'string') {\n return { type: 'uri', modality: part.type, mime_type: part.mime_type, uri: part.uri };\n }\n return { type: 'blob', modality: part.type, mime_type: part.mime_type };\n });\n return [{ role: 'user', parts } satisfies GenAiMessage];\n}\n\nexport function addDecisionResponseAttributes(span: Span, response: unknown, recordOutputs: boolean): void {\n if (!isObjectLike(response)) {\n return;\n }\n\n if (isObjectLike(response.usage)) {\n const usage = response.usage as Record<string, number | undefined>;\n span.setAttributes(\n getTokenUsageAttributes(\n usage.total_input_tokens,\n usage.total_output_tokens,\n undefined,\n usage.total_cached_tokens,\n usage.total_tokens,\n ),\n );\n }\n\n if (recordOutputs && response.answers !== undefined) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, getEvaluationOutputMessages(response.answers));\n }\n}\n"],"mappings":";;;;;;;;AAWA,SAAgB,yBAAyB,QAAqD;CAC5F,OAAO,2BAA2B;EAAE,OAAO,gBAAgB,OAAO,KAAK;EAAG,WAAW,OAAO;CAAU,CAAC;AACzG;;;;;;AAOA,SAAS,gBAAgB,OAAyB;CAChD,IAAI,OAAO,UAAU,UACnB,OAAO;CAYT,OAAO,CAAC;EAAE,MAAM;EAAQ,QATT,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK,EAAA,CAAG,OAAO,YAAY,CAAC,CAAC,KAAK,SAA2B;GAC1G,IAAI,KAAK,SAAS,QAChB,OAAO;IAAE,MAAM;IAAQ,SAAS,KAAK;GAAK;GAE5C,IAAI,OAAO,KAAK,QAAQ,UACtB,OAAO;IAAE,MAAM;IAAO,UAAU,KAAK;IAAM,WAAW,KAAK;IAAW,KAAK,KAAK;GAAI;GAEtF,OAAO;IAAE,MAAM;IAAQ,UAAU,KAAK;IAAM,WAAW,KAAK;GAAU;EACxE,CAC4B;CAAE,CAAwB;AACxD;AAEA,SAAgB,8BAA8B,MAAY,UAAmB,eAA8B;CACzG,IAAI,CAAC,aAAa,QAAQ,GACxB;CAGF,IAAI,aAAa,SAAS,KAAK,GAAG;EAChC,MAAM,QAAQ,SAAS;EACvB,KAAK,cACH,wBACE,MAAM,oBACN,MAAM,qBACN,KAAA,GACA,MAAM,qBACN,MAAM,YACR,CACF;CACF;CAEA,IAAI,iBAAiB,SAAS,YAAY,KAAA,GACxC,KAAK,aAAa,wBAAwB,4BAA4B,SAAS,OAAO,CAAC;AAE3F"}
@@ -1,8 +1,9 @@
1
1
  import { GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE, GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE } from "../core/gen-ai-attributes.js";
2
+ import { runGenAiSpanEnd, runGenAiSpanStart } from "../core/span-hooks.js";
2
3
  import { resolveGenAiCallRecording } from "../core/utils.js";
3
4
  import { LANGCHAIN_ORIGIN } from "./constants.js";
4
5
  import { GEN_AI_EMBEDDINGS_INPUT, GEN_AI_OPERATION_NAME, GEN_AI_PROVIDER_NAME, GEN_AI_REQUEST_MODEL, SENTRY_OP, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
5
- import { getClient, hasSpanStreamingEnabled, startSpan, stringify } from "@sentry/core";
6
+ import { SPAN_STATUS_ERROR, getClient, hasSpanStreamingEnabled, startSpan, stringify } from "@sentry/core";
6
7
  import { GEN_AI_EMBEDDINGS } from "@sentry/conventions/op";
7
8
  // src/ai/langchain/embeddings.ts
8
9
  /**
@@ -42,11 +43,9 @@ function extractEmbeddingAttributes(instance) {
42
43
  * @internal Exported so the diagnostics-channel (orchestrion) instrumentation can build the same
43
44
  * span as the prototype-patching path below.
44
45
  */
45
- function _INTERNAL_getLangChainEmbeddingsSpanOptions(instance, input, options = {}) {
46
- const { recordInputs } = resolveGenAiCallRecording(options, {
47
- operation: "embeddings",
48
- input
49
- });
46
+ function _INTERNAL_getLangChainEmbeddingsSpanOptions(instance, call, options = {}) {
47
+ const { input } = call;
48
+ const { recordInputs } = resolveGenAiCallRecording(options, call);
50
49
  const attributes = extractEmbeddingAttributes(instance);
51
50
  const modelName = attributes[GEN_AI_REQUEST_MODEL] || "unknown";
52
51
  const client = getClient();
@@ -63,8 +62,24 @@ function _INTERNAL_getLangChainEmbeddingsSpanOptions(instance, input, options =
63
62
  */
64
63
  function instrumentEmbeddingMethod(originalMethod, options = {}) {
65
64
  return new Proxy(originalMethod, { apply(target, thisArg, args) {
66
- return startSpan(_INTERNAL_getLangChainEmbeddingsSpanOptions(thisArg, args[0], options), () => {
67
- return Reflect.apply(target, thisArg, args);
65
+ const call = {
66
+ operation: "embeddings",
67
+ input: args[0]
68
+ };
69
+ return startSpan(_INTERNAL_getLangChainEmbeddingsSpanOptions(thisArg, call, options), async (span) => {
70
+ runGenAiSpanStart(options, span, call);
71
+ try {
72
+ const response = await Reflect.apply(target, thisArg, args);
73
+ runGenAiSpanEnd(options, span, call, { response });
74
+ return response;
75
+ } catch (error) {
76
+ span.setStatus({
77
+ code: SPAN_STATUS_ERROR,
78
+ message: "internal_error"
79
+ });
80
+ runGenAiSpanEnd(options, span, call, { error });
81
+ throw error;
82
+ }
68
83
  });
69
84
  } });
70
85
  }
@@ -1 +1 @@
1
- {"version":3,"file":"embeddings.js","names":[],"sources":["../../../../src/ai/langchain/embeddings.ts"],"sourcesContent":["import { getClient, hasSpanStreamingEnabled, startSpan, stringify } from '@sentry/core';\nimport type { SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_OPERATION_NAME,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_MODEL,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_EMBEDDINGS } from '@sentry/conventions/op';\nimport {\n GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE,\n GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE,\n} from '../core/gen-ai-attributes';\nimport { resolveGenAiCallRecording } from '../core/utils';\nimport { LANGCHAIN_ORIGIN } from './constants';\nimport type { LangChainOptions } from './types';\n\n/**\n * Infers the AI provider system name from the embedding class instance.\n */\nfunction inferSystemFromInstance(instance: Record<string, unknown>): string {\n const name = (instance.constructor as { name?: string })?.name ?? '';\n if (name.includes('OpenAI')) return 'openai';\n if (name.includes('Google')) return 'google_genai';\n if (name.includes('Mistral')) return 'mistralai';\n if (name.includes('Vertex')) return 'google_vertexai';\n if (name.includes('Bedrock')) return 'aws_bedrock';\n if (name.includes('Ollama')) return 'ollama';\n if (name.includes('Cloudflare')) return 'cloudflare';\n if (name.includes('Cohere')) return 'cohere';\n return 'langchain';\n}\n\n/**\n * Extracts span attributes from a LangChain embedding class instance.\n */\nfunction extractEmbeddingAttributes(instance: unknown): Record<string, unknown> {\n const embeddingsInstance = (instance ?? {}) as Record<string, unknown>;\n\n const attributes: Record<string, unknown> = {\n [SENTRY_ORIGIN]: LANGCHAIN_ORIGIN,\n [SENTRY_OP]: GEN_AI_EMBEDDINGS,\n [GEN_AI_OPERATION_NAME]: 'embeddings',\n [GEN_AI_REQUEST_MODEL]: embeddingsInstance.model ?? 'unknown',\n };\n\n attributes[GEN_AI_PROVIDER_NAME] = inferSystemFromInstance(embeddingsInstance);\n if ('dimensions' in embeddingsInstance) {\n attributes[GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE] = embeddingsInstance.dimensions;\n }\n if ('encodingFormat' in embeddingsInstance) {\n attributes[GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE] = embeddingsInstance.encodingFormat;\n }\n\n return attributes;\n}\n\n/**\n * Builds the span options for a LangChain embedding call from the embeddings instance and input.\n *\n * @internal Exported so the diagnostics-channel (orchestrion) instrumentation can build the same\n * span as the prototype-patching path below.\n */\nexport function _INTERNAL_getLangChainEmbeddingsSpanOptions(\n instance: unknown,\n input: unknown,\n options: LangChainOptions = {},\n): { name: string; attributes: Record<string, SpanAttributeValue> } {\n const { recordInputs } = resolveGenAiCallRecording(options, { operation: 'embeddings', input });\n const attributes = extractEmbeddingAttributes(instance);\n const modelName = attributes[GEN_AI_REQUEST_MODEL] || 'unknown';\n const client = getClient();\n\n if (recordInputs && input != null) {\n attributes[GEN_AI_EMBEDDINGS_INPUT] = stringify(input, String);\n }\n\n return {\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name:\n (typeof modelName === 'string' && modelName !== 'unknown') || !(client && hasSpanStreamingEnabled(client))\n ? `embeddings ${modelName}`\n : 'embeddings',\n attributes: attributes as Record<string, SpanAttributeValue>,\n };\n}\n\n/**\n * Wraps a LangChain embedding method (embedQuery or embedDocuments) to create Sentry spans.\n *\n * Used internally by the Node.js auto-instrumentation to patch embedding class prototypes.\n */\nexport function instrumentEmbeddingMethod(\n originalMethod: (...args: unknown[]) => Promise<unknown>,\n options: LangChainOptions = {},\n): (...args: unknown[]) => Promise<unknown> {\n return new Proxy(originalMethod, {\n apply(target, thisArg, args: unknown[]): Promise<unknown> {\n return startSpan(_INTERNAL_getLangChainEmbeddingsSpanOptions(thisArg, args[0], options), () => {\n // On rejection `startSpan` marks the span failed and rethrows to the caller, so we don't\n // record the error ourselves.\n return Reflect.apply(target, thisArg, args);\n });\n },\n });\n}\n\n/**\n * Wraps a LangChain embeddings instance to create Sentry spans for `embedQuery` and `embedDocuments` calls.\n *\n * Use this in non-Node runtimes (Cloudflare, browser, etc.) where auto-instrumentation is not available.\n *\n * @example\n * ```javascript\n * import * as Sentry from '@sentry/cloudflare';\n * import { OpenAIEmbeddings } from '@langchain/openai';\n *\n * const embeddings = Sentry.instrumentLangChainEmbeddings(\n * new OpenAIEmbeddings({ model: 'text-embedding-3-small' })\n * );\n *\n * await embeddings.embedQuery('Hello world');\n * await embeddings.embedDocuments(['doc1', 'doc2']);\n * ```\n */\nexport function instrumentLangChainEmbeddings<T extends object>(instance: T, options?: LangChainOptions): T {\n const embeddingsInstance = instance as Record<string, unknown>;\n\n if (typeof embeddingsInstance.embedQuery === 'function') {\n embeddingsInstance.embedQuery = instrumentEmbeddingMethod(\n embeddingsInstance.embedQuery as (...args: unknown[]) => Promise<unknown>,\n options,\n );\n }\n\n if (typeof embeddingsInstance.embedDocuments === 'function') {\n embeddingsInstance.embedDocuments = instrumentEmbeddingMethod(\n embeddingsInstance.embedDocuments as (...args: unknown[]) => Promise<unknown>,\n options,\n );\n }\n\n return instance;\n}\n"],"mappings":";;;;;;;;;;AAsBA,SAAS,wBAAwB,UAA2C;CAC1E,MAAM,OAAQ,SAAS,aAAmC,QAAQ;CAClE,IAAI,KAAK,SAAS,QAAQ,GAAG,OAAO;CACpC,IAAI,KAAK,SAAS,QAAQ,GAAG,OAAO;CACpC,IAAI,KA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;;;;;;;;;;;;;;;AAoBA,SAAgB,8BAAgD,UAAa,SAA+B;CAC1G,MAAM,qBAAqB;CAE3B,IAAI,OAAO,mBAAmB,eAAe,YAC3C,mBAAmB,aAAa,0BAC9B,mBAAmB,YACnB,OACF;CAGF,IAAI,OAAO,mBAAmB,mBAAmB,YAC/C,mBAAmB,iBAAiB,0BAClC,mBAAmB,gBACnB,OACF;CAGF,OAAO;AACT"}
1
+ {"version":3,"file":"embeddings.js","names":[],"sources":["../../../../src/ai/langchain/embeddings.ts"],"sourcesContent":["import { getClient, hasSpanStreamingEnabled, SPAN_STATUS_ERROR, startSpan, stringify } from '@sentry/core';\nimport type { SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_OPERATION_NAME,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_MODEL,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_EMBEDDINGS } from '@sentry/conventions/op';\nimport {\n GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE,\n GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE,\n} from '../core/gen-ai-attributes';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport { resolveGenAiCallRecording } from '../core/utils';\nimport { LANGCHAIN_ORIGIN } from './constants';\nimport type { LangChainEmbeddingsCallInfo, LangChainOptions } from './types';\n\n/**\n * Infers the AI provider system name from the embedding class instance.\n */\nfunction inferSystemFromInstance(instance: Record<string, unknown>): string {\n const name = (instance.constructor as { name?: string })?.name ?? '';\n if (name.includes('OpenAI')) return 'openai';\n if (name.includes('Google')) return 'google_genai';\n if (name.includes('Mistral')) return 'mistralai';\n if (name.includes('Vertex')) return 'google_vertexai';\n if (name.includes('Bedrock')) return 'aws_bedrock';\n if (name.includes('Ollama')) return 'ollama';\n if (name.includes('Cloudflare')) return 'cloudflare';\n if (name.includes('Cohere')) return 'cohere';\n return 'langchain';\n}\n\n/**\n * Extracts span attributes from a LangChain embedding class instance.\n */\nfunction extractEmbeddingAttributes(instance: unknown): Record<string, unknown> {\n const embeddingsInstance = (instance ?? {}) as Record<string, unknown>;\n\n const attributes: Record<string, unknown> = {\n [SENTRY_ORIGIN]: LANGCHAIN_ORIGIN,\n [SENTRY_OP]: GEN_AI_EMBEDDINGS,\n [GEN_AI_OPERATION_NAME]: 'embeddings',\n [GEN_AI_REQUEST_MODEL]: embeddingsInstance.model ?? 'unknown',\n };\n\n attributes[GEN_AI_PROVIDER_NAME] = inferSystemFromInstance(embeddingsInstance);\n if ('dimensions' in embeddingsInstance) {\n attributes[GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE] = embeddingsInstance.dimensions;\n }\n if ('encodingFormat' in embeddingsInstance) {\n attributes[GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE] = embeddingsInstance.encodingFormat;\n }\n\n return attributes;\n}\n\n/**\n * Builds the span options for a LangChain embedding call from the embeddings instance and input.\n *\n * @internal Exported so the diagnostics-channel (orchestrion) instrumentation can build the same\n * span as the prototype-patching path below.\n */\nexport function _INTERNAL_getLangChainEmbeddingsSpanOptions(\n instance: unknown,\n call: LangChainEmbeddingsCallInfo,\n options: LangChainOptions = {},\n): { name: string; attributes: Record<string, SpanAttributeValue> } {\n const { input } = call;\n const { recordInputs } = resolveGenAiCallRecording(options, call);\n const attributes = extractEmbeddingAttributes(instance);\n const modelName = attributes[GEN_AI_REQUEST_MODEL] || 'unknown';\n const client = getClient();\n\n if (recordInputs && input != null) {\n attributes[GEN_AI_EMBEDDINGS_INPUT] = stringify(input, String);\n }\n\n return {\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name:\n (typeof modelName === 'string' && modelName !== 'unknown') || !(client && hasSpanStreamingEnabled(client))\n ? `embeddings ${modelName}`\n : 'embeddings',\n attributes: attributes as Record<string, SpanAttributeValue>,\n };\n}\n\n/**\n * Wraps a LangChain embedding method (embedQuery or embedDocuments) to create Sentry spans.\n *\n * Used internally by the Node.js auto-instrumentation to patch embedding class prototypes.\n */\nexport function instrumentEmbeddingMethod(\n originalMethod: (...args: unknown[]) => Promise<unknown>,\n options: LangChainOptions = {},\n): (...args: unknown[]) => Promise<unknown> {\n return new Proxy(originalMethod, {\n apply(target, thisArg, args: unknown[]): Promise<unknown> {\n const call: LangChainEmbeddingsCallInfo = { operation: 'embeddings', input: args[0] };\n return startSpan(_INTERNAL_getLangChainEmbeddingsSpanOptions(thisArg, call, options), async span => {\n runGenAiSpanStart(options, span, call);\n try {\n const response = await Reflect.apply(target, thisArg, args);\n runGenAiSpanEnd(options, span, call, { response });\n return response;\n } catch (error) {\n // The error is rethrown to the caller, so we only mark the span failed and do not record it.\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n runGenAiSpanEnd(options, span, call, { error });\n throw error;\n }\n });\n },\n });\n}\n\n/**\n * Wraps a LangChain embeddings instance to create Sentry spans for `embedQuery` and `embedDocuments` calls.\n *\n * Use this in non-Node runtimes (Cloudflare, browser, etc.) where auto-instrumentation is not available.\n *\n * @example\n * ```javascript\n * import * as Sentry from '@sentry/cloudflare';\n * import { OpenAIEmbeddings } from '@langchain/openai';\n *\n * const embeddings = Sentry.instrumentLangChainEmbeddings(\n * new OpenAIEmbeddings({ model: 'text-embedding-3-small' })\n * );\n *\n * await embeddings.embedQuery('Hello world');\n * await embeddings.embedDocuments(['doc1', 'doc2']);\n * ```\n */\nexport function instrumentLangChainEmbeddings<T extends object>(instance: T, options?: LangChainOptions): T {\n const embeddingsInstance = instance as Record<string, unknown>;\n\n if (typeof embeddingsInstance.embedQuery === 'function') {\n embeddingsInstance.embedQuery = instrumentEmbeddingMethod(\n embeddingsInstance.embedQuery as (...args: unknown[]) => Promise<unknown>,\n options,\n );\n }\n\n if (typeof embeddingsInstance.embedDocuments === 'function') {\n embeddingsInstance.embedDocuments = instrumentEmbeddingMethod(\n embeddingsInstance.embedDocuments as (...args: unknown[])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gBACA,UAA4B,CAAC,GACa;CAC1C,OAAO,IAAI,MAAM,gBAAgB,EAC/B,MAAM,QAAQ,SAAS,MAAmC;EACxD,MAAM,OAAoC;GAAE,WAAW;GAAc,OAAO,KAAK;EAAG;EACpF,OAAO,UAAU,4CAA4C,SAAS,MAAM,OAAO,GAAG,OAAM,SAAQ;GAClG,kBAAkB,SAAS,MAAM,IAAI;GACrC,IAAI;IACF,MAAM,WAAW,MAAM,QAAQ,MAAM,QAAQ,SAAS,IAAI;IAC1D,gBAAgB,SAAS,MAAM,MAAM,EAAE,SAAS,CAAC;IACjD,OAAO;GACT,SAAS,OAAO;IAEd,KAAK,UAAU;KAAE,MAAM;KAAmB,SAAS;IAAiB,CAAC;IACrE,gBAAgB,SAAS,MAAM,MAAM,EAAE,MAAM,CAAC;IAC9C,MAAM;GACR;EACF,CAAC;CACH,EACF,CAAC;AACH;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,8BAAgD,UAAa,SAA+B;CAC1G,MAAM,qBAAqB;CAE3B,IAAI,OAAO,mBAAmB,eAAe,YAC3C,mBAAmB,aAAa,0BAC9B,mBAAmB,YACnB,OACF;CAGF,IAAI,OAAO,mBAAmB,mBAAmB,YAC/C,mBAAmB,iBAAiB,0BAClC,mBAAmB,gBACnB,OACF;CAGF,OAAO;AACT"}
@@ -1,4 +1,5 @@
1
1
  import { DEBUG_BUILD } from "../../debug-build.js";
2
+ import { runGenAiSpanEnd, runGenAiSpanStart } from "../core/span-hooks.js";
2
3
  import { resolveGenAiCallRecording } from "../core/utils.js";
3
4
  import { recordTimeToFirstChunk } from "../core/time-to-first-chunk.js";
4
5
  import { LANGCHAIN_ORIGIN, MAX_TRACKED_LANGCHAIN_RUNS } from "./constants.js";
@@ -22,9 +23,12 @@ function createLangChainCallbackHandler(options = {}) {
22
23
  /**
23
24
  * Exit a span and clean up
24
25
  */
25
- const exitSpan = (runId) => {
26
- const span = runs.remove(runId)?.span;
27
- if (span?.isRecording()) span.end();
26
+ const exitSpan = (runId, result = {}) => {
27
+ const run = runs.remove(runId);
28
+ if (run?.span.isRecording()) {
29
+ runGenAiSpanEnd(options, run.span, run.call, result);
30
+ run.span.end();
31
+ }
28
32
  };
29
33
  let warnedFull = false;
30
34
  const trackRun = (runId, run) => {
@@ -40,7 +44,7 @@ function createLangChainCallbackHandler(options = {}) {
40
44
  };
41
45
  const getAncestors = (parentRunId) => {
42
46
  const ancestors = [];
43
- for (let run = getRun(parentRunId); run; run = getRun(run.parentRunId)) ancestors.push(run);
47
+ for (let run = getRun(parentRunId); run; run = getRun(run.call.parentRunId)) ancestors.push(run);
44
48
  return ancestors;
45
49
  };
46
50
  const getParentRunSpan = (ancestors, activeSpan) => {
@@ -49,7 +53,8 @@ function createLangChainCallbackHandler(options = {}) {
49
53
  if (!spanIsIgnored(run.span) || getRootSpan(run.span) === run.span) return run.span;
50
54
  }
51
55
  };
52
- const startRunSpan = (runId, parentRunId, recordOutputs, start) => {
56
+ const startRunSpan = (call, recordOutputs, start) => {
57
+ const { runId, parentRunId } = call;
53
58
  const ancestors = getAncestors(parentRunId);
54
59
  const activeSpan = getActiveSpan();
55
60
  const parentSpan = getParentRunSpan(ancestors, activeSpan);
@@ -59,7 +64,7 @@ function createLangChainCallbackHandler(options = {}) {
59
64
  if (conversationId && conversationId !== ownId) span.setAttribute(GEN_AI_CONVERSATION_ID, conversationId);
60
65
  const run = {
61
66
  span,
62
- parentRunId,
67
+ call,
63
68
  activeSpan,
64
69
  conversationId,
65
70
  recordOutputs
@@ -70,6 +75,7 @@ function createLangChainCallbackHandler(options = {}) {
70
75
  ancestor.conversationId = conversationId;
71
76
  ancestor.span.setAttribute(GEN_AI_CONVERSATION_ID, conversationId);
72
77
  }
78
+ runGenAiSpanStart(options, span, call);
73
79
  return run;
74
80
  };
75
81
  /**
@@ -103,7 +109,7 @@ function createLangChainCallbackHandler(options = {}) {
103
109
  awaitHandlers: true,
104
110
  handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, _runName) {
105
111
  const serialized = llm;
106
- const { recordInputs, recordOutputs } = resolveRecording({
112
+ const call = {
107
113
  operation: "chat",
108
114
  serialized,
109
115
  prompts,
@@ -112,13 +118,14 @@ function createLangChainCallbackHandler(options = {}) {
112
118
  extraParams,
113
119
  tags,
114
120
  metadata
115
- });
121
+ };
122
+ const { recordInputs, recordOutputs } = resolveRecording(call);
116
123
  const invocationParams = getInvocationParams(tags);
117
124
  const attributes = extractLLMRequestAttributes(serialized, prompts, recordInputs, invocationParams, metadata);
118
125
  const modelName = attributes[GEN_AI_REQUEST_MODEL] || "unknown";
119
126
  const operationName = typeof attributes[GEN_AI_OPERATION_NAME] === "string" ? attributes[GEN_AI_OPERATION_NAME] : "unknown";
120
127
  const client = getClient();
121
- startRunSpan(runId, parentRunId, recordOutputs, () => startInactiveSpan({
128
+ startRunSpan(call, recordOutputs, () => startInactiveSpan({
122
129
  name: typeof modelName === "string" && modelName !== "unknown" || !(client && hasSpanStreamingEnabled(client)) ? `${operationName} ${modelName}` : operationName,
123
130
  attributes: {
124
131
  ...getAgentNameFromMetadata(metadata),
@@ -131,7 +138,7 @@ function createLangChainCallbackHandler(options = {}) {
131
138
  handleChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, _runName) {
132
139
  const serialized = llm;
133
140
  const chatMessages = messages;
134
- const { recordInputs, recordOutputs } = resolveRecording({
141
+ const call = {
135
142
  operation: "chat",
136
143
  serialized,
137
144
  messages: chatMessages,
@@ -140,7 +147,8 @@ function createLangChainCallbackHandler(options = {}) {
140
147
  extraParams,
141
148
  tags,
142
149
  metadata
143
- });
150
+ };
151
+ const { recordInputs, recordOutputs } = resolveRecording(call);
144
152
  const invocationParams = getInvocationParams(tags);
145
153
  const attributes = extractChatModelRequestAttributes(serialized, chatMessages, recordInputs, invocationParams, metadata);
146
154
  const toolDefsJson = recordInputs ? extractToolDefinitions(extraParams) : void 0;
@@ -148,7 +156,7 @@ function createLangChainCallbackHandler(options = {}) {
148
156
  const modelName = attributes[GEN_AI_REQUEST_MODEL] || "unknown";
149
157
  const operationName = typeof attributes[GEN_AI_OPERATION_NAME] === "string" ? attributes[GEN_AI_OPERATION_NAME] : "unknown";
150
158
  const client = getClient();
151
- startRunSpan(runId, parentRunId, recordOutputs, () => startInactiveSpan({
159
+ startRunSpan(call, recordOutputs, () => startInactiveSpan({
152
160
  name: typeof modelName === "string" && modelName !== "unknown" || !(client && hasSpanStreamingEnabled(client)) ? `${operationName} ${modelName}` : operationName,
153
161
  attributes: {
154
162
  ...getAgentNameFromMetadata(metadata),
@@ -169,19 +177,19 @@ function createLangChainCallbackHandler(options = {}) {
169
177
  const attributes = extractLlmResponseAttributes(output, run.recordOutputs);
170
178
  if (attributes) span.setAttributes(attributes);
171
179
  }
172
- exitSpan(runId);
180
+ exitSpan(runId, { response: output });
173
181
  },
174
- handleLLMError(_error, runId) {
182
+ handleLLMError(error, runId) {
175
183
  const span = runs.get(runId)?.span;
176
184
  if (span?.isRecording()) span.setStatus({
177
185
  code: SPAN_STATUS_ERROR,
178
186
  message: "internal_error"
179
187
  });
180
- exitSpan(runId);
188
+ exitSpan(runId, { error });
181
189
  },
182
190
  handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, _runType, runName) {
183
191
  if (isTypeSafeClassifier(chain)) {
184
- const { recordInputs, recordOutputs } = resolveRecording({
192
+ const call = {
185
193
  operation: "decide",
186
194
  serialized: chain,
187
195
  inputs,
@@ -189,12 +197,13 @@ function createLangChainCallbackHandler(options = {}) {
189
197
  parentRunId,
190
198
  tags,
191
199
  metadata
192
- });
193
- startRunSpan(runId, parentRunId, recordOutputs, () => startTypeSafeClassifierSpan(chain, inputs, metadata, recordInputs)).decide = true;
200
+ };
201
+ const { recordInputs, recordOutputs } = resolveRecording(call);
202
+ startRunSpan(call, recordOutputs, () => startTypeSafeClassifierSpan(chain, inputs, metadata, recordInputs)).decide = true;
194
203
  return;
195
204
  }
196
205
  if (metadata?.__sentry_langgraph__) return;
197
- const { recordInputs, recordOutputs } = resolveRecording({
206
+ const call = {
198
207
  operation: "invoke_agent",
199
208
  serialized: chain,
200
209
  inputs,
@@ -202,7 +211,8 @@ function createLangChainCallbackHandler(options = {}) {
202
211
  parentRunId,
203
212
  tags,
204
213
  metadata
205
- });
214
+ };
215
+ const { recordInputs, recordOutputs } = resolveRecording(call);
206
216
  const chainName = runName || chain.name;
207
217
  const attributes = {
208
218
  ...getConversationIdFromMetadata(metadata),
@@ -212,7 +222,7 @@ function createLangChainCallbackHandler(options = {}) {
212
222
  if (chainName) attributes[GEN_AI_PIPELINE_NAME] = chainName;
213
223
  if (recordInputs) attributes["langchain.chain.inputs"] = JSON.stringify(inputs);
214
224
  const client = getClient();
215
- startRunSpan(runId, parentRunId, recordOutputs, () => startInactiveSpan({
225
+ startRunSpan(call, recordOutputs, () => startInactiveSpan({
216
226
  name: !(client && hasSpanStreamingEnabled(client)) ? `chain ${chainName || "unknown_chain"}` : chainName ? `invoke_agent ${chainName}` : "invoke_agent",
217
227
  attributes: {
218
228
  ...attributes,
@@ -227,19 +237,19 @@ function createLangChainCallbackHandler(options = {}) {
227
237
  if (run.decide) addTypeSafeClassifierResponseAttributes(span, outputs, run.recordOutputs);
228
238
  else if (run.recordOutputs) span.setAttributes({ "langchain.chain.outputs": JSON.stringify(outputs) });
229
239
  }
230
- exitSpan(runId);
240
+ exitSpan(runId, { response: outputs });
231
241
  },
232
- handleChainError(_error, runId) {
242
+ handleChainError(error, runId) {
233
243
  const span = runs.get(runId)?.span;
234
244
  if (span?.isRecording()) span.setStatus({
235
245
  code: SPAN_STATUS_ERROR,
236
246
  message: "internal_error"
237
247
  });
238
- exitSpan(runId);
248
+ exitSpan(runId, { error });
239
249
  },
240
250
  handleToolStart(tool, input, runId, parentRunId, tags, metadata, runName) {
241
251
  if (metadata?.__sentry_langgraph__) return;
242
- const { recordInputs, recordOutputs } = resolveRecording({
252
+ const call = {
243
253
  operation: "execute_tool",
244
254
  serialized: tool,
245
255
  input,
@@ -247,7 +257,8 @@ function createLangChainCallbackHandler(options = {}) {
247
257
  parentRunId,
248
258
  tags,
249
259
  metadata
250
- });
260
+ };
261
+ const { recordInputs, recordOutputs } = resolveRecording(call);
251
262
  const toolName = runName || tool.name || "unknown_tool";
252
263
  const attributes = {
253
264
  ...getAgentNameFromMetadata(metadata),
@@ -257,7 +268,7 @@ function createLangChainCallbackHandler(options = {}) {
257
268
  [GEN_AI_TOOL_NAME]: toolName
258
269
  };
259
270
  if (recordInputs) attributes[GEN_AI_TOOL_CALL_ARGUMENTS] = input;
260
- startRunSpan(runId, parentRunId, recordOutputs, () => startInactiveSpan({
271
+ startRunSpan(call, recordOutputs, () => startInactiveSpan({
261
272
  name: `execute_tool ${toolName}`,
262
273
  attributes: {
263
274
  ...attributes,
@@ -275,15 +286,15 @@ function createLangChainCallbackHandler(options = {}) {
275
286
  span.setAttributes({ [GEN_AI_TOOL_CALL_RESULT]: stringify(content, String) });
276
287
  }
277
288
  }
278
- exitSpan(runId);
289
+ exitSpan(runId, { response: output });
279
290
  },
280
- handleToolError(_error, runId) {
291
+ handleToolError(error, runId) {
281
292
  const span = runs.get(runId)?.span;
282
293
  if (span?.isRecording()) span.setStatus({
283
294
  code: SPAN_STATUS_ERROR,
284
295
  message: "internal_error"
285
296
  });
286
- exitSpan(runId);
297
+ exitSpan(runId, { error });
287
298
  },
288
299
  copy() {
289
300
  return handler;