@sentry/server-utils 10.64.0 → 10.65.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.
- package/build/cjs/graphql/graphql-dc-subscriber.js +125 -0
- package/build/cjs/graphql/graphql-dc-subscriber.js.map +1 -0
- package/build/cjs/graphql/index.js +23 -0
- package/build/cjs/graphql/index.js.map +1 -0
- package/build/cjs/graphql/utils.js +86 -0
- package/build/cjs/graphql/utils.js.map +1 -0
- package/build/cjs/index.js +10 -11
- package/build/cjs/index.js.map +1 -1
- package/build/cjs/integrations/tracing-channel/amqplib.js +420 -0
- package/build/cjs/integrations/tracing-channel/amqplib.js.map +1 -0
- package/build/cjs/integrations/tracing-channel/express/index.js +24 -0
- package/build/cjs/integrations/tracing-channel/express/index.js.map +1 -0
- package/build/cjs/integrations/tracing-channel/express/instrumentation.js +173 -0
- package/build/cjs/integrations/tracing-channel/express/instrumentation.js.map +1 -0
- package/build/cjs/integrations/tracing-channel/express/route.js +76 -0
- package/build/cjs/integrations/tracing-channel/express/route.js.map +1 -0
- package/build/cjs/integrations/tracing-channel/fastify/instrumentation.js +1 -1
- package/build/cjs/integrations/tracing-channel/fastify/instrumentation.js.map +1 -1
- package/build/cjs/integrations/tracing-channel/google-genai.js +96 -0
- package/build/cjs/integrations/tracing-channel/google-genai.js.map +1 -0
- package/build/cjs/integrations/tracing-channel/graphql/constants.js +26 -0
- package/build/cjs/integrations/tracing-channel/graphql/constants.js.map +1 -0
- package/build/cjs/integrations/tracing-channel/graphql/index.js +66 -0
- package/build/cjs/integrations/tracing-channel/graphql/index.js.map +1 -0
- package/build/cjs/integrations/tracing-channel/graphql/resolvers.js +168 -0
- package/build/cjs/integrations/tracing-channel/graphql/resolvers.js.map +1 -0
- package/build/cjs/integrations/tracing-channel/graphql/spans.js +102 -0
- package/build/cjs/integrations/tracing-channel/graphql/spans.js.map +1 -0
- package/build/cjs/integrations/tracing-channel/ioredis.js +14 -14
- package/build/cjs/integrations/tracing-channel/ioredis.js.map +1 -1
- package/build/cjs/integrations/tracing-channel/mysql.js +1 -1
- package/build/cjs/integrations/tracing-channel/mysql.js.map +1 -1
- package/build/cjs/integrations/tracing-channel/openai.js.map +1 -1
- package/build/cjs/integrations/tracing-channel/postgres-js.js +191 -0
- package/build/cjs/integrations/tracing-channel/postgres-js.js.map +1 -0
- package/build/cjs/integrations/tracing-channel/postgres.js +5 -5
- package/build/cjs/integrations/tracing-channel/postgres.js.map +1 -1
- package/build/cjs/integrations/tracing-channel/redis.js +227 -0
- package/build/cjs/integrations/tracing-channel/redis.js.map +1 -0
- package/build/cjs/integrations/tracing-channel/vercel-ai.js +2 -2
- package/build/cjs/integrations/tracing-channel/vercel-ai.js.map +1 -1
- package/build/cjs/mongoose/mongoose-dc-subscriber.js +1 -1
- package/build/cjs/mongoose/mongoose-dc-subscriber.js.map +1 -1
- package/build/cjs/mysql2/index.js +23 -0
- package/build/cjs/mysql2/index.js.map +1 -0
- package/build/cjs/mysql2/mysql2-dc-subscriber.js +68 -0
- package/build/cjs/mysql2/mysql2-dc-subscriber.js.map +1 -0
- package/build/cjs/orchestrion/channels.js +13 -1
- package/build/cjs/orchestrion/channels.js.map +1 -1
- package/build/cjs/orchestrion/config/amqplib.js +81 -0
- package/build/cjs/orchestrion/config/amqplib.js.map +1 -0
- package/build/cjs/orchestrion/config/express.js +76 -0
- package/build/cjs/orchestrion/config/express.js.map +1 -0
- package/build/cjs/orchestrion/config/google-genai.js +38 -0
- package/build/cjs/orchestrion/config/google-genai.js.map +1 -0
- package/build/cjs/orchestrion/config/graphql.js +28 -0
- package/build/cjs/orchestrion/config/graphql.js.map +1 -0
- package/build/cjs/orchestrion/config/index.js +15 -2
- package/build/cjs/orchestrion/config/index.js.map +1 -1
- package/build/cjs/orchestrion/config/postgres.js +50 -0
- package/build/cjs/orchestrion/config/postgres.js.map +1 -0
- package/build/cjs/orchestrion/config/redis.js +76 -0
- package/build/cjs/orchestrion/config/redis.js.map +1 -0
- package/build/cjs/orchestrion/config/vercel-ai.js +18 -14
- package/build/cjs/orchestrion/config/vercel-ai.js.map +1 -1
- package/build/cjs/orchestrion/index.js +18 -1
- package/build/cjs/orchestrion/index.js.map +1 -1
- package/build/cjs/redis/index.js +23 -0
- package/build/cjs/redis/index.js.map +1 -0
- package/build/cjs/redis/redis-dc-subscriber.js +23 -35
- package/build/cjs/redis/redis-dc-subscriber.js.map +1 -1
- package/build/cjs/tracing-channel.js +7 -6
- package/build/cjs/tracing-channel.js.map +1 -1
- package/build/cjs/vercel-ai/util.js +123 -0
- package/build/cjs/vercel-ai/util.js.map +1 -0
- package/build/cjs/vercel-ai/vercel-ai-dc-subscriber.js +138 -74
- package/build/cjs/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -1
- package/build/cjs/vercel-ai/{vercel-ai-orchestrion-v6-subscriber.js → vercel-ai-orchestrion-subscriber.js} +153 -23
- package/build/cjs/vercel-ai/vercel-ai-orchestrion-subscriber.js.map +1 -0
- package/build/esm/graphql/graphql-dc-subscriber.js +118 -0
- package/build/esm/graphql/graphql-dc-subscriber.js.map +1 -0
- package/build/esm/graphql/index.js +21 -0
- package/build/esm/graphql/index.js.map +1 -0
- package/build/esm/graphql/utils.js +81 -0
- package/build/esm/graphql/utils.js.map +1 -0
- package/build/esm/index.js +3 -1
- package/build/esm/index.js.map +1 -1
- package/build/esm/integrations/tracing-channel/amqplib.js +418 -0
- package/build/esm/integrations/tracing-channel/amqplib.js.map +1 -0
- package/build/esm/integrations/tracing-channel/anthropic.js +1 -1
- package/build/esm/integrations/tracing-channel/express/index.js +22 -0
- package/build/esm/integrations/tracing-channel/express/index.js.map +1 -0
- package/build/esm/integrations/tracing-channel/express/instrumentation.js +171 -0
- package/build/esm/integrations/tracing-channel/express/instrumentation.js.map +1 -0
- package/build/esm/integrations/tracing-channel/express/route.js +68 -0
- package/build/esm/integrations/tracing-channel/express/route.js.map +1 -0
- package/build/esm/integrations/tracing-channel/fastify/instrumentation.js +2 -2
- package/build/esm/integrations/tracing-channel/fastify/instrumentation.js.map +1 -1
- package/build/esm/integrations/tracing-channel/google-genai.js +94 -0
- package/build/esm/integrations/tracing-channel/google-genai.js.map +1 -0
- package/build/esm/integrations/tracing-channel/graphql/constants.js +14 -0
- package/build/esm/integrations/tracing-channel/graphql/constants.js.map +1 -0
- package/build/esm/integrations/tracing-channel/graphql/index.js +63 -0
- package/build/esm/integrations/tracing-channel/graphql/index.js.map +1 -0
- package/build/esm/integrations/tracing-channel/graphql/resolvers.js +164 -0
- package/build/esm/integrations/tracing-channel/graphql/resolvers.js.map +1 -0
- package/build/esm/integrations/tracing-channel/graphql/spans.js +96 -0
- package/build/esm/integrations/tracing-channel/graphql/spans.js.map +1 -0
- package/build/esm/integrations/tracing-channel/ioredis.js +15 -15
- package/build/esm/integrations/tracing-channel/ioredis.js.map +1 -1
- package/build/esm/integrations/tracing-channel/mysql.js +2 -2
- package/build/esm/integrations/tracing-channel/mysql.js.map +1 -1
- package/build/esm/integrations/tracing-channel/openai.js +1 -1
- package/build/esm/integrations/tracing-channel/openai.js.map +1 -1
- package/build/esm/integrations/tracing-channel/postgres-js.js +189 -0
- package/build/esm/integrations/tracing-channel/postgres-js.js.map +1 -0
- package/build/esm/integrations/tracing-channel/postgres.js +6 -6
- package/build/esm/integrations/tracing-channel/postgres.js.map +1 -1
- package/build/esm/integrations/tracing-channel/redis.js +225 -0
- package/build/esm/integrations/tracing-channel/redis.js.map +1 -0
- package/build/esm/integrations/tracing-channel/vercel-ai.js +1 -1
- package/build/esm/integrations/tracing-channel/vercel-ai.js.map +1 -1
- package/build/esm/mongoose/mongoose-dc-subscriber.js +2 -2
- package/build/esm/mongoose/mongoose-dc-subscriber.js.map +1 -1
- package/build/esm/mysql2/index.js +21 -0
- package/build/esm/mysql2/index.js.map +1 -0
- package/build/esm/mysql2/mysql2-dc-subscriber.js +62 -0
- package/build/esm/mysql2/mysql2-dc-subscriber.js.map +1 -0
- package/build/esm/orchestrion/channels.js +13 -1
- package/build/esm/orchestrion/channels.js.map +1 -1
- package/build/esm/orchestrion/config/amqplib.js +78 -0
- package/build/esm/orchestrion/config/amqplib.js.map +1 -0
- package/build/esm/orchestrion/config/express.js +73 -0
- package/build/esm/orchestrion/config/express.js.map +1 -0
- package/build/esm/orchestrion/config/google-genai.js +35 -0
- package/build/esm/orchestrion/config/google-genai.js.map +1 -0
- package/build/esm/orchestrion/config/graphql.js +25 -0
- package/build/esm/orchestrion/config/graphql.js.map +1 -0
- package/build/esm/orchestrion/config/index.js +15 -2
- package/build/esm/orchestrion/config/index.js.map +1 -1
- package/build/esm/orchestrion/config/postgres.js +47 -0
- package/build/esm/orchestrion/config/postgres.js.map +1 -0
- package/build/esm/orchestrion/config/redis.js +73 -0
- package/build/esm/orchestrion/config/redis.js.map +1 -0
- package/build/esm/orchestrion/config/vercel-ai.js +18 -14
- package/build/esm/orchestrion/config/vercel-ai.js.map +1 -1
- package/build/esm/orchestrion/index.js +14 -2
- package/build/esm/orchestrion/index.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/esm/redis/index.js +21 -0
- package/build/esm/redis/index.js.map +1 -0
- package/build/esm/redis/redis-dc-subscriber.js +24 -36
- package/build/esm/redis/redis-dc-subscriber.js.map +1 -1
- package/build/esm/tracing-channel.js +8 -7
- package/build/esm/tracing-channel.js.map +1 -1
- package/build/esm/vercel-ai/util.js +116 -0
- package/build/esm/vercel-ai/util.js.map +1 -0
- package/build/esm/vercel-ai/vercel-ai-dc-subscriber.js +112 -50
- package/build/esm/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -1
- package/build/esm/vercel-ai/{vercel-ai-orchestrion-v6-subscriber.js → vercel-ai-orchestrion-subscriber.js} +153 -23
- package/build/esm/vercel-ai/vercel-ai-orchestrion-subscriber.js.map +1 -0
- package/build/types/graphql/graphql-dc-subscriber.d.ts +94 -0
- package/build/types/graphql/graphql-dc-subscriber.d.ts.map +1 -0
- package/build/types/graphql/index.d.ts +12 -0
- package/build/types/graphql/index.d.ts.map +1 -0
- package/build/types/graphql/utils.d.ts +40 -0
- package/build/types/graphql/utils.d.ts.map +1 -0
- package/build/types/index.d.ts +4 -2
- package/build/types/index.d.ts.map +1 -1
- package/build/types/integrations/tracing-channel/amqplib.d.ts +11 -0
- package/build/types/integrations/tracing-channel/amqplib.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/express/index.d.ts +18 -0
- package/build/types/integrations/tracing-channel/express/index.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/express/instrumentation.d.ts +4 -0
- package/build/types/integrations/tracing-channel/express/instrumentation.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/express/route.d.ts +28 -0
- package/build/types/integrations/tracing-channel/express/route.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/express/types.d.ts +64 -0
- package/build/types/integrations/tracing-channel/express/types.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/fastify/instrumentation.d.ts.map +1 -1
- package/build/types/integrations/tracing-channel/google-genai.d.ts +12 -0
- package/build/types/integrations/tracing-channel/google-genai.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/graphql/constants.d.ts +12 -0
- package/build/types/integrations/tracing-channel/graphql/constants.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/graphql/graphql-types.d.ts +135 -0
- package/build/types/integrations/tracing-channel/graphql/graphql-types.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/graphql/index.d.ts +28 -0
- package/build/types/integrations/tracing-channel/graphql/index.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/graphql/resolvers.d.ts +13 -0
- package/build/types/integrations/tracing-channel/graphql/resolvers.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/graphql/spans.d.ts +17 -0
- package/build/types/integrations/tracing-channel/graphql/spans.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/graphql/types.d.ts +25 -0
- package/build/types/integrations/tracing-channel/graphql/types.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/ioredis.d.ts.map +1 -1
- package/build/types/integrations/tracing-channel/mysql.d.ts.map +1 -1
- package/build/types/integrations/tracing-channel/openai.d.ts.map +1 -1
- package/build/types/integrations/tracing-channel/postgres-js.d.ts +26 -0
- package/build/types/integrations/tracing-channel/postgres-js.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/postgres.d.ts.map +1 -1
- package/build/types/integrations/tracing-channel/redis.d.ts +16 -0
- package/build/types/integrations/tracing-channel/redis.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/vercel-ai.d.ts +1 -1
- package/build/types/mongoose/mongoose-dc-subscriber.d.ts.map +1 -1
- package/build/types/mysql2/index.d.ts +11 -0
- package/build/types/mysql2/index.d.ts.map +1 -0
- package/build/types/mysql2/mysql2-dc-subscriber.d.ts +59 -0
- package/build/types/mysql2/mysql2-dc-subscriber.d.ts.map +1 -0
- package/build/types/orchestrion/channels.d.ts +34 -0
- package/build/types/orchestrion/channels.d.ts.map +1 -1
- package/build/types/orchestrion/config/amqplib.d.ts +66 -0
- package/build/types/orchestrion/config/amqplib.d.ts.map +1 -0
- package/build/types/orchestrion/config/express.d.ts +32 -0
- package/build/types/orchestrion/config/express.d.ts.map +1 -0
- package/build/types/orchestrion/config/google-genai.d.ts +30 -0
- package/build/types/orchestrion/config/google-genai.d.ts.map +1 -0
- package/build/types/orchestrion/config/graphql.d.ts +29 -0
- package/build/types/orchestrion/config/graphql.d.ts.map +1 -0
- package/build/types/orchestrion/config/index.d.ts.map +1 -1
- package/build/types/orchestrion/config/postgres.d.ts +9 -0
- package/build/types/orchestrion/config/postgres.d.ts.map +1 -0
- package/build/types/orchestrion/config/redis.d.ts +37 -0
- package/build/types/orchestrion/config/redis.d.ts.map +1 -0
- package/build/types/orchestrion/config/vercel-ai.d.ts +1 -0
- package/build/types/orchestrion/config/vercel-ai.d.ts.map +1 -1
- package/build/types/orchestrion/index.d.ts +31 -4
- package/build/types/orchestrion/index.d.ts.map +1 -1
- package/build/types/redis/index.d.ts +18 -0
- package/build/types/redis/index.d.ts.map +1 -0
- package/build/types/redis/redis-dc-subscriber.d.ts +0 -5
- package/build/types/redis/redis-dc-subscriber.d.ts.map +1 -1
- package/build/types/tracing-channel.d.ts +5 -0
- package/build/types/tracing-channel.d.ts.map +1 -1
- package/build/types/vercel-ai/util.d.ts +32 -0
- package/build/types/vercel-ai/util.d.ts.map +1 -0
- package/build/types/vercel-ai/vercel-ai-dc-subscriber.d.ts +6 -2
- package/build/types/vercel-ai/vercel-ai-dc-subscriber.d.ts.map +1 -1
- package/build/types/vercel-ai/{vercel-ai-orchestrion-v6-subscriber.d.ts → vercel-ai-orchestrion-subscriber.d.ts} +1 -1
- package/build/types/vercel-ai/vercel-ai-orchestrion-subscriber.d.ts.map +1 -0
- package/build/types-ts3.8/graphql/graphql-dc-subscriber.d.ts +94 -0
- package/build/types-ts3.8/graphql/index.d.ts +12 -0
- package/build/types-ts3.8/graphql/utils.d.ts +40 -0
- package/build/types-ts3.8/index.d.ts +4 -2
- package/build/types-ts3.8/integrations/tracing-channel/amqplib.d.ts +11 -0
- package/build/types-ts3.8/integrations/tracing-channel/express/index.d.ts +18 -0
- package/build/types-ts3.8/integrations/tracing-channel/express/instrumentation.d.ts +4 -0
- package/build/types-ts3.8/integrations/tracing-channel/express/route.d.ts +28 -0
- package/build/types-ts3.8/integrations/tracing-channel/express/types.d.ts +64 -0
- package/build/types-ts3.8/integrations/tracing-channel/google-genai.d.ts +12 -0
- package/build/types-ts3.8/integrations/tracing-channel/graphql/constants.d.ts +12 -0
- package/build/types-ts3.8/integrations/tracing-channel/graphql/graphql-types.d.ts +135 -0
- package/build/types-ts3.8/integrations/tracing-channel/graphql/index.d.ts +30 -0
- package/build/types-ts3.8/integrations/tracing-channel/graphql/resolvers.d.ts +13 -0
- package/build/types-ts3.8/integrations/tracing-channel/graphql/spans.d.ts +17 -0
- package/build/types-ts3.8/integrations/tracing-channel/graphql/types.d.ts +25 -0
- package/build/types-ts3.8/integrations/tracing-channel/postgres-js.d.ts +26 -0
- package/build/types-ts3.8/integrations/tracing-channel/redis.d.ts +16 -0
- package/build/types-ts3.8/integrations/tracing-channel/vercel-ai.d.ts +1 -1
- package/build/types-ts3.8/mysql2/index.d.ts +11 -0
- package/build/types-ts3.8/mysql2/mysql2-dc-subscriber.d.ts +59 -0
- package/build/types-ts3.8/orchestrion/channels.d.ts +34 -0
- package/build/types-ts3.8/orchestrion/config/amqplib.d.ts +66 -0
- package/build/types-ts3.8/orchestrion/config/express.d.ts +32 -0
- package/build/types-ts3.8/orchestrion/config/google-genai.d.ts +30 -0
- package/build/types-ts3.8/orchestrion/config/graphql.d.ts +29 -0
- package/build/types-ts3.8/orchestrion/config/postgres.d.ts +9 -0
- package/build/types-ts3.8/orchestrion/config/redis.d.ts +37 -0
- package/build/types-ts3.8/orchestrion/config/vercel-ai.d.ts +1 -0
- package/build/types-ts3.8/orchestrion/index.d.ts +33 -4
- package/build/types-ts3.8/redis/index.d.ts +18 -0
- package/build/types-ts3.8/redis/redis-dc-subscriber.d.ts +0 -5
- package/build/types-ts3.8/tracing-channel.d.ts +5 -0
- package/build/types-ts3.8/vercel-ai/util.d.ts +32 -0
- package/build/types-ts3.8/vercel-ai/vercel-ai-dc-subscriber.d.ts +6 -2
- package/build/types-ts3.8/vercel-ai/{vercel-ai-orchestrion-v6-subscriber.d.ts → vercel-ai-orchestrion-subscriber.d.ts} +1 -1
- package/package.json +2 -2
- package/build/cjs/vercel-ai/vercel-ai-orchestrion-v6-subscriber.js.map +0 -1
- package/build/esm/vercel-ai/vercel-ai-orchestrion-v6-subscriber.js.map +0 -1
- package/build/types/vercel-ai/vercel-ai-orchestrion-v6-subscriber.d.ts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tracing-channel.js","sources":["../../src/tracing-channel.ts"],"sourcesContent":["import type { TracingChannel, TracingChannelSubscribers } from 'node:diagnostics_channel';\nimport type { AsyncLocalStorage } from 'node:async_hooks';\nimport type { ExclusiveEventHintOrCaptureContext, Span } from '@sentry/core';\nimport { debug, captureException, SPAN_STATUS_ERROR, getAsyncContextStrategy, getMainCarrier } from '@sentry/core';\nimport { DEBUG_BUILD } from './debug-build';\nimport { ERROR_TYPE } from '@sentry/conventions/attributes';\n\nexport type TracingChannelPayloadWithSpan<TData extends object> = TData & {\n /**\n * The current active span for the traced call.\n */\n _sentrySpan?: Span;\n\n /**\n * The context's active store value, used to restore the context for asyncStart continuations for callback-based tracing.\n */\n _sentryCallerStore?: unknown;\n};\n\n/*\n * A type patch so that we don't have to handle all subscription types.\n */\nexport interface SentryTracingChannel<TData extends object = object> extends Omit<\n TracingChannel<TData, TracingChannelPayloadWithSpan<TData>>,\n 'subscribe' | 'unsubscribe'\n> {\n subscribe(subscribers: Partial<TracingChannelSubscribers<TracingChannelPayloadWithSpan<TData>>>): void;\n unsubscribe(subscribers: Partial<TracingChannelSubscribers<TracingChannelPayloadWithSpan<TData>>>): void;\n}\n\nexport interface TracingChannelLifeCycleOptions<TData extends object = object> {\n /**\n * Invoked with the span and the channel context object once the traced operation completes\n * Use it to enrich the span from the result/error (branch on `'error' in data` / `'result' in data`) or to run cleanup.\n */\n beforeSpanEnd?: (span: Span, data: TracingChannelPayloadWithSpan<TData>) => void;\n\n /**\n * Whether a thrown error is captured as a Sentry event. The span is always marked with error status regardless. Defaults to `false`.\n * You can alternatively pass a function that sets the ExclusiveEventHintOrCaptureContext on the captured error.\n * Set `true` for instrumentations that own the error boundary, (e.g: route handlers)\n * For database drivers, it is not recommended to set this at all.\n */\n captureError?: boolean | ((e: unknown) => ExclusiveEventHintOrCaptureContext);\n\n /**\n * Take ownership of *when* the span ends: return `true` and the helper won't end it on\n * `end`/`asyncEnd`. For results that settle out-of-band — e.g. a streamed `EventEmitter` that\n * completes via its own `'end'`/`'error'` events.\n *\n * Call `end` when it settles — `end()` on success, `end(error)` on failure. `end` owns *how* the span\n * ends (error status/attributes, `captureError`, `beforeSpanEnd`) and is idempotent. Default `false`\n * lets the helper end the span as usual.\n */\n deferSpanEnd?: (args: {\n span: Span;\n data: TracingChannelPayloadWithSpan<TData>;\n /** Ends the span: `end()` on success, `end(error)` on failure. Idempotent. */\n end: (error?: unknown) => void;\n }) => boolean;\n}\n\n/** Returned by {@link bindTracingChannelToSpan}: the bound channel plus a teardown handle. */\nexport interface TracingChannelBindingHandle<TData extends object = object> {\n /**\n * The tracing channel with the span bound into async context.\n */\n channel: SentryTracingChannel<TData>;\n\n /**\n * Tears down the binding: unsubscribes lifecycle handlers, when present, and unbinds the start store.\n * Idempotent, and a no-op when no async context binding was available.\n */\n unbind: () => void;\n}\n\nconst NOOP = (): void => {};\n\n/**\n * Bind a span and its lifecycle to a tracing channel so the span becomes the active async context\n * for the traced operation and is ended when the operation completes.\n *\n * `getSpan` may return `undefined` to opt a payload out entirely: nothing is bound, no span is\n * tracked, and the active context is left untouched. Use it for events that ride the same channel\n * but should reuse the enclosing span instead of opening (and ending) their own — e.g. an agent\n * loop's per-step events, where ending a freshly opened span would close the parent prematurely.\n */\nexport function bindTracingChannelToSpan<TData extends object>(\n channel: TracingChannel<TData, TData>,\n getSpan: (data: TracingChannelPayloadWithSpan<TData>) => Span | undefined,\n opts?: TracingChannelLifeCycleOptions<TData>,\n): TracingChannelBindingHandle<TData> {\n const handle = bindSpanToChannelStore(channel, getSpan);\n\n const beforeSpanEnd = opts?.beforeSpanEnd;\n const deferSpanEnd = opts?.deferSpanEnd;\n const getErrorHint = (e: unknown): ExclusiveEventHintOrCaptureContext => {\n if (typeof opts?.captureError === 'function') {\n return opts.captureError(e);\n }\n\n return {\n mechanism: {\n type: 'auto.diagnostic_channels.bind_span',\n handled: false,\n },\n };\n };\n\n // Apply Sentry error status + attributes (and capture, if configured) to a span. Shared by the\n // channel `error` lifecycle and the deferred `end` util so the two can't drift.\n const annotateSpanError = (span: Span, error: unknown): void => {\n if (opts?.captureError) {\n captureException(error, getErrorHint(error));\n }\n\n const { message, attributes } = getErrorInfo(error);\n span.setStatus({ code: SPAN_STATUS_ERROR, message });\n span.setAttributes(attributes);\n };\n\n // Creates an end fn for deferred handlers to use, ensures consistent span end behavior\n const makeDeferredEnd = (span: Span, data: TracingChannelPayloadWithSpan<TData>) => {\n let ended = false;\n\n return (error?: unknown): void => {\n if (ended) {\n return;\n }\n\n ended = true;\n if (error !== undefined) {\n annotateSpanError(span, error);\n }\n\n endBoundSpan(data, beforeSpanEnd);\n };\n };\n\n const subscribers: Partial<TracingChannelSubscribers<TracingChannelPayloadWithSpan<TData>>> = {\n start: NOOP,\n asyncStart: NOOP,\n end(data) {\n // The operation settled synchronously (returned or threw)\n // Presence checks because caller can return `undefined` result or throw a falsy value.\n if ('error' in data || 'result' in data) {\n const span = data._sentrySpan;\n if (span && deferSpanEnd?.({ span, data, end: makeDeferredEnd(span, data) })) {\n return;\n }\n endBoundSpan(data, beforeSpanEnd);\n }\n },\n error(data) {\n // No span was bound for this payload (`getSpan` returned undefined), so there is nothing to\n // annotate and no instrumentation that owns capturing this error.\n const span = data._sentrySpan;\n if (!span) {\n return;\n }\n\n annotateSpanError(span, data.error);\n },\n asyncEnd(data) {\n const span = data._sentrySpan;\n if (span && deferSpanEnd?.({ span, data, end: makeDeferredEnd(span, data) })) {\n return;\n }\n endBoundSpan(data, beforeSpanEnd);\n },\n };\n\n handle.channel.subscribe(subscribers);\n\n return {\n channel: handle.channel,\n unbind: () => {\n handle.channel.unsubscribe(subscribers);\n handle.unbind();\n },\n };\n}\n\n/**\n * Bind a span into the channel's async context so it becomes active for the traced operation,\n * without managing its lifecycle. The primitive behind {@link bindTracingChannelToSpan}, which\n * layers span-ending and error handling on top.\n *\n * `getSpan` may return `undefined` to leave the active context untouched for that payload.\n */\nfunction bindSpanToChannelStore<TData extends object>(\n channel: TracingChannel<TData, TData>,\n getSpan: (data: TracingChannelPayloadWithSpan<TData>) => Span | undefined,\n): TracingChannelBindingHandle<TData> {\n // Grabs the tracing channel binding defined by the AsyncContext strategy implementation\n const binding = getAsyncContextStrategy(getMainCarrier()).getTracingChannelBinding?.();\n\n // If no binding, then either the implementer doesn't support tracing channels or there is no active strategy\n // Failure mode here means we would still access the channel and potentially subscribe to it, but parenting will be off.\n if (!binding) {\n DEBUG_BUILD && debug.log('[TracingChannel] Could not access async context binding.');\n\n return {\n channel,\n unbind: NOOP,\n };\n }\n\n // Grab the ALS instance, we don't really care what is in it as long as the AsyncContext strategy can use its value to figure out parenting.\n const asyncLocalStorage = binding.asyncLocalStorage as AsyncLocalStorage<TData>;\n\n // bindStore activates the ALS for the traced call; any getStore() inside it returns the value bound for that context.\n // 1. Produce: getStoreWithActiveSpan(span) clones the current scope, plants the span via _INTERNAL_setSpanForScope, and returns { scope, isolationScope }, the active context carrying our span.\n // 2. Bind: the courier hands that opaque value to channel.start.bindStore(asyncLocalStorage, producer), which runs the traced op inside asyncLocalStorage.run(value, …); it never inspects the value.\n // 3. Read: inside the op, Sentry's scope machinery calls getScopes() → asyncStorage.getStore() on that same ALS, so getCurrentScope/getIsolationScope/getActiveSpan resolve to the scope carrying our span.\n // 4. Nest: any child span started in the traced op parents to that active span.\n channel.start.bindStore(asyncLocalStorage, (data: TracingChannelPayloadWithSpan<TData>) => {\n // Stash the caller's store before we swap in the span store, so `asyncStart` can restore it for\n // callback-style channels (see `_sentryCallerStore`).\n data._sentryCallerStore = asyncLocalStorage.getStore();\n\n const span = getSpan(data);\n if (!span) {\n // Leave the active context untouched so nested operations keep parenting to the enclosing span.\n return data._sentryCallerStore as TData;\n }\n data._sentrySpan = span;\n\n return binding.getStoreWithActiveSpan(span) as TData;\n });\n\n // Restore the caller's context for the async continuation. Only callback-style channels `runStores`\n // `asyncStart` (so the callback runs inside this store). promise channels `publish` it, leaving this\n // inert, their continuation already inherits the caller's context natively.\n channel.asyncStart.bindStore(asyncLocalStorage, (data: TracingChannelPayloadWithSpan<TData>) => {\n return data._sentryCallerStore as TData;\n });\n\n return {\n channel,\n unbind: () => {\n // Removes the stores\n channel.start.unbindStore(asyncLocalStorage);\n channel.asyncStart.unbindStore(asyncLocalStorage);\n },\n };\n}\n\nfunction endBoundSpan<TData extends object>(\n data: TracingChannelPayloadWithSpan<TData>,\n beforeSpanEnd: TracingChannelLifeCycleOptions<TData>['beforeSpanEnd'],\n): void {\n const span = data._sentrySpan;\n if (!span) {\n return;\n }\n beforeSpanEnd?.(span, data);\n span.end();\n}\n\ntype ErrorInfo = {\n message: string | undefined;\n attributes: Record<string, string>;\n};\n\n/**\n * Best-effort message and attribute extraction for thrown/rejected values.\n */\nfunction getErrorInfo(error: unknown): ErrorInfo {\n const isObject = !!error && typeof error === 'object';\n const raw = isObject ? ('message' in error ? error.message : undefined) : error;\n\n // Leave the status message unset if not set (e.g. an `AggregateError` from\n // ECONNREFUSED, whose `.message` is empty). Otherwise cast to string.\n const message = raw ? String(raw) : undefined;\n const type = isObject && 'name' in error ? String(error.name) : 'unknown';\n\n return {\n message,\n attributes: {\n [ERROR_TYPE]: type,\n },\n };\n}\n"],"names":[],"mappings":";;;;AA4EA,MAAM,OAAO,MAAY;AAAC,CAAA;AAWnB,SAAS,wBAAA,CACd,OAAA,EACA,OAAA,EACA,IAAA,EACoC;AACpC,EAAA,MAAM,MAAA,GAAS,sBAAA,CAAuB,OAAA,EAAS,OAAO,CAAA;AAEtD,EAAA,MAAM,gBAAgB,IAAA,EAAM,aAAA;AAC5B,EAAA,MAAM,eAAe,IAAA,EAAM,YAAA;AAC3B,EAAA,MAAM,YAAA,GAAe,CAAC,CAAA,KAAmD;AACvE,IAAA,IAAI,OAAO,IAAA,EAAM,YAAA,KAAiB,UAAA,EAAY;AAC5C,MAAA,OAAO,IAAA,CAAK,aAAa,CAAC,CAAA;AAAA,IAC5B;AAEA,IAAA,OAAO;AAAA,MACL,SAAA,EAAW;AAAA,QACT,IAAA,EAAM,oCAAA;AAAA,QACN,OAAA,EAAS;AAAA;AACX,KACF;AAAA,EACF,CAAA;AAIA,EAAA,MAAM,iBAAA,GAAoB,CAAC,IAAA,EAAY,KAAA,KAAyB;AAC9D,IAAA,IAAI,MAAM,YAAA,EAAc;AACtB,MA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B,GACF;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"tracing-channel.js","sources":["../../src/tracing-channel.ts"],"sourcesContent":["import type { TracingChannel, TracingChannelSubscribers } from 'node:diagnostics_channel';\nimport type { AsyncLocalStorage } from 'node:async_hooks';\nimport type { ExclusiveEventHintOrCaptureContext, Span } from '@sentry/core';\nimport {\n debug,\n captureException,\n isObjectLike,\n SPAN_STATUS_ERROR,\n getAsyncContextStrategy,\n getMainCarrier,\n getActiveSpan,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from './debug-build';\nimport { ERROR_TYPE } from '@sentry/conventions/attributes';\n\nexport type TracingChannelPayloadWithSpan<TData extends object> = TData & {\n /**\n * The current active span for the traced call.\n */\n _sentrySpan?: Span;\n\n /**\n * The context's active store value, used to restore the context for asyncStart continuations for callback-based tracing.\n */\n _sentryCallerStore?: unknown;\n};\n\n/*\n * A type patch so that we don't have to handle all subscription types.\n */\nexport interface SentryTracingChannel<TData extends object = object> extends Omit<\n TracingChannel<TData, TracingChannelPayloadWithSpan<TData>>,\n 'subscribe' | 'unsubscribe'\n> {\n subscribe(subscribers: Partial<TracingChannelSubscribers<TracingChannelPayloadWithSpan<TData>>>): void;\n unsubscribe(subscribers: Partial<TracingChannelSubscribers<TracingChannelPayloadWithSpan<TData>>>): void;\n}\n\nexport interface TracingChannelLifeCycleOptions<TData extends object = object> {\n /**\n * Invoked with the span and the channel context object once the traced operation completes\n * Use it to enrich the span from the result/error (branch on `'error' in data` / `'result' in data`) or to run cleanup.\n */\n beforeSpanEnd?: (span: Span, data: TracingChannelPayloadWithSpan<TData>) => void;\n\n /**\n * Whether a thrown error is captured as a Sentry event. The span is always marked with error status regardless. Defaults to `false`.\n * You can alternatively pass a function that sets the ExclusiveEventHintOrCaptureContext on the captured error.\n * Set `true` for instrumentations that own the error boundary, (e.g: route handlers)\n * For database drivers, it is not recommended to set this at all.\n */\n captureError?: boolean | ((e: unknown) => ExclusiveEventHintOrCaptureContext);\n\n /**\n * Take ownership of *when* the span ends: return `true` and the helper won't end it on\n * `end`/`asyncEnd`. For results that settle out-of-band — e.g. a streamed `EventEmitter` that\n * completes via its own `'end'`/`'error'` events.\n *\n * Call `end` when it settles — `end()` on success, `end(error)` on failure. `end` owns *how* the span\n * ends (error status/attributes, `captureError`, `beforeSpanEnd`) and is idempotent. Default `false`\n * lets the helper end the span as usual.\n */\n deferSpanEnd?: (args: {\n span: Span;\n data: TracingChannelPayloadWithSpan<TData>;\n /** Ends the span: `end()` on success, `end(error)` on failure. Idempotent. */\n end: (error?: unknown) => void;\n }) => boolean;\n\n /**\n * Apply span/scope binding only if there is a parent span, similar to returning `undefined` in the `getSpan` callback.\n * If you need to perform some conditional checking on the parent span before deciding, do it in the `getSpan` callback.\n */\n requiresParentSpan?: boolean;\n}\n\n/** Returned by {@link bindTracingChannelToSpan}: the bound channel plus a teardown handle. */\nexport interface TracingChannelBindingHandle<TData extends object = object> {\n /**\n * The tracing channel with the span bound into async context.\n */\n channel: SentryTracingChannel<TData>;\n\n /**\n * Tears down the binding: unsubscribes lifecycle handlers, when present, and unbinds the start store.\n * Idempotent, and a no-op when no async context binding was available.\n */\n unbind: () => void;\n}\n\nconst NOOP = (): void => {};\n\n/**\n * Bind a span and its lifecycle to a tracing channel so the span becomes the active async context\n * for the traced operation and is ended when the operation completes.\n *\n * `getSpan` may return `undefined` to opt a payload out entirely: nothing is bound, no span is\n * tracked, and the active context is left untouched. Use it for events that ride the same channel\n * but should reuse the enclosing span instead of opening (and ending) their own — e.g. an agent\n * loop's per-step events, where ending a freshly opened span would close the parent prematurely.\n */\nexport function bindTracingChannelToSpan<TData extends object>(\n channel: TracingChannel<TData, TData>,\n getSpan: (data: TracingChannelPayloadWithSpan<TData>) => Span | undefined,\n opts?: TracingChannelLifeCycleOptions<TData>,\n): TracingChannelBindingHandle<TData> {\n const handle = bindSpanToChannelStore(channel, getSpan, opts);\n\n const beforeSpanEnd = opts?.beforeSpanEnd;\n const deferSpanEnd = opts?.deferSpanEnd;\n const getErrorHint = (e: unknown): ExclusiveEventHintOrCaptureContext => {\n if (typeof opts?.captureError === 'function') {\n return opts.captureError(e);\n }\n\n return {\n mechanism: {\n type: 'auto.diagnostic_channels.bind_span',\n handled: false,\n },\n };\n };\n\n // Apply Sentry error status + attributes (and capture, if configured) to a span. Shared by the\n // channel `error` lifecycle and the deferred `end` util so the two can't drift.\n const annotateSpanError = (span: Span, error: unknown): void => {\n if (opts?.captureError) {\n captureException(error, getErrorHint(error));\n }\n\n const { message, attributes } = getErrorInfo(error);\n span.setStatus({ code: SPAN_STATUS_ERROR, message });\n span.setAttributes(attributes);\n };\n\n // Creates an end fn for deferred handlers to use, ensures consistent span end behavior\n const makeDeferredEnd = (span: Span, data: TracingChannelPayloadWithSpan<TData>) => {\n let ended = false;\n\n return (error?: unknown): void => {\n if (ended) {\n return;\n }\n\n ended = true;\n if (error !== undefined) {\n annotateSpanError(span, error);\n }\n\n endBoundSpan(data, beforeSpanEnd);\n };\n };\n\n const subscribers: Partial<TracingChannelSubscribers<TracingChannelPayloadWithSpan<TData>>> = {\n start: NOOP,\n asyncStart: NOOP,\n end(data) {\n // The operation settled synchronously (returned or threw)\n // Presence checks because caller can return `undefined` result or throw a falsy value.\n if ('error' in data || 'result' in data) {\n const span = data._sentrySpan;\n if (span && deferSpanEnd?.({ span, data, end: makeDeferredEnd(span, data) })) {\n return;\n }\n endBoundSpan(data, beforeSpanEnd);\n }\n },\n error(data) {\n // No span was bound for this payload (`getSpan` returned undefined), so there is nothing to\n // annotate and no instrumentation that owns capturing this error.\n const span = data._sentrySpan;\n if (!span) {\n return;\n }\n\n annotateSpanError(span, data.error);\n },\n asyncEnd(data) {\n const span = data._sentrySpan;\n if (span && deferSpanEnd?.({ span, data, end: makeDeferredEnd(span, data) })) {\n return;\n }\n endBoundSpan(data, beforeSpanEnd);\n },\n };\n\n handle.channel.subscribe(subscribers);\n\n return {\n channel: handle.channel,\n unbind: () => {\n handle.channel.unsubscribe(subscribers);\n handle.unbind();\n },\n };\n}\n\n/**\n * Bind a span into the channel's async context so it becomes active for the traced operation,\n * without managing its lifecycle. The primitive behind {@link bindTracingChannelToSpan}, which\n * layers span-ending and error handling on top.\n *\n * `getSpan` may return `undefined` to leave the active context untouched for that payload.\n */\nfunction bindSpanToChannelStore<TData extends object>(\n channel: TracingChannel<TData, TData>,\n getSpan: (data: TracingChannelPayloadWithSpan<TData>) => Span | undefined,\n opts?: Pick<TracingChannelLifeCycleOptions, 'requiresParentSpan'>,\n): TracingChannelBindingHandle<TData> {\n // Grabs the tracing channel binding defined by the AsyncContext strategy implementation\n const binding = getAsyncContextStrategy(getMainCarrier()).getTracingChannelBinding?.();\n\n // If no binding, then either the implementer doesn't support tracing channels or there is no active strategy\n // Failure mode here means we would still access the channel and potentially subscribe to it, but parenting will be off.\n if (!binding) {\n DEBUG_BUILD && debug.log('[TracingChannel] Could not access async context binding.');\n\n return {\n channel,\n unbind: NOOP,\n };\n }\n\n // Grab the ALS instance, we don't really care what is in it as long as the AsyncContext strategy can use its value to figure out parenting.\n const asyncLocalStorage = binding.asyncLocalStorage as AsyncLocalStorage<TData>;\n\n // bindStore activates the ALS for the traced call; any getStore() inside it returns the value bound for that context.\n // 1. Produce: getStoreWithActiveSpan(span) clones the current scope, plants the span via _INTERNAL_setSpanForScope, and returns { scope, isolationScope }, the active context carrying our span.\n // 2. Bind: the courier hands that opaque value to channel.start.bindStore(asyncLocalStorage, producer), which runs the traced op inside asyncLocalStorage.run(value, …); it never inspects the value.\n // 3. Read: inside the op, Sentry's scope machinery calls getScopes() → asyncStorage.getStore() on that same ALS, so getCurrentScope/getIsolationScope/getActiveSpan resolve to the scope carrying our span.\n // 4. Nest: any child span started in the traced op parents to that active span.\n channel.start.bindStore(asyncLocalStorage, (data: TracingChannelPayloadWithSpan<TData>) => {\n // Stash the caller's store before we swap in the span store, so `asyncStart` can restore it for\n // callback-style channels (see `_sentryCallerStore`).\n data._sentryCallerStore = asyncLocalStorage.getStore();\n\n const shouldGetSpan = !opts?.requiresParentSpan || getActiveSpan();\n const span = shouldGetSpan ? getSpan(data) : undefined;\n if (!span) {\n // Leave the active context untouched so nested operations keep parenting to the enclosing span.\n return data._sentryCallerStore as TData;\n }\n data._sentrySpan = span;\n\n return binding.getStoreWithActiveSpan(span) as TData;\n });\n\n // Restore the caller's context for the async continuation. Only callback-style channels `runStores`\n // `asyncStart` (so the callback runs inside this store). promise channels `publish` it, leaving this\n // inert, their continuation already inherits the caller's context natively.\n channel.asyncStart.bindStore(asyncLocalStorage, (data: TracingChannelPayloadWithSpan<TData>) => {\n return data._sentryCallerStore as TData;\n });\n\n return {\n channel,\n unbind: () => {\n // Removes the stores\n channel.start.unbindStore(asyncLocalStorage);\n channel.asyncStart.unbindStore(asyncLocalStorage);\n },\n };\n}\n\nfunction endBoundSpan<TData extends object>(\n data: TracingChannelPayloadWithSpan<TData>,\n beforeSpanEnd: TracingChannelLifeCycleOptions<TData>['beforeSpanEnd'],\n): void {\n const span = data._sentrySpan;\n if (!span) {\n return;\n }\n beforeSpanEnd?.(span, data);\n span.end();\n}\n\ntype ErrorInfo = {\n message: string | undefined;\n attributes: Record<string, string>;\n};\n\n/**\n * Best-effort message and attribute extraction for thrown/rejected values.\n */\nfunction getErrorInfo(error: unknown): ErrorInfo {\n const errorIsObject = isObjectLike(error);\n const raw = errorIsObject ? ('message' in error ? error.message : undefined) : error;\n\n // Leave the status message unset if not set (e.g. an `AggregateError` from\n // ECONNREFUSED, whose `.message` is empty). Otherwise cast to string.\n const message = raw ? String(raw) : undefined;\n const type = errorIsObject && 'name' in error ? String(error.name) : 'unknown';\n\n return {\n message,\n attributes: {\n [ERROR_TYPE]: type,\n },\n };\n}\n"],"names":[],"mappings":";;;;AA0FA,MAAM,OAAO,MAAY;AAAC,CAAA;AAWnB,SAAS,wBAAA,CACd,OAAA,EACA,OAAA,EACA,IAAA,EACoC;AACpC,EAAA,MAAM,MAAA,GAAS,sBAAA,CAAuB,OAAA,EAAS,OAAA,EAAS,IAAI,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AClB,EAAA,IAAI,CAAC,IAAA,EAAM;AACT,IAAA;AAAA,EACF;AACA,EAAA,aAAA,GAAgB,MAAM,IAAI,CAAA;AAC1B,EAAA,IAAA,CAAK,GAAA,EAAI;AACX;AAUA,SAAS,aAAa,KAAA,EAA2B;AAC/C,EAAA,MAAM,aAAA,GAAgB,aAAa,KAAK,CAAA;AACxC,EAAA,MAAM,MAAM,aAAA,GAAiB,SAAA,IAAa,KAAA,GAAQ,KAAA,CAAM,UAAU,MAAA,GAAa,KAAA;AAI/E,EAAA,MAAM,OAAA,GAAU,GAAA,GAAM,MAAA,CAAO,GAAG,CAAA,GAAI,MAAA;AACpC,EAAA,MAAM,OAAO,aAAA,IAAiB,MAAA,IAAU,QAAQ,MAAA,CAAO,KAAA,CAAM,IAAI,CAAA,GAAI,SAAA;AAErE,EAAA,OAAO;AAAA,IACL,OAAA;AAAA,IACA,UAAA,EAAY;AAAA,MACV,CAAC,UAAU,GAAG;AAAA;AAChB,GACF;AACF;;;;"}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { isObjectLike } from '@sentry/core';
|
|
2
|
+
|
|
3
|
+
function asString(value) {
|
|
4
|
+
return typeof value === "string" ? value : void 0;
|
|
5
|
+
}
|
|
6
|
+
function asNumber(value) {
|
|
7
|
+
return typeof value === "number" && !isNaN(value) ? value : void 0;
|
|
8
|
+
}
|
|
9
|
+
function sum(a, b) {
|
|
10
|
+
return a === void 0 && b === void 0 ? void 0 : (a ?? 0) + (b ?? 0);
|
|
11
|
+
}
|
|
12
|
+
function safeStringify(value) {
|
|
13
|
+
if (typeof value === "string") {
|
|
14
|
+
return value;
|
|
15
|
+
}
|
|
16
|
+
try {
|
|
17
|
+
return JSON.stringify(value);
|
|
18
|
+
} catch {
|
|
19
|
+
return "[unserializable]";
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function isReadableStream(value) {
|
|
23
|
+
return isObjectLike(value) && typeof value.pipeThrough === "function" && typeof value.getReader === "function";
|
|
24
|
+
}
|
|
25
|
+
function tapModelCallStream(stream, onFinal, onError) {
|
|
26
|
+
const reader = stream.getReader();
|
|
27
|
+
const state = { toolCalls: [] };
|
|
28
|
+
let text = "";
|
|
29
|
+
let settled = false;
|
|
30
|
+
const finalize = () => {
|
|
31
|
+
if (settled) {
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
settled = true;
|
|
35
|
+
if (text) {
|
|
36
|
+
state.text = text;
|
|
37
|
+
}
|
|
38
|
+
onFinal(state);
|
|
39
|
+
};
|
|
40
|
+
const fail = (error) => {
|
|
41
|
+
if (settled) {
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
settled = true;
|
|
45
|
+
onError(error);
|
|
46
|
+
};
|
|
47
|
+
return new ReadableStream({
|
|
48
|
+
async pull(controller) {
|
|
49
|
+
try {
|
|
50
|
+
const { done, value } = await reader.read();
|
|
51
|
+
if (done) {
|
|
52
|
+
finalize();
|
|
53
|
+
controller.close();
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
text += accumulateChunk(state, value) ?? "";
|
|
57
|
+
controller.enqueue(value);
|
|
58
|
+
} catch (error) {
|
|
59
|
+
fail(error);
|
|
60
|
+
controller.error(error);
|
|
61
|
+
}
|
|
62
|
+
},
|
|
63
|
+
cancel(reason) {
|
|
64
|
+
finalize();
|
|
65
|
+
return reader.cancel(reason);
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
function accumulateChunk(state, chunk) {
|
|
70
|
+
if (!isObjectLike(chunk)) {
|
|
71
|
+
return void 0;
|
|
72
|
+
}
|
|
73
|
+
const {
|
|
74
|
+
type,
|
|
75
|
+
delta,
|
|
76
|
+
textDelta,
|
|
77
|
+
id,
|
|
78
|
+
modelId,
|
|
79
|
+
toolCallId,
|
|
80
|
+
toolName,
|
|
81
|
+
input,
|
|
82
|
+
args,
|
|
83
|
+
finishReason,
|
|
84
|
+
usage,
|
|
85
|
+
providerMetadata
|
|
86
|
+
} = chunk;
|
|
87
|
+
switch (type) {
|
|
88
|
+
case "text-delta": {
|
|
89
|
+
const textChunk = delta ?? textDelta;
|
|
90
|
+
return typeof textChunk === "string" ? textChunk : void 0;
|
|
91
|
+
}
|
|
92
|
+
case "tool-call":
|
|
93
|
+
state.toolCalls.push({ toolCallId, toolName, input: input ?? args });
|
|
94
|
+
return void 0;
|
|
95
|
+
case "response-metadata":
|
|
96
|
+
if (typeof id === "string") {
|
|
97
|
+
state.responseId = id;
|
|
98
|
+
}
|
|
99
|
+
if (typeof modelId === "string") {
|
|
100
|
+
state.responseModel = modelId;
|
|
101
|
+
}
|
|
102
|
+
return void 0;
|
|
103
|
+
case "finish":
|
|
104
|
+
state.finishReason = finishReason;
|
|
105
|
+
state.usage = usage;
|
|
106
|
+
if (providerMetadata !== void 0) {
|
|
107
|
+
state.providerMetadata = providerMetadata;
|
|
108
|
+
}
|
|
109
|
+
return void 0;
|
|
110
|
+
default:
|
|
111
|
+
return void 0;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export { asNumber, asString, isReadableStream, safeStringify, sum, tapModelCallStream };
|
|
116
|
+
//# sourceMappingURL=util.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"util.js","sources":["../../../src/vercel-ai/util.ts"],"sourcesContent":["/** Shared, state-free helpers for the Vercel AI (`ai`) channel subscribers, plus the streamed model-call tap. */\n\nimport { isObjectLike } from '@sentry/core';\n\n/** Narrow to a string, or `undefined` for anything else. */\nexport function asString(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\n/** Narrow to a finite number, or `undefined` for anything else (including `NaN`). */\nexport function asNumber(value: unknown): number | undefined {\n return typeof value === 'number' && !isNaN(value) ? value : undefined;\n}\n\n/** Add two optional numbers, treating a missing operand as `0` but returning `undefined` when both are absent. */\nexport function sum(a: number | undefined, b: number | undefined): number | undefined {\n return a === undefined && b === undefined ? undefined : (a ?? 0) + (b ?? 0);\n}\n\n/** Stringify a value, passing strings through and falling back to a placeholder on circular/unserializable input. */\nexport function safeStringify(value: unknown): string {\n if (typeof value === 'string') {\n return value;\n }\n try {\n return JSON.stringify(value);\n } catch {\n return '[unserializable]';\n }\n}\n\n/*\n * Streaming support for the `ai:telemetry` tracing channel.\n *\n * For a streamed model call (`doStream`) the SDK resolves the `languageModelCall` channel promise as\n * soon as it hands back the *unconsumed* stream — so `result.stream` is a `ReadableStream` and the\n * final usage / finish reason / output only arrive later, as the stream is drained (they ride the\n * stream's own `finish`/`text-delta`/`tool-call` chunks, never the channel context). The SDK\n * deliberately leaves `result` undefined on the `streamText`/`step` contexts and exposes the stream\n * only on the model call, expecting consumers to tap it themselves.\n * @see https://github.com/vercel/ai/pull/15660 (discussion: \"tee off and aggregate ourselves\")\n *\n * We replace `result.stream` with a passthrough that forwards every chunk untouched (so the SDK's own\n * consumption is unaffected) while accumulating the data we need, then hand the aggregate back once the\n * stream settles so the model-call span can be enriched and ended out-of-band.\n */\n\n/** The subset of a streamed provider chunk we read. Unknown chunk types are forwarded and ignored. */\ninterface StreamChunk {\n type?: unknown;\n delta?: unknown;\n // v4 text-delta chunks carry the text on `textDelta`; v5+ uses `delta`.\n textDelta?: unknown;\n id?: unknown;\n modelId?: unknown;\n toolCallId?: unknown;\n toolName?: unknown;\n input?: unknown;\n args?: unknown;\n finishReason?: unknown;\n usage?: unknown;\n providerMetadata?: unknown;\n error?: unknown;\n}\n\n/** The aggregate handed back once a streamed model call finishes, in the shape `enrichSpanOnEnd` expects. */\nexport interface StreamedModelCallResult {\n text?: string;\n toolCalls: Array<Record<string, unknown>>;\n usage?: unknown;\n finishReason?: unknown;\n responseId?: string;\n responseModel?: string;\n providerMetadata?: unknown;\n}\n\n/** A minimal structural check — the streamed model call exposes a web `ReadableStream` on `result.stream`. */\nexport function isReadableStream(value: unknown): value is ReadableStream<unknown> {\n return (\n isObjectLike(value) &&\n typeof (value as { pipeThrough?: unknown }).pipeThrough === 'function' &&\n typeof (value as { getReader?: unknown }).getReader === 'function'\n );\n}\n\n/**\n * Wrap a streamed model call's `ReadableStream` so its chunks are observed as the SDK consumes them,\n * without altering what the SDK sees. Returns a replacement stream to swap onto `result.stream`.\n *\n * `onFinal` runs exactly once when the stream drains cleanly; `onError` runs exactly once if it errors\n * or is cancelled. Reading one source chunk per `pull` preserves the SDK's backpressure. The\n * `try/catch` around every read guarantees the owning span is always ended — a leaked open span on a\n * mid-stream failure would be worse than a slightly-less-enriched one.\n */\nexport function tapModelCallStream(\n stream: ReadableStream<unknown>,\n onFinal: (result: StreamedModelCallResult) => void,\n onError: (error: unknown) => void,\n): ReadableStream<unknown> {\n const reader = stream.getReader();\n const state: StreamedModelCallResult = { toolCalls: [] };\n let text = '';\n let settled = false;\n\n const finalize = (): void => {\n if (settled) {\n return;\n }\n settled = true;\n if (text) {\n state.text = text;\n }\n onFinal(state);\n };\n\n const fail = (error: unknown): void => {\n if (settled) {\n return;\n }\n settled = true;\n onError(error);\n };\n\n return new ReadableStream<unknown>({\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n finalize();\n controller.close();\n\n return;\n }\n text += accumulateChunk(state, value) ?? '';\n controller.enqueue(value);\n } catch (error) {\n fail(error);\n controller.error(error);\n }\n },\n cancel(reason) {\n // Consumer stopped reading early (e.g. a `break` out of `for await`); close out the span with\n // whatever we have rather than leave it open. A non-error reason is a deliberate stop, not a failure.\n finalize();\n\n return reader.cancel(reason);\n },\n });\n}\n\n/**\n * Fold a single streamed chunk into the running aggregate. Returns any text delta so the caller can\n * accumulate it (kept out of `state` until the end to avoid re-joining on every chunk).\n */\nfunction accumulateChunk(state: StreamedModelCallResult, chunk: unknown): string | undefined {\n if (!isObjectLike(chunk)) {\n return undefined;\n }\n const {\n type,\n delta,\n textDelta,\n id,\n modelId,\n toolCallId,\n toolName,\n input,\n args,\n finishReason,\n usage,\n providerMetadata,\n } = chunk as StreamChunk;\n\n switch (type) {\n case 'text-delta': {\n const textChunk = delta ?? textDelta;\n return typeof textChunk === 'string' ? textChunk : undefined;\n }\n case 'tool-call':\n state.toolCalls.push({ toolCallId, toolName, input: input ?? args });\n\n return undefined;\n case 'response-metadata':\n if (typeof id === 'string') {\n state.responseId = id;\n }\n if (typeof modelId === 'string') {\n state.responseModel = modelId;\n }\n\n return undefined;\n case 'finish':\n state.finishReason = finishReason;\n state.usage = usage;\n if (providerMetadata !== undefined) {\n state.providerMetadata = providerMetadata;\n }\n\n return undefined;\n default:\n return undefined;\n }\n}\n"],"names":[],"mappings":";;AAKO,SAAS,SAAS,KAAA,EAAoC;AAC3D,EAAA,OAAO,OAAO,KAAA,KAAU,QAAA,GAAW,KAAA,GAAQ,MAAA;AAC7C;AAGO,SAAS,SAAS,KAAA,EAAoC;AAC3D,EAAA,OAAO,OAAO,KAAA,KAAU,QAAA,IAAY,CAAC,KAAA,CAAM,KAAK,IAAI,KAAA,GAAQ,MAAA;AAC9D;AAGO,SAAS,GAAA,CAAI,GAAuB,CAAA,EAA2C;AACpF,EAAA,OAAO,MAAM,MAAA,IAAa,CAAA,KAAM,SAAY,MAAA,GAAA,CAAa,CAAA,IAAK,MAAM,CAAA,IAAK,CAAA,CAAA;AAC3E;AAGO,SAAS,cAAc,KAAA,EAAwB;AACpD,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,IAAI;AACF,IAAA,OAAO,IAAA,CAAK,UAAU,KAAK,CAAA;AAAA,EAC7B,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,kBAAA;AAAA,EACT;AACF;AAgDO,SAAS,iBAAiB,KAAA,EAAkD;AACjF,EAAA,OACE,YAAA,CAAa,KAAK,CAAA,IAClB,OAAQ,MAAoC,WAAA,KAAgB,UAAA,IAC5D,OAAQ,KAAA,CAAkC,SAAA,KAAc,UAAA;AAE5D;AAWO,SAAS,kBAAA,CACd,MAAA,EACA,OAAA,EACA,OAAA,EACyB;AACzB,EAAA,MAAM,MAA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A;AAEb;;;;"}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { GEN_AI_TOOL_OUTPUT, GEN_AI_USAGE_INPUT_TOKENS, GEN_AI_USAGE_OUTPUT_TOKENS, GEN_AI_USAGE_TOTAL_TOKENS, GEN_AI_RESPONSE_FINISH_REASONS, GEN_AI_RESPONSE_ID, GEN_AI_RESPONSE_MODEL, GEN_AI_OUTPUT_MESSAGES, GEN_AI_EMBEDDINGS_INPUT, GEN_AI_OPERATION_NAME, GEN_AI_TOOL_INPUT, GEN_AI_TOOL_NAME, GEN_AI_TOOL_TYPE, GEN_AI_REQUEST_AVAILABLE_TOOLS, GEN_AI_FUNCTION_ID, GEN_AI_RESPONSE_STREAMING, GEN_AI_INPUT_MESSAGES, GEN_AI_REQUEST_MODEL, GEN_AI_SYSTEM } from '@sentry/conventions/attributes';
|
|
2
2
|
import { GEN_AI_EXECUTE_TOOL_SPAN_OP, GEN_AI_INVOKE_AGENT_SPAN_OP } from '@sentry/conventions/op';
|
|
3
|
-
import {
|
|
3
|
+
import { isObjectLike, getProviderMetadataAttributes, GEN_AI_CONVERSATION_ID_ATTRIBUTE, spanToJSON, getClient, shouldEnableTruncation, SPAN_STATUS_ERROR, withScope, spanToTraceContext, captureException, startInactiveSpan, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, getTruncatedJsonString, GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE, GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE } from '@sentry/core';
|
|
4
4
|
import { bindTracingChannelToSpan } from '../tracing-channel.js';
|
|
5
|
+
import { isReadableStream, asString, tapModelCallStream, safeStringify, sum, asNumber } from './util.js';
|
|
5
6
|
|
|
6
7
|
const AI_SDK_TELEMETRY_TRACING_CHANNEL = "ai:telemetry";
|
|
7
8
|
const ORIGIN = "auto.vercelai.channel";
|
|
@@ -15,7 +16,15 @@ const VERCEL_AI_MODEL_PROVIDER_ATTRIBUTE = "vercel.ai.model.provider";
|
|
|
15
16
|
const VERCEL_AI_SETTINGS_MAX_RETRIES_ATTRIBUTE = "vercel.ai.settings.maxRetries";
|
|
16
17
|
const operationIdByCallId = /* @__PURE__ */ new Map();
|
|
17
18
|
const toolDescriptionsByCallId = /* @__PURE__ */ new Map();
|
|
18
|
-
const
|
|
19
|
+
const invokeAgentSpanByCallId = /* @__PURE__ */ new Map();
|
|
20
|
+
const ROOT_OPERATION_TYPES = /* @__PURE__ */ new Set([
|
|
21
|
+
"generateText",
|
|
22
|
+
"streamText",
|
|
23
|
+
"generateObject",
|
|
24
|
+
"embed",
|
|
25
|
+
"embedMany",
|
|
26
|
+
"rerank"
|
|
27
|
+
]);
|
|
19
28
|
function clearOperationId(data) {
|
|
20
29
|
if (!ROOT_OPERATION_TYPES.has(data.type)) {
|
|
21
30
|
return;
|
|
@@ -28,6 +37,7 @@ function clearOperationId(data) {
|
|
|
28
37
|
function clearOperationCallId(callId) {
|
|
29
38
|
operationIdByCallId.delete(callId);
|
|
30
39
|
toolDescriptionsByCallId.delete(callId);
|
|
40
|
+
invokeAgentSpanByCallId.delete(callId);
|
|
31
41
|
}
|
|
32
42
|
function recordToolDescriptions(callId, tools) {
|
|
33
43
|
if (!callId || !Array.isArray(tools)) {
|
|
@@ -35,7 +45,7 @@ function recordToolDescriptions(callId, tools) {
|
|
|
35
45
|
}
|
|
36
46
|
let descriptions = toolDescriptionsByCallId.get(callId);
|
|
37
47
|
for (const tool of tools) {
|
|
38
|
-
if (
|
|
48
|
+
if (isObjectLike(tool) && typeof tool.name === "string" && typeof tool.description === "string") {
|
|
39
49
|
descriptions = descriptions ?? /* @__PURE__ */ new Map();
|
|
40
50
|
if (!descriptions.has(tool.name)) {
|
|
41
51
|
descriptions.set(tool.name, tool.description);
|
|
@@ -52,21 +62,16 @@ function resolveToolDescription(callId, toolName, tools) {
|
|
|
52
62
|
return fromMap;
|
|
53
63
|
}
|
|
54
64
|
if (Array.isArray(tools)) {
|
|
55
|
-
const match = tools.find((tool) =>
|
|
56
|
-
return
|
|
65
|
+
const match = tools.find((tool) => isObjectLike(tool) && tool.name === toolName);
|
|
66
|
+
return isObjectLike(match) ? asString(match.description) : void 0;
|
|
57
67
|
}
|
|
58
|
-
if (
|
|
68
|
+
if (isObjectLike(tools)) {
|
|
59
69
|
const tool = tools[toolName];
|
|
60
|
-
return
|
|
70
|
+
return isObjectLike(tool) ? asString(tool.description) : void 0;
|
|
61
71
|
}
|
|
62
72
|
return void 0;
|
|
63
73
|
}
|
|
64
|
-
let subscribed = false;
|
|
65
74
|
function subscribeVercelAiTracingChannel(tracingChannel, options = {}) {
|
|
66
|
-
if (subscribed) {
|
|
67
|
-
return;
|
|
68
|
-
}
|
|
69
|
-
subscribed = true;
|
|
70
75
|
bindTracingChannelToSpan(
|
|
71
76
|
tracingChannel(AI_SDK_TELEMETRY_TRACING_CHANNEL),
|
|
72
77
|
(data) => createSpanFromMessage(data, options),
|
|
@@ -76,10 +81,84 @@ function subscribeVercelAiTracingChannel(tracingChannel, options = {}) {
|
|
|
76
81
|
beforeSpanEnd: (span, data) => {
|
|
77
82
|
enrichSpanOnEnd(span, data, options);
|
|
78
83
|
clearOperationId(data);
|
|
79
|
-
}
|
|
84
|
+
},
|
|
85
|
+
// A streamed model call resolves before its stream is drained, so we tap the stream, keep the
|
|
86
|
+
// span open, and end it (via `end`) once the final usage/finish/output chunks arrive.
|
|
87
|
+
deferSpanEnd: ({ data, end }) => deferStreamedModelCallEnd(data, options, end)
|
|
80
88
|
}
|
|
81
89
|
);
|
|
82
90
|
}
|
|
91
|
+
function deferStreamedModelCallEnd(data, options, end) {
|
|
92
|
+
if (data.type !== "languageModelCall" || !isObjectLike(data.result)) {
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
const result = data.result;
|
|
96
|
+
const stream = result.stream;
|
|
97
|
+
if (!isReadableStream(stream)) {
|
|
98
|
+
return false;
|
|
99
|
+
}
|
|
100
|
+
const callId = asString(data.event.callId);
|
|
101
|
+
const { recordOutputs } = getRecordingOptions(data.event, options);
|
|
102
|
+
result.stream = tapModelCallStream(
|
|
103
|
+
stream,
|
|
104
|
+
(final) => {
|
|
105
|
+
data.result = { ...result, ...streamedResultToChannelResult(final) };
|
|
106
|
+
end();
|
|
107
|
+
enrichInvokeAgentFromStream(callId, final, recordOutputs);
|
|
108
|
+
},
|
|
109
|
+
(error) => end(error)
|
|
110
|
+
);
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
113
|
+
function streamedResultToChannelResult(final) {
|
|
114
|
+
const content = [];
|
|
115
|
+
if (final.text) {
|
|
116
|
+
content.push({ type: "text", text: final.text });
|
|
117
|
+
}
|
|
118
|
+
for (const toolCall of final.toolCalls) {
|
|
119
|
+
content.push({ type: "tool-call", ...toolCall });
|
|
120
|
+
}
|
|
121
|
+
return {
|
|
122
|
+
content,
|
|
123
|
+
...final.usage !== void 0 ? { usage: final.usage } : {},
|
|
124
|
+
...final.finishReason !== void 0 ? { finishReason: final.finishReason } : {},
|
|
125
|
+
...final.providerMetadata !== void 0 ? { providerMetadata: final.providerMetadata } : {},
|
|
126
|
+
...final.responseId || final.responseModel ? {
|
|
127
|
+
response: {
|
|
128
|
+
...final.responseId ? { id: final.responseId } : {},
|
|
129
|
+
...final.responseModel ? { modelId: final.responseModel } : {}
|
|
130
|
+
}
|
|
131
|
+
} : {}
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
function enrichInvokeAgentFromStream(callId, final, recordOutputs) {
|
|
135
|
+
const span = callId ? invokeAgentSpanByCallId.get(callId) : void 0;
|
|
136
|
+
if (!span) {
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
const usage = isObjectLike(final.usage) ? final.usage : void 0;
|
|
140
|
+
if (usage) {
|
|
141
|
+
const input = tokenCount(usage.inputTokens) ?? tokenCount(usage.promptTokens) ?? tokenCount(usage.tokens);
|
|
142
|
+
const output = tokenCount(usage.outputTokens) ?? tokenCount(usage.completionTokens);
|
|
143
|
+
addTokensToSpan(span, GEN_AI_USAGE_INPUT_TOKENS, input);
|
|
144
|
+
addTokensToSpan(span, GEN_AI_USAGE_OUTPUT_TOKENS, output);
|
|
145
|
+
addTokensToSpan(span, GEN_AI_USAGE_TOTAL_TOKENS, tokenCount(usage.totalTokens) ?? sum(input, output));
|
|
146
|
+
}
|
|
147
|
+
if (recordOutputs) {
|
|
148
|
+
const parts = partsFromTextAndToolCalls(final.text, final.toolCalls);
|
|
149
|
+
const outputMessages = buildOutputMessages(parts, getFinishReason({ finishReason: final.finishReason }));
|
|
150
|
+
if (outputMessages) {
|
|
151
|
+
span.setAttribute(GEN_AI_OUTPUT_MESSAGES, outputMessages);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
function addTokensToSpan(span, attribute, value) {
|
|
156
|
+
if (value === void 0) {
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
const current = spanToJSON(span).data[attribute];
|
|
160
|
+
span.setAttribute(attribute, (typeof current === "number" ? current : 0) + value);
|
|
161
|
+
}
|
|
83
162
|
function createSpanFromMessage(data, channelOptions) {
|
|
84
163
|
const { type, event } = data;
|
|
85
164
|
if (type === "step" || !event || typeof event !== "object") {
|
|
@@ -102,6 +181,7 @@ function createSpanFromMessage(data, channelOptions) {
|
|
|
102
181
|
switch (type) {
|
|
103
182
|
case "generateText":
|
|
104
183
|
case "streamText":
|
|
184
|
+
case "generateObject":
|
|
105
185
|
return buildInvokeAgentSpan(event, baseAttributes, recordInputs, enableTruncation, callId, type === "streamText");
|
|
106
186
|
case "languageModelCall":
|
|
107
187
|
return buildModelCallSpan(event, baseAttributes, recordInputs, enableTruncation, callId, modelId);
|
|
@@ -134,13 +214,17 @@ function buildInvokeAgentSpan(event, baseAttributes, recordInputs, enableTruncat
|
|
|
134
214
|
if (callId) {
|
|
135
215
|
operationIdByCallId.set(callId, { operationId, isStream });
|
|
136
216
|
}
|
|
137
|
-
|
|
217
|
+
const span = startGenAiSpan(GEN_AI_INVOKE_AGENT_SPAN_OP, functionId, {
|
|
138
218
|
...baseAttributes,
|
|
139
219
|
[VERCEL_AI_OPERATION_ID_ATTRIBUTE]: operationId,
|
|
140
220
|
[GEN_AI_RESPONSE_STREAMING]: isStream,
|
|
141
221
|
...functionId ? { [GEN_AI_FUNCTION_ID]: functionId } : {},
|
|
142
222
|
...recordInputs ? buildInputMessageAttributes(event, enableTruncation) : {}
|
|
143
223
|
});
|
|
224
|
+
if (isStream && callId) {
|
|
225
|
+
invokeAgentSpanByCallId.set(callId, span);
|
|
226
|
+
}
|
|
227
|
+
return span;
|
|
144
228
|
}
|
|
145
229
|
function buildModelCallSpan(event, baseAttributes, recordInputs, enableTruncation, callId, modelId) {
|
|
146
230
|
const parent = callId ? operationIdByCallId.get(callId) : void 0;
|
|
@@ -153,7 +237,7 @@ function buildModelCallSpan(event, baseAttributes, recordInputs, enableTruncatio
|
|
|
153
237
|
});
|
|
154
238
|
}
|
|
155
239
|
function buildToolSpan(event, recordInputs) {
|
|
156
|
-
const toolCall =
|
|
240
|
+
const toolCall = isObjectLike(event.toolCall) ? event.toolCall : {};
|
|
157
241
|
const toolName = asString(toolCall.toolName);
|
|
158
242
|
const toolCallId = asString(event.toolCallId) ?? asString(toolCall.toolCallId);
|
|
159
243
|
const toolInput = toolCall.input ?? toolCall.args;
|
|
@@ -169,7 +253,7 @@ function buildToolSpan(event, recordInputs) {
|
|
|
169
253
|
}
|
|
170
254
|
function enrichSpanOnEnd(span, data, channelOptions) {
|
|
171
255
|
const { type, result } = data;
|
|
172
|
-
if (!
|
|
256
|
+
if (!isObjectLike(result)) {
|
|
173
257
|
return;
|
|
174
258
|
}
|
|
175
259
|
const { recordOutputs } = getRecordingOptions(data.event, channelOptions);
|
|
@@ -177,16 +261,16 @@ function enrichSpanOnEnd(span, data, channelOptions) {
|
|
|
177
261
|
if (recordOutputs) {
|
|
178
262
|
span.setAttribute(GEN_AI_TOOL_OUTPUT, safeStringify(result.output ?? result));
|
|
179
263
|
}
|
|
180
|
-
const output =
|
|
264
|
+
const output = isObjectLike(result.output) ? result.output : void 0;
|
|
181
265
|
if (output?.type === "tool-error") {
|
|
182
266
|
captureToolError(span, data, output.error);
|
|
183
267
|
}
|
|
184
268
|
return;
|
|
185
269
|
}
|
|
186
|
-
const usage =
|
|
270
|
+
const usage = isObjectLike(result.usage) ? result.usage : void 0;
|
|
187
271
|
if (usage) {
|
|
188
|
-
const inputTokens = tokenCount(usage.inputTokens) ?? tokenCount(usage.tokens);
|
|
189
|
-
const outputTokens = tokenCount(usage.outputTokens);
|
|
272
|
+
const inputTokens = tokenCount(usage.inputTokens) ?? tokenCount(usage.promptTokens) ?? tokenCount(usage.tokens);
|
|
273
|
+
const outputTokens = tokenCount(usage.outputTokens) ?? tokenCount(usage.completionTokens);
|
|
190
274
|
const totalTokens = tokenCount(usage.totalTokens) ?? sum(inputTokens, outputTokens);
|
|
191
275
|
if (inputTokens !== void 0) {
|
|
192
276
|
span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, inputTokens);
|
|
@@ -202,7 +286,7 @@ function enrichSpanOnEnd(span, data, channelOptions) {
|
|
|
202
286
|
if (finishReason && type === "languageModelCall") {
|
|
203
287
|
span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, safeStringify([finishReason]));
|
|
204
288
|
}
|
|
205
|
-
const response =
|
|
289
|
+
const response = isObjectLike(result.response) ? result.response : void 0;
|
|
206
290
|
const responseId = asString(response?.id) ?? asString(result.responseId);
|
|
207
291
|
if (responseId) {
|
|
208
292
|
span.setAttribute(GEN_AI_RESPONSE_ID, responseId);
|
|
@@ -233,10 +317,10 @@ function getFinishReason(result) {
|
|
|
233
317
|
if (typeof finishReason === "string") {
|
|
234
318
|
return finishReason;
|
|
235
319
|
}
|
|
236
|
-
return
|
|
320
|
+
return isObjectLike(finishReason) ? asString(finishReason.unified) : void 0;
|
|
237
321
|
}
|
|
238
322
|
function tokenCount(value) {
|
|
239
|
-
return asNumber(value) ?? (
|
|
323
|
+
return asNumber(value) ?? (isObjectLike(value) ? asNumber(value.total) : void 0);
|
|
240
324
|
}
|
|
241
325
|
function buildOutputMessages(parts, finishReason) {
|
|
242
326
|
if (!parts.length) {
|
|
@@ -256,7 +340,7 @@ function toolCallPart(toolCall) {
|
|
|
256
340
|
function partsFromContent(content) {
|
|
257
341
|
const parts = [];
|
|
258
342
|
for (const item of content) {
|
|
259
|
-
if (!
|
|
343
|
+
if (!isObjectLike(item)) {
|
|
260
344
|
continue;
|
|
261
345
|
}
|
|
262
346
|
if (item.type === "text" && typeof item.text === "string") {
|
|
@@ -274,7 +358,7 @@ function partsFromTextAndToolCalls(text, toolCalls) {
|
|
|
274
358
|
}
|
|
275
359
|
if (Array.isArray(toolCalls)) {
|
|
276
360
|
for (const toolCall of toolCalls) {
|
|
277
|
-
if (
|
|
361
|
+
if (isObjectLike(toolCall)) {
|
|
278
362
|
parts.push(toolCallPart(toolCall));
|
|
279
363
|
}
|
|
280
364
|
}
|
|
@@ -286,7 +370,7 @@ function captureToolError(span, data, error) {
|
|
|
286
370
|
code: SPAN_STATUS_ERROR,
|
|
287
371
|
message: error instanceof Error ? error.message : "tool_error"
|
|
288
372
|
});
|
|
289
|
-
const toolCall =
|
|
373
|
+
const toolCall = isObjectLike(data.event.toolCall) ? data.event.toolCall : {};
|
|
290
374
|
const toolName = asString(toolCall.toolName);
|
|
291
375
|
const toolCallId = asString(data.event.toolCallId) ?? asString(toolCall.toolCallId);
|
|
292
376
|
withScope((scope) => {
|
|
@@ -336,28 +420,6 @@ function buildInputMessageAttributes(event, enableTruncation) {
|
|
|
336
420
|
}
|
|
337
421
|
return attributes;
|
|
338
422
|
}
|
|
339
|
-
function asString(value) {
|
|
340
|
-
return typeof value === "string" ? value : void 0;
|
|
341
|
-
}
|
|
342
|
-
function asNumber(value) {
|
|
343
|
-
return typeof value === "number" && !isNaN(value) ? value : void 0;
|
|
344
|
-
}
|
|
345
|
-
function sum(a, b) {
|
|
346
|
-
return a === void 0 && b === void 0 ? void 0 : (a ?? 0) + (b ?? 0);
|
|
347
|
-
}
|
|
348
|
-
function isRecord(value) {
|
|
349
|
-
return typeof value === "object" && value !== null;
|
|
350
|
-
}
|
|
351
|
-
function safeStringify(value) {
|
|
352
|
-
if (typeof value === "string") {
|
|
353
|
-
return value;
|
|
354
|
-
}
|
|
355
|
-
try {
|
|
356
|
-
return JSON.stringify(value);
|
|
357
|
-
} catch {
|
|
358
|
-
return "[unserializable]";
|
|
359
|
-
}
|
|
360
|
-
}
|
|
361
423
|
|
|
362
|
-
export { clearOperationCallId, clearOperationId, createSpanFromMessage, enrichSpanOnEnd, subscribeVercelAiTracingChannel };
|
|
424
|
+
export { captureToolError, clearOperationCallId, clearOperationId, createSpanFromMessage, enrichSpanOnEnd, streamedResultToChannelResult, subscribeVercelAiTracingChannel };
|
|
363
425
|
//# sourceMappingURL=vercel-ai-dc-subscriber.js.map
|