@sentry/server-utils 11.22.0 → 11.23.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/THIRD-PARTY-LICENSES.txt +10 -10
- package/build/cjs/chunks/config.js +2 -2
- package/build/cjs/chunks/config.js.map +1 -1
- package/build/cjs/chunks/core.js +0 -1
- package/build/cjs/chunks/exports.js +72 -27
- package/build/cjs/chunks/exports.js.map +1 -1
- package/build/cjs/chunks/module-details-from-path.js +427 -428
- package/build/cjs/chunks/module-details-from-path.js.map +1 -1
- package/build/cjs/chunks/moduleInjectedTransform.js +419 -421
- package/build/cjs/chunks/moduleInjectedTransform.js.map +1 -1
- package/build/cjs/chunks/rolldown-runtime.js +8 -6
- package/build/cjs/index.js +42 -25
- package/build/cjs/index.js.map +1 -1
- package/build/cjs/index.request-handler.js +2 -2
- package/build/cjs/orchestrion/bundler/bun.js +1 -1
- package/build/cjs/orchestrion/bundler/esbuild.js +1 -1
- package/build/cjs/orchestrion/bundler/rollup.js +1 -1
- package/build/cjs/orchestrion/bundler/vite.js +2 -2
- package/build/cjs/orchestrion/bundler/webpack-loader.js +2 -2
- package/build/cjs/orchestrion/bundler/webpack.js +4 -4
- package/build/esm/_virtual/{_@oxc-project_runtime@0.158.0 → _@oxc-project_runtime@0.160.0}/helpers/defineProperty.js +1 -1
- package/build/esm/_virtual/{_@oxc-project_runtime@0.158.0 → _@oxc-project_runtime@0.160.0}/helpers/esm/assertClassBrand.js +1 -1
- package/build/esm/_virtual/{_@oxc-project_runtime@0.158.0 → _@oxc-project_runtime@0.160.0}/helpers/esm/checkPrivateRedeclaration.js +1 -1
- package/build/esm/_virtual/{_@oxc-project_runtime@0.158.0 → _@oxc-project_runtime@0.160.0}/helpers/esm/classPrivateFieldGet2.js +1 -1
- package/build/esm/_virtual/{_@oxc-project_runtime@0.158.0 → _@oxc-project_runtime@0.160.0}/helpers/esm/classPrivateFieldInitSpec.js +1 -1
- package/build/esm/_virtual/{_@oxc-project_runtime@0.158.0 → _@oxc-project_runtime@0.160.0}/helpers/esm/classPrivateFieldSet2.js +1 -1
- package/build/esm/_virtual/{_@oxc-project_runtime@0.158.0 → _@oxc-project_runtime@0.160.0}/helpers/esm/classPrivateMethodInitSpec.js +1 -1
- package/build/esm/_virtual/{_@oxc-project_runtime@0.158.0 → _@oxc-project_runtime@0.160.0}/helpers/esm/defineProperty.js +1 -1
- package/build/esm/_virtual/{_@oxc-project_runtime@0.158.0 → _@oxc-project_runtime@0.160.0}/helpers/esm/toPrimitive.js +1 -1
- package/build/esm/_virtual/{_@oxc-project_runtime@0.158.0 → _@oxc-project_runtime@0.160.0}/helpers/esm/toPropertyKey.js +1 -1
- package/build/esm/_virtual/{_@oxc-project_runtime@0.158.0 → _@oxc-project_runtime@0.160.0}/helpers/esm/typeof.js +1 -1
- package/build/esm/_virtual/{_@oxc-project_runtime@0.158.0 → _@oxc-project_runtime@0.160.0}/helpers/toPrimitive.js +1 -1
- package/build/esm/_virtual/{_@oxc-project_runtime@0.158.0 → _@oxc-project_runtime@0.160.0}/helpers/toPropertyKey.js +1 -1
- package/build/esm/_virtual/{_@oxc-project_runtime@0.158.0 → _@oxc-project_runtime@0.160.0}/helpers/typeof.js +1 -1
- package/build/esm/_virtual/_rolldown/runtime.js +8 -6
- package/build/esm/ai/anthropic-ai/index.js +2 -2
- package/build/esm/ai/anthropic-ai/streaming.js +11 -2
- package/build/esm/ai/anthropic-ai/streaming.js.map +1 -1
- package/build/esm/ai/anthropic-ai/tool-runner.js +3 -3
- package/build/esm/ai/anthropic-ai/utils.js +2 -2
- package/build/esm/ai/core/span-hooks.js +1 -1
- package/build/esm/ai/core/time-to-first-chunk.js +1 -1
- package/build/esm/ai/core/utils.js +2 -2
- package/build/esm/ai/flue/index.js +2 -2
- package/build/esm/ai/flue/utils.js +2 -2
- package/build/esm/ai/google-genai/decisions.js +1 -1
- package/build/esm/ai/google-genai/index.js +2 -2
- package/build/esm/ai/google-genai/streaming.js +9 -2
- package/build/esm/ai/google-genai/streaming.js.map +1 -1
- package/build/esm/ai/google-genai/utils.js +1 -1
- package/build/esm/ai/langchain/embeddings.js +3 -3
- package/build/esm/ai/langchain/index.js +15 -9
- package/build/esm/ai/langchain/index.js.map +1 -1
- package/build/esm/ai/langchain/typesafe-classifier.js +2 -2
- package/build/esm/ai/langchain/utils.js +3 -4
- package/build/esm/ai/langchain/utils.js.map +1 -1
- package/build/esm/ai/langgraph/agent-span.js +3 -3
- package/build/esm/ai/langgraph/index.js +1 -1
- package/build/esm/ai/langgraph/stream.js +2 -2
- package/build/esm/ai/langgraph/utils.js +3 -3
- package/build/esm/ai/mastra/index.js +2 -2
- package/build/esm/ai/mastra/span-registry.js +1 -1
- package/build/esm/ai/mastra/utils.js +2 -2
- package/build/esm/ai/mistral/index.js +2 -2
- package/build/esm/ai/mistral/streaming.js +18 -9
- package/build/esm/ai/mistral/streaming.js.map +1 -1
- package/build/esm/ai/openai/index.js +2 -2
- package/build/esm/ai/openai/mapping.js +1 -1
- package/build/esm/ai/openai/streaming.js +15 -2
- package/build/esm/ai/openai/streaming.js.map +1 -1
- package/build/esm/ai/openai/utils.js +2 -2
- package/build/esm/ai/pi-ai/chat.js +12 -4
- package/build/esm/ai/pi-ai/chat.js.map +1 -1
- package/build/esm/ai/pi-ai/providers.js +1 -1
- package/build/esm/ai/pi-ai/recording.js +1 -1
- package/build/esm/ai/pi-durable/index.js +2 -2
- package/build/esm/ai/pi-durable/runs.js +3 -3
- package/build/esm/ai/pi-durable/tools.js +3 -3
- package/build/esm/ai/tanstack-ai/index.js +2 -2
- package/build/esm/ai/tanstack-ai/utils.js +2 -2
- package/build/esm/ai/typesafe/index.js +3 -3
- package/build/esm/ai/workers-ai/index.js +2 -2
- package/build/esm/ai/workers-ai/streaming.js +7 -5
- package/build/esm/ai/workers-ai/streaming.js.map +1 -1
- package/build/esm/ai/workers-ai/utils.js +3 -3
- package/build/esm/async-context.js +1 -1
- package/build/esm/cron/common.js +1 -1
- package/build/esm/cron/cron.js +1 -1
- package/build/esm/cron/node-cron.js +1 -1
- package/build/esm/cron/node-schedule.js +1 -1
- package/build/esm/eve.js +1 -1
- package/build/esm/integrations/amqplib.js +3 -3
- package/build/esm/integrations/anthropic.js +3 -4
- package/build/esm/integrations/anthropic.js.map +1 -1
- package/build/esm/integrations/aws-sdk/index.js +3 -3
- package/build/esm/integrations/aws-sdk/services/MessageAttributes.js +1 -1
- package/build/esm/integrations/aws-sdk/services/bedrock-runtime-content.js +2 -2
- package/build/esm/integrations/aws-sdk/services/bedrock-runtime.js +3 -3
- package/build/esm/integrations/aws-sdk/services/dynamodb.js +1 -1
- package/build/esm/integrations/aws-sdk/services/lambda.js +2 -2
- package/build/esm/integrations/aws-sdk/services/sns.js +3 -3
- package/build/esm/integrations/aws-sdk/services/sqs.js +2 -2
- package/build/esm/integrations/bullmq/meter.js +2 -2
- package/build/esm/integrations/bullmq/tracer.js +2 -2
- package/build/esm/integrations/clickhouse.js +3 -3
- package/build/esm/integrations/cron.js +1 -1
- package/build/esm/integrations/dataloader.js +3 -3
- package/build/esm/integrations/express/error-handler.js +1 -1
- package/build/esm/integrations/express/index.js +1 -1
- package/build/esm/integrations/express/instrumentation.js +3 -3
- package/build/esm/integrations/fastify/errors.js +1 -1
- package/build/esm/integrations/fastify/index.js +1 -1
- package/build/esm/integrations/fastify/instrumentation.js +3 -3
- package/build/esm/integrations/firebase/firestore.js +2 -2
- package/build/esm/integrations/firebase/functions.js +1 -1
- package/build/esm/integrations/firebase/index.js +1 -1
- package/build/esm/integrations/flue.js +1 -1
- package/build/esm/integrations/generic-pool.js +3 -3
- package/build/esm/integrations/google-genai.js +2 -2
- package/build/esm/integrations/graphql/graphql-dc-subscriber.js +3 -3
- package/build/esm/integrations/graphql/index.js +1 -1
- package/build/esm/integrations/graphql/resolvers.js +2 -2
- package/build/esm/integrations/graphql/spans.js +3 -3
- package/build/esm/integrations/groq.js +1 -1
- package/build/esm/integrations/hapi/hapi-error-handler.js +1 -1
- package/build/esm/integrations/hapi/hapi-utils.js +4 -5
- package/build/esm/integrations/hapi/hapi-utils.js.map +1 -1
- package/build/esm/integrations/hapi/index.js +1 -1
- package/build/esm/integrations/hono/applyPatches.js +1 -1
- package/build/esm/integrations/hono/createHonoMiddleware.js +1 -1
- package/build/esm/integrations/hono/honoIntegration.js +3 -3
- package/build/esm/integrations/hono/matchResult.js +1 -1
- package/build/esm/integrations/hono/middlewareHandlers.js +2 -2
- package/build/esm/integrations/hono/patchAppRequest.js +3 -3
- package/build/esm/integrations/hono/patchAppUse.js +1 -1
- package/build/esm/integrations/hono/patchRoute.js +1 -1
- package/build/esm/integrations/hono/wrapMiddlewareSpan.js +3 -3
- package/build/esm/integrations/kafkajs/consumer.js +2 -2
- package/build/esm/integrations/kafkajs/index.js +1 -1
- package/build/esm/integrations/kafkajs/spans.js +2 -2
- package/build/esm/integrations/knex.js +3 -3
- package/build/esm/integrations/koa/index.js +3 -3
- package/build/esm/integrations/langchain.js +1 -1
- package/build/esm/integrations/langgraph.js +1 -1
- package/build/esm/integrations/lru-memoizer.js +1 -1
- package/build/esm/integrations/mastra-classifier.js +2 -2
- package/build/esm/integrations/mastra.js +4 -4
- package/build/esm/integrations/mcp-server.js +2 -2
- package/build/esm/integrations/mistral.js +2 -2
- package/build/esm/integrations/mongodb/index.js +1 -1
- package/build/esm/integrations/mongodb/mongodb-span.js +1 -1
- package/build/esm/integrations/mongoose/index.js +1 -1
- package/build/esm/integrations/mongoose/mongoose-dc-subscriber.js +3 -3
- package/build/esm/integrations/mongoose/mongoose-legacy-span.js +1 -1
- package/build/esm/integrations/mysql.js +3 -3
- package/build/esm/integrations/mysql2/index.js +1 -1
- package/build/esm/integrations/mysql2/mysql2-dc-subscriber.js +3 -3
- package/build/esm/integrations/neon.js +3 -3
- package/build/esm/integrations/nitro/captureStorageEvents.js +3 -3
- package/build/esm/integrations/nitro/captureTracingEvents.js +3 -3
- package/build/esm/integrations/nitro/index.js +1 -1
- package/build/esm/integrations/nitro/setServerTimingHeaders.js +1 -1
- package/build/esm/integrations/node-cron.js +1 -1
- package/build/esm/integrations/node-schedule.js +1 -1
- package/build/esm/integrations/openai-compatible.js +2 -2
- package/build/esm/integrations/openai.js +2 -2
- package/build/esm/integrations/pg.js +3 -3
- package/build/esm/integrations/pi-ai.js +1 -1
- package/build/esm/integrations/pi-durable.js +1 -1
- package/build/esm/integrations/pino.js +1 -1
- package/build/esm/integrations/postgresjs/index.js +3 -3
- package/build/esm/integrations/postgresjs/postgresjs-dc-subscriber.js +3 -3
- package/build/esm/integrations/postgresjs-wrapper.js +1 -1
- package/build/esm/integrations/prisma/index.js +1 -1
- package/build/esm/integrations/prisma/orchestrion.js +8 -12
- package/build/esm/integrations/prisma/orchestrion.js.map +1 -1
- package/build/esm/integrations/prisma/tracing-helper.js +2 -2
- package/build/esm/integrations/redis/index.js +3 -3
- package/build/esm/integrations/redis/ioredis-channel-subscriber.js +3 -3
- package/build/esm/integrations/redis/redis-cache.js +1 -1
- package/build/esm/integrations/redis/redis-dc-subscriber.js +3 -3
- package/build/esm/integrations/serveTunnel.js +2 -2
- package/build/esm/integrations/tanstack-ai.js +1 -1
- package/build/esm/integrations/tedious.js +4 -4
- package/build/esm/integrations/together-ai.js +1 -1
- package/build/esm/integrations/typesafe.js +1 -1
- package/build/esm/integrations/vercel-ai/extract.js +1 -1
- package/build/esm/integrations/vercel-ai/index.js +1 -1
- package/build/esm/integrations/vercel-ai/util.js +21 -2
- package/build/esm/integrations/vercel-ai/util.js.map +1 -1
- package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js +3 -3
- package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js +1 -1
- package/build/esm/integrations/vercel-ai/vercel-ai-tool-telemetry.js +3 -3
- package/build/esm/integrations/winston.js +1 -1
- package/build/esm/opentelemetry.js +1 -1
- package/build/esm/orchestrion/bundler/esbuild.js +1 -1
- package/build/esm/orchestrion/bundler/externalRequire.js +1 -1
- package/build/esm/orchestrion/bundler/rollup.js +1 -1
- package/build/esm/orchestrion/bundler/webpack-loader.js +1 -1
- package/build/esm/orchestrion/bundler/webpack.js +1 -1
- package/build/esm/orchestrion/config/index.js +1 -1
- package/build/esm/orchestrion/config/mistral.js +1 -1
- package/build/esm/orchestrion/config/mistral.js.map +1 -1
- package/build/esm/orchestrion/detect.js +1 -1
- package/build/esm/orchestrion/instrumentation.js +1 -1
- package/build/esm/package.json +1 -1
- package/build/esm/tracing-channel.js +1 -2
- package/build/esm/tracing-channel.js.map +1 -1
- package/build/esm/utils/cronMonitoring.js +1 -1
- package/build/esm/utils/diagnosticsChannel.js +1 -1
- package/build/esm/utils/module.js +2 -2
- package/build/esm/utils/module.js.map +1 -1
- package/build/esm/utils/monitorStream.js +1 -1
- package/build/esm/utils/serverTimingTraceHeader.js +1 -1
- package/build/esm/utils/tunnelServer.js +1 -1
- package/build/esm/utils/wrapServerRequestHandler.js +4 -4
- package/build/esm/vendored/@apm-js-collab/code-transformer/lib/matcher.js +3 -3
- package/build/esm/vendored/@apm-js-collab/code-transformer/lib/transformer.js +5 -5
- package/build/esm/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/core-BiWIBBjf.js +1 -1
- package/build/esm/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/webpack-loader-factory.js +1 -1
- package/build/esm/vendored/esquery/dist/esquery.min.js +1 -0
- package/build/esm/vendored/esquery/dist/esquery.min.js.map +1 -1
- package/build/esm/vendored/meriyah/dist/meriyah.js +416 -418
- package/build/esm/vendored/meriyah/dist/meriyah.js.map +1 -1
- package/build/esm/vendored/meriyah/dist/meriyah2.js +416 -418
- package/build/esm/vendored/meriyah/dist/meriyah2.js.map +1 -1
- package/build/esm/vendored/source-map/lib/base64-vlq.js +1 -1
- package/build/esm/vendored/source-map/lib/base64-vlq.js.map +1 -1
- package/build/types/ai/anthropic-ai/streaming.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/types.d.ts +1 -0
- package/build/types/ai/anthropic-ai/types.d.ts.map +1 -1
- package/build/types/ai/google-genai/streaming.d.ts.map +1 -1
- package/build/types/ai/langchain/index.d.ts.map +1 -1
- package/build/types/ai/mistral/streaming.d.ts.map +1 -1
- package/build/types/ai/openai/streaming.d.ts.map +1 -1
- package/build/types/ai/pi-ai/chat.d.ts.map +1 -1
- package/build/types/ai/workers-ai/streaming.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/util.d.ts.map +1 -1
- package/build/types/orchestrion/config/mistral.d.ts +3 -3
- package/build/types/tracing-channel.d.ts.map +1 -1
- package/package.json +3 -3
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_debug_build = require("./chunks/debug-build.js");
|
|
3
2
|
let _sentry_conventions_attributes = require("@sentry/conventions/attributes");
|
|
4
|
-
let _sentry_core = require("@sentry/core");
|
|
5
3
|
let _sentry_conventions_op = require("@sentry/conventions/op");
|
|
4
|
+
let _sentry_core = require("@sentry/core");
|
|
6
5
|
let _sentry_core_server = require("@sentry/core/server");
|
|
6
|
+
const require_debug_build = require("./chunks/debug-build.js");
|
|
7
7
|
// src/utils/monitorStream.ts
|
|
8
8
|
/**
|
|
9
9
|
* Monitor the source without reading ahead or treating cancellation as a source failure.
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_core_BiWIBBjf = require("../../chunks/core-BiWIBBjf.js");
|
|
3
|
+
let node_fs = require("node:fs");
|
|
3
4
|
const require_config = require("../../chunks/config.js");
|
|
4
5
|
const require_moduleInjectedTransform = require("../../chunks/moduleInjectedTransform.js");
|
|
5
6
|
const require_options = require("../../chunks/options.js");
|
|
6
|
-
let node_fs = require("node:fs");
|
|
7
7
|
// ../../node_modules/.pnpm/@apm-js-collab+code-transformer-bundler-plugins@0.7.6_esbuild@0.28.1_rollup@4.68.3_vite_ba2d60d9522bfc1375bd8d747d2e3205/node_modules/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/bun.mjs
|
|
8
8
|
function loaderForPath(path) {
|
|
9
9
|
if (path.endsWith(".tsx")) return "tsx";
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_esbuild = require("../../chunks/esbuild.js");
|
|
3
|
+
let _sentry_core = require("@sentry/core");
|
|
3
4
|
const require_config = require("../../chunks/config.js");
|
|
4
5
|
const require_options = require("../../chunks/options.js");
|
|
5
6
|
const require_resolve = require("../../chunks/resolve.js");
|
|
6
|
-
let _sentry_core = require("@sentry/core");
|
|
7
7
|
// src/orchestrion/bundler/esbuild.ts
|
|
8
8
|
function matchesEsbuildExternal(entry, moduleName) {
|
|
9
9
|
if (entry.includes("*")) return new RegExp(`^${entry.split("*").map(_sentry_core.escapeStringForRegex).join(".*")}$`).test(moduleName);
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let node_module = require("node:module");
|
|
2
3
|
const require_rollup_CzqrjlS4 = require("../../chunks/rollup-CzqrjlS4.js");
|
|
3
4
|
const require_config = require("../../chunks/config.js");
|
|
4
5
|
const require_options = require("../../chunks/options.js");
|
|
5
6
|
const require_resolve = require("../../chunks/resolve.js");
|
|
6
|
-
let node_module = require("node:module");
|
|
7
7
|
// src/orchestrion/bundler/rollup.ts
|
|
8
8
|
/**
|
|
9
9
|
* Whether a raw (un-normalized) `external` input option marks `name` as
|
|
@@ -3,11 +3,11 @@ const require_esbuild = require("../../chunks/esbuild.js");
|
|
|
3
3
|
const require_rollup_CzqrjlS4 = require("../../chunks/rollup-CzqrjlS4.js");
|
|
4
4
|
const require_config = require("../../chunks/config.js");
|
|
5
5
|
const require_options = require("../../chunks/options.js");
|
|
6
|
-
const require_resolve = require("../../chunks/resolve.js");
|
|
7
6
|
let _sentry_core = require("@sentry/core");
|
|
7
|
+
let node_fs = require("node:fs");
|
|
8
8
|
let node_module = require("node:module");
|
|
9
9
|
let node_path = require("node:path");
|
|
10
|
-
|
|
10
|
+
const require_resolve = require("../../chunks/resolve.js");
|
|
11
11
|
// ../../node_modules/.pnpm/@apm-js-collab+code-transformer-bundler-plugins@0.7.6_esbuild@0.28.1_rollup@4.68.3_vite_ba2d60d9522bfc1375bd8d747d2e3205/node_modules/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/vite.mjs
|
|
12
12
|
function codeTransformerVite(options) {
|
|
13
13
|
return {
|
|
@@ -5,10 +5,10 @@ Object.defineProperties(exports, {
|
|
|
5
5
|
const require_rolldown_runtime = require("../../chunks/rolldown-runtime.js");
|
|
6
6
|
const require_instrumentation_serde_C_Xxv_jj = require("../../chunks/instrumentation-serde-C-Xxv-jj.js");
|
|
7
7
|
const require_module_details_from_path$1 = require("../../chunks/module-details-from-path.js");
|
|
8
|
-
const require_moduleInjectedTransform = require("../../chunks/moduleInjectedTransform.js");
|
|
9
|
-
let node_path = require("node:path");
|
|
10
8
|
let path = require("node:path");
|
|
11
9
|
let fs = require("node:fs");
|
|
10
|
+
let node_path = require("node:path");
|
|
11
|
+
const require_moduleInjectedTransform = require("../../chunks/moduleInjectedTransform.js");
|
|
12
12
|
// ../../node_modules/.pnpm/@apm-js-collab+code-transformer-bundler-plugins@0.7.6_esbuild@0.28.1_rollup@4.68.3_vite_ba2d60d9522bfc1375bd8d747d2e3205/node_modules/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/webpack-loader-factory.mjs
|
|
13
13
|
var import_code_transformer = require_module_details_from_path$1.require_code_transformer();
|
|
14
14
|
var import_module_details_from_path = /* @__PURE__ */ require_rolldown_runtime.__toESM(require_module_details_from_path$1.require_module_details_from_path(), 1);
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let _sentry_core = require("@sentry/core");
|
|
2
3
|
const require_config = require("../../chunks/config.js");
|
|
3
4
|
const require_instrumentation_serde_C_Xxv_jj = require("../../chunks/instrumentation-serde-C-Xxv-jj.js");
|
|
4
|
-
const require_resolve = require("../../chunks/resolve.js");
|
|
5
|
-
require("../../chunks/core.js");
|
|
6
|
-
const require_options = require("../../chunks/options.js");
|
|
7
|
-
let _sentry_core = require("@sentry/core");
|
|
8
5
|
let path = require("node:path");
|
|
9
6
|
let url = require("node:url");
|
|
10
7
|
let crypto = require("node:crypto");
|
|
8
|
+
const require_resolve = require("../../chunks/resolve.js");
|
|
9
|
+
require("../../chunks/core.js");
|
|
10
|
+
const require_options = require("../../chunks/options.js");
|
|
11
11
|
// ../../node_modules/.pnpm/@apm-js-collab+code-transformer-bundler-plugins@0.7.6_esbuild@0.28.1_rollup@4.68.3_vite_ba2d60d9522bfc1375bd8d747d2e3205/node_modules/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/webpack.mjs
|
|
12
12
|
var LOADER_PATH = (0, path.resolve)((0, path.dirname)((0, url.fileURLToPath)(require("url").pathToFileURL(__filename).href)), "..", "cjs", "webpack-loader.cjs");
|
|
13
13
|
var DIAGNOSTICS_STATE_KEY = "__codeTransformerWebpackDiagnostics";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { __commonJSMin } from "../../_rolldown/runtime.js";
|
|
2
2
|
import { require_toPropertyKey } from "./toPropertyKey.js";
|
|
3
|
-
// \0@oxc-project+runtime@0.
|
|
3
|
+
// \0@oxc-project+runtime@0.160.0/helpers/defineProperty.js
|
|
4
4
|
var require_defineProperty = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
5
5
|
var toPropertyKey = require_toPropertyKey();
|
|
6
6
|
function _defineProperty(e, r, t) {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { __esmMin } from "../../../_rolldown/runtime.js";
|
|
2
|
-
// \0@oxc-project+runtime@0.
|
|
2
|
+
// \0@oxc-project+runtime@0.160.0/helpers/esm/assertClassBrand.js
|
|
3
3
|
function _assertClassBrand(e, t, n) {
|
|
4
4
|
if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n;
|
|
5
5
|
throw new TypeError("Private element is not present on this object");
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { __esmMin } from "../../../_rolldown/runtime.js";
|
|
2
|
-
// \0@oxc-project+runtime@0.
|
|
2
|
+
// \0@oxc-project+runtime@0.160.0/helpers/esm/checkPrivateRedeclaration.js
|
|
3
3
|
function _checkPrivateRedeclaration(e, t) {
|
|
4
4
|
if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object");
|
|
5
5
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { __esmMin } from "../../../_rolldown/runtime.js";
|
|
2
2
|
import _assertClassBrand from "./assertClassBrand.js";
|
|
3
|
-
// \0@oxc-project+runtime@0.
|
|
3
|
+
// \0@oxc-project+runtime@0.160.0/helpers/esm/classPrivateFieldGet2.js
|
|
4
4
|
function _classPrivateFieldGet2(s, a) {
|
|
5
5
|
return s.get(_assertClassBrand(s, a));
|
|
6
6
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { __esmMin } from "../../../_rolldown/runtime.js";
|
|
2
2
|
import _checkPrivateRedeclaration from "./checkPrivateRedeclaration.js";
|
|
3
|
-
// \0@oxc-project+runtime@0.
|
|
3
|
+
// \0@oxc-project+runtime@0.160.0/helpers/esm/classPrivateFieldInitSpec.js
|
|
4
4
|
function _classPrivateFieldInitSpec(e, t, a) {
|
|
5
5
|
_checkPrivateRedeclaration(e, t), t.set(e, a);
|
|
6
6
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { __esmMin } from "../../../_rolldown/runtime.js";
|
|
2
2
|
import _assertClassBrand from "./assertClassBrand.js";
|
|
3
|
-
// \0@oxc-project+runtime@0.
|
|
3
|
+
// \0@oxc-project+runtime@0.160.0/helpers/esm/classPrivateFieldSet2.js
|
|
4
4
|
function _classPrivateFieldSet2(s, a, r) {
|
|
5
5
|
return s.set(_assertClassBrand(s, a), r), r;
|
|
6
6
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { __esmMin } from "../../../_rolldown/runtime.js";
|
|
2
2
|
import _checkPrivateRedeclaration from "./checkPrivateRedeclaration.js";
|
|
3
|
-
// \0@oxc-project+runtime@0.
|
|
3
|
+
// \0@oxc-project+runtime@0.160.0/helpers/esm/classPrivateMethodInitSpec.js
|
|
4
4
|
function _classPrivateMethodInitSpec(e, a) {
|
|
5
5
|
_checkPrivateRedeclaration(e, a), a.add(e);
|
|
6
6
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import toPropertyKey from "./toPropertyKey.js";
|
|
2
|
-
// \0@oxc-project+runtime@0.
|
|
2
|
+
// \0@oxc-project+runtime@0.160.0/helpers/esm/defineProperty.js
|
|
3
3
|
function _defineProperty(e, r, t) {
|
|
4
4
|
return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
|
|
5
5
|
value: t,
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import _typeof from "./typeof.js";
|
|
2
2
|
import toPrimitive from "./toPrimitive.js";
|
|
3
|
-
// \0@oxc-project+runtime@0.
|
|
3
|
+
// \0@oxc-project+runtime@0.160.0/helpers/esm/toPropertyKey.js
|
|
4
4
|
function toPropertyKey(t) {
|
|
5
5
|
var i = toPrimitive(t, "string");
|
|
6
6
|
return "symbol" == _typeof(i) ? i : i + "";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { __commonJSMin } from "../../_rolldown/runtime.js";
|
|
2
2
|
import { require_typeof } from "./typeof.js";
|
|
3
|
-
// \0@oxc-project+runtime@0.
|
|
3
|
+
// \0@oxc-project+runtime@0.160.0/helpers/toPrimitive.js
|
|
4
4
|
var require_toPrimitive = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
5
5
|
var _typeof = require_typeof()["default"];
|
|
6
6
|
function toPrimitive(t, e) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { __commonJSMin } from "../../_rolldown/runtime.js";
|
|
2
2
|
import { require_typeof } from "./typeof.js";
|
|
3
3
|
import { require_toPrimitive } from "./toPrimitive.js";
|
|
4
|
-
// \0@oxc-project+runtime@0.
|
|
4
|
+
// \0@oxc-project+runtime@0.160.0/helpers/toPropertyKey.js
|
|
5
5
|
var require_toPropertyKey = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
6
6
|
var _typeof = require_typeof()["default"];
|
|
7
7
|
var toPrimitive = require_toPrimitive();
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { __commonJSMin } from "../../_rolldown/runtime.js";
|
|
2
|
-
// \0@oxc-project+runtime@0.
|
|
2
|
+
// \0@oxc-project+runtime@0.160.0/helpers/typeof.js
|
|
3
3
|
var require_typeof = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
4
4
|
function _typeof(o) {
|
|
5
5
|
"@babel/helpers - typeof";
|
|
@@ -15,12 +15,14 @@ var __esmMin = (fn, res, err) => () => {
|
|
|
15
15
|
};
|
|
16
16
|
var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod, mod.exports), cb = null), mod.exports);
|
|
17
17
|
var __copyProps = (to, from, except, desc) => {
|
|
18
|
-
if (from && typeof from === "object" || typeof from === "function")
|
|
19
|
-
key
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
18
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
19
|
+
for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) {
|
|
20
|
+
desc = __getOwnPropDesc(from, key);
|
|
21
|
+
__defProp(to, key, {
|
|
22
|
+
get: desc && desc.get && !desc.configurable ? desc.get : () => from[key],
|
|
23
|
+
enumerable: !desc || desc.enumerable
|
|
24
|
+
});
|
|
25
|
+
}
|
|
24
26
|
}
|
|
25
27
|
return to;
|
|
26
28
|
};
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { getClient, hasSpanStreamingEnabled, startSpan, startSpanManual } from "@sentry/core";
|
|
2
|
+
import { GEN_AI_OPERATION_NAME, GEN_AI_PROVIDER_NAME, GEN_AI_REQUEST_FREQUENCY_PENALTY, GEN_AI_REQUEST_MAX_TOKENS, GEN_AI_REQUEST_MODEL, GEN_AI_REQUEST_TEMPERATURE, GEN_AI_REQUEST_TOP_K, GEN_AI_REQUEST_TOP_P, GEN_AI_TOOL_DEFINITIONS, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
|
|
1
3
|
import { GEN_AI_REQUEST_STREAM_ATTRIBUTE } from "../core/gen-ai-attributes.js";
|
|
2
4
|
import { runGenAiSpanEnd, runGenAiSpanStart } from "../core/span-hooks.js";
|
|
3
5
|
import { getErrorStatus, getGenAiSpanOp, getRequestSignal, resolveGenAiCallRecording, wrapPromiseWithMethods } from "../core/utils.js";
|
|
@@ -5,8 +7,6 @@ import { ANTHROPIC_AI_ORIGIN, ANTHROPIC_METHOD_REGISTRY } from "./constants.js";
|
|
|
5
7
|
import { instrumentAsyncIterableStream, instrumentMessageStream } from "./streaming.js";
|
|
6
8
|
import { instrumentSessionToolRunner, instrumentToolRunner, instrumentToolRunnerFactory } from "./tool-runner.js";
|
|
7
9
|
import { addResponseAttributes, getMessagesAttributes, getProviderName, messagesFromParams } from "./utils.js";
|
|
8
|
-
import { GEN_AI_OPERATION_NAME, GEN_AI_PROVIDER_NAME, GEN_AI_REQUEST_FREQUENCY_PENALTY, GEN_AI_REQUEST_MAX_TOKENS, GEN_AI_REQUEST_MODEL, GEN_AI_REQUEST_TEMPERATURE, GEN_AI_REQUEST_TOP_K, GEN_AI_REQUEST_TOP_P, GEN_AI_TOOL_DEFINITIONS, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
|
|
9
|
-
import { getClient, hasSpanStreamingEnabled, startSpan, startSpanManual } from "@sentry/core";
|
|
10
10
|
// src/ai/anthropic-ai/index.ts
|
|
11
11
|
let suppressDelegatedCreate = false;
|
|
12
12
|
const INSTRUMENTED_METHODS = /* @__PURE__ */ new WeakSet();
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
+
import { SPAN_STATUS_ERROR, captureException } from "@sentry/core";
|
|
1
2
|
import { endStreamSpan, getErrorStatus } from "../core/utils.js";
|
|
2
3
|
import { recordTimeToFirstChunk } from "../core/time-to-first-chunk.js";
|
|
3
4
|
import { mapAnthropicErrorToStatusMessage } from "./utils.js";
|
|
4
|
-
import { SPAN_STATUS_ERROR, captureException } from "@sentry/core";
|
|
5
5
|
// src/ai/anthropic-ai/streaming.ts
|
|
6
6
|
/**
|
|
7
7
|
* Checks if an event is an error event
|
|
@@ -97,6 +97,15 @@ function handleContentBlockStop(event, state) {
|
|
|
97
97
|
delete state.activeToolBlocks[event.index];
|
|
98
98
|
}
|
|
99
99
|
/**
|
|
100
|
+
* Whether an event carries new model output, which is what `gen_ai.response.time_to_first_chunk` measures.
|
|
101
|
+
* `message_start`, `ping`, empty block starts, signatures and stop events do not.
|
|
102
|
+
*/
|
|
103
|
+
function hasOutput(event) {
|
|
104
|
+
if (event.type === "content_block_start") return !!(event.content_block?.name || event.content_block?.type === "redacted_thinking");
|
|
105
|
+
if (event.type === "content_block_delta") return !!(event.delta?.text || event.delta?.partial_json || event.delta?.thinking);
|
|
106
|
+
return false;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
100
109
|
* Processes an event
|
|
101
110
|
* @param event - The event to process
|
|
102
111
|
* @param state - The state of the streaming process
|
|
@@ -106,7 +115,7 @@ function handleContentBlockStop(event, state) {
|
|
|
106
115
|
function processEvent(event, state, recordOutputs, span) {
|
|
107
116
|
if (!(event && typeof event === "object")) return;
|
|
108
117
|
if (isErrorEvent(event, span)) return;
|
|
109
|
-
recordTimeToFirstChunk(span);
|
|
118
|
+
if (hasOutput(event)) recordTimeToFirstChunk(span);
|
|
110
119
|
handleMessageMetadata(event, state);
|
|
111
120
|
handleContentBlockStart(event, state);
|
|
112
121
|
handleContentBlockDelta(event, state, recordOutputs);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"streaming.js","names":[],"sources":["../../../../src/ai/anthropic-ai/streaming.ts"],"sourcesContent":["import { captureException, SPAN_STATUS_ERROR } from '@sentry/core';\nimport type { Span } from '@sentry/core';\nimport type { GenAiSpanResult } from '../core/span-hooks';\nimport { endStreamSpan, getErrorStatus } from '../core/utils';\nimport { recordTimeToFirstChunk } from '../core/time-to-first-chunk';\nimport type { AnthropicAiStreamingEvent } from './types';\nimport { mapAnthropicErrorToStatusMessage } from './utils';\n\n/**\n * State object used to accumulate information from a stream of Anthropic AI events.\n */\ninterface StreamingState {\n /** Collected response text fragments (for output recording). */\n responseTexts: string[];\n /** Reasons for finishing the response, as reported by the API. */\n finishReasons: string[];\n /** The response ID. */\n responseId: string;\n /** The model name. */\n responseModel: string;\n /** Number of input tokens, not counting cache reads and writes. */\n inputTokens: number | undefined;\n /** Number of prompt/input tokens used, including cache reads and writes. */\n promptTokens: number | undefined;\n /** Number of completion/output tokens used. */\n completionTokens: number | undefined;\n /** Number of cache creation input tokens used. */\n cacheCreationInputTokens: number | undefined;\n /** Number of cache read input tokens used. */\n cacheReadInputTokens: number | undefined;\n /** Accumulated tool calls (finalized) */\n toolCalls: Array<Record<string, unknown>>;\n /** In-progress tool call blocks keyed by index */\n activeToolBlocks: Record<\n number,\n {\n id?: string;\n name?: string;\n inputJsonParts: string[];\n }\n >;\n}\n\n/**\n * Checks if an event is an error event\n * @param event - The event to process\n * @param state - The state of the streaming process\n * @param recordOutputs - Whether to record outputs\n * @param span - The span to update\n * @returns Whether an error occurred\n */\n\nfunction isErrorEvent(event: AnthropicAiStreamingEvent, span: Span): boolean {\n if ('type' in event && typeof event.type === 'string') {\n if (event.type === 'error') {\n // The SDK surfaces this error to the caller (the async iterator rejects / their `error`\n // listener fires), so we only mark the span failed and do not record it.\n span.setStatus({ code: SPAN_STATUS_ERROR, message: mapAnthropicErrorToStatusMessage(event.error?.type) });\n return true;\n }\n }\n return false;\n}\n\n/**\n * Processes the message metadata of an event\n * @param event - The event to process\n * @param state - The state of the streaming process\n */\n\nfunction handleMessageMetadata(event: AnthropicAiStreamingEvent, state: StreamingState): void {\n // Cumulative token counts and the final stop reason both arrive on the message_delta event.\n // @see https://docs.anthropic.com/en/docs/build-with-claude/streaming#event-types\n if (event.type === 'message_delta') {\n if (event.usage) {\n // Input and cache counts can grow after message_start (e.g. with server tools), so the last value wins.\n applyInputUsage(event.usage, state);\n if (typeof event.usage.output_tokens === 'number') {\n state.completionTokens = event.usage.output_tokens;\n }\n }\n if (event.delta?.stop_reason) {\n state.finishReasons.push(event.delta.stop_reason);\n }\n }\n\n if (event.message) {\n const message = event.message;\n\n if (message.id) state.responseId = message.id;\n if (message.model) state.responseModel = message.model;\n\n if (message.usage) {\n applyInputUsage(message.usage, state);\n }\n }\n}\n\n/**\n * Records the input and cache token counts of a usage object that are numbers.\n */\nfunction applyInputUsage(\n usage: {\n input_tokens?: number | null;\n cache_creation_input_tokens?: number | null;\n cache_read_input_tokens?: number | null;\n },\n state: StreamingState,\n): void {\n if (typeof usage.input_tokens === 'number') state.inputTokens = usage.input_tokens;\n if (typeof usage.cache_creation_input_tokens === 'number')\n state.cacheCreationInputTokens = usage.cache_creation_input_tokens;\n if (typeof usage.cache_read_input_tokens === 'number') state.cacheReadInputTokens = usage.cache_read_input_tokens;\n\n if (typeof state.inputTokens === 'number') {\n state.promptTokens = state.inputTokens + (state.cacheCreationInputTokens ?? 0) + (state.cacheReadInputTokens ?? 0);\n }\n}\n\n/**\n * Handle start of a content block (e.g., tool_use)\n */\nfunction handleContentBlockStart(event: AnthropicAiStreamingEvent, state: StreamingState): void {\n if (event.type !== 'content_block_start' || typeof event.index !== 'number' || !event.content_block) return;\n if (event.content_block.type === 'tool_use' || event.content_block.type === 'server_tool_use') {\n state.activeToolBlocks[event.index] = {\n id: event.content_block.id,\n name: event.content_block.name,\n inputJsonParts: [],\n };\n }\n}\n\n/**\n * Handle deltas of a content block, including input_json_delta for tool_use\n */\nfunction handleContentBlockDelta(\n event: AnthropicAiStreamingEvent,\n state: StreamingState,\n recordOutputs: boolean,\n): void {\n if (event.type !== 'content_block_delta' || !event.delta) return;\n\n // Accumulate tool_use input JSON deltas only when we have an index and an active tool block\n if (\n typeof event.index === 'number' &&\n 'partial_json' in event.delta &&\n typeof event.delta.partial_json === 'string'\n ) {\n const active = state.activeToolBlocks[event.index];\n if (active) {\n active.inputJsonParts.push(event.delta.partial_json);\n }\n }\n\n // Accumulate streamed response text regardless of index\n if (recordOutputs && typeof event.delta.text === 'string') {\n state.responseTexts.push(event.delta.text);\n }\n}\n\n/**\n * Handle stop of a content block; finalize tool_use entries\n */\nfunction handleContentBlockStop(event: AnthropicAiStreamingEvent, state: StreamingState): void {\n if (event.type !== 'content_block_stop' || typeof event.index !== 'number') return;\n\n const active = state.activeToolBlocks[event.index];\n if (!active) return;\n\n const raw = active.inputJsonParts.join('');\n let parsedInput: unknown;\n\n try {\n parsedInput = raw ? JSON.parse(raw) : {};\n } catch {\n parsedInput = { __unparsed: raw };\n }\n\n state.toolCalls.push({\n type: 'tool_use',\n id: active.id,\n name: active.name,\n input: parsedInput,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete state.activeToolBlocks[event.index];\n}\n\n/**\n * Processes an event\n * @param event - The event to process\n * @param state - The state of the streaming process\n * @param recordOutputs - Whether to record outputs\n * @param span - The span to update\n */\nfunction processEvent(\n event: AnthropicAiStreamingEvent,\n state: StreamingState,\n recordOutputs: boolean,\n span: Span,\n): void {\n if (!(event && typeof event === 'object')) {\n return;\n }\n\n const isError = isErrorEvent(event, span);\n if (isError) return;\n\n recordTimeToFirstChunk(span);\n\n handleMessageMetadata(event, state);\n\n // Tool call events are sent via 3 separate events:\n // - content_block_start (start of the tool call)\n // - content_block_delta (delta aka input of the tool call)\n // - content_block_stop (end of the tool call)\n // We need to handle them all to capture the full tool call.\n handleContentBlockStart(event, state);\n handleContentBlockDelta(event, state, recordOutputs);\n handleContentBlockStop(event, state);\n}\n\n/**\n * Instruments an async iterable stream of Anthropic events, updates the span with\n * streaming attributes and (optionally) the aggregated output text, and yields\n * each event from the input stream unchanged.\n */\nexport async function* instrumentAsyncIterableStream(\n stream: AsyncIterable<AnthropicAiStreamingEvent>,\n span: Span,\n recordOutputs: boolean,\n beforeSpanEnd?: (result: GenAiSpanResult<never>) => void,\n): AsyncGenerator<AnthropicAiStreamingEvent, void, unknown> {\n const state: StreamingState = {\n responseTexts: [],\n finishReasons: [],\n responseId: '',\n responseModel: '',\n inputTokens: undefined,\n promptTokens: undefined,\n completionTokens: undefined,\n cacheCreationInputTokens: undefined,\n cacheReadInputTokens: undefined,\n toolCalls: [],\n activeToolBlocks: {},\n };\n const result: GenAiSpanResult<never> = {};\n\n try {\n for await (const event of stream) {\n processEvent(event, state, recordOutputs, span);\n yield event;\n }\n } catch (error) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n result.error = error;\n throw error;\n } finally {\n endStreamSpan(span, state, recordOutputs, () => beforeSpanEnd?.(result));\n }\n}\n\n/**\n * Instruments a MessageStream by registering event handlers and preserving the original stream API.\n */\nexport function instrumentMessageStream<R extends { on: (...args: unknown[]) => void; aborted?: boolean }>(\n stream: R,\n span: Span,\n recordOutputs: boolean,\n abortSignal?: AbortSignal,\n beforeSpanEnd?: (result: GenAiSpanResult<never>) => void,\n): R {\n const state: StreamingState = {\n responseTexts: [],\n finishReasons: [],\n responseId: '',\n responseModel: '',\n inputTokens: undefined,\n promptTokens: undefined,\n completionTokens: undefined,\n cacheCreationInputTokens: undefined,\n cacheReadInputTokens: undefined,\n toolCalls: [],\n activeToolBlocks: {},\n };\n\n stream.on('streamEvent', (event: unknown) => {\n processEvent(event as AnthropicAiStreamingEvent, state, recordOutputs, span);\n });\n\n // The event fired when a message is done being streamed by the API. Corresponds to the message_stop SSE event.\n // @see https://github.com/anthropics/anthropic-sdk-typescript/blob/d3be31f5a4e6ebb4c0a2f65dbb8f381ae73a9166/helpers.md?plain=1#L42-L44\n stream.on('message', () => {\n endStreamSpan(span, state, recordOutputs, () => beforeSpanEnd?.({}));\n });\n\n // Fires last on every stream, so a stream that stops without 'message' (aborted, or the body closed early) still\n // ends its span. An 'abort' listener would also stop the SDK from raising an unobserved abort as a rejection.\n stream.on('end', () => {\n if (span.isRecording() && stream.aborted) {\n // `aborted` is also set when the caller's `AbortSignal.timeout()` fires, which is a timeout, not a cancellation.\n span.setStatus(\n abortSignal?.aborted ? getErrorStatus(abortSignal) : { code: SPAN_STATUS_ERROR, message: 'cancelled' },\n );\n }\n endStreamSpan(span, state, recordOutputs, () => beforeSpanEnd?.({}));\n });\n\n stream.on('error', (error: unknown) => {\n // Attaching this listener stops the stream error from being raised as an unhandled rejection, so\n // we capture it here to avoid swallowing it (e.g. for callers that don't await/iterate the stream).\n captureException(error, {\n mechanism: {\n handled: false,\n type: 'auto.ai.anthropic.stream_error',\n },\n });\n\n if (span.isRecording()) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n endStreamSpan(span, state, recordOutputs, () => beforeSpanEnd?.({ error }));\n }\n });\n\n return stream;\n}\n"],"mappings":";;;;;;;;;;;;;AAoDA,SAAS,aAAa,OAAkC,MAAqB;CAC3E,IAAI,UAAU,SAAS,OAAO,MAAM,SAAS,UACvC;MAAA,MAAM,SAAS,SAAS;GAG1B,KAAK,UAAU;IAAE,MAAM;IAAmB,SAAS,iCAAiC,MAAM,OAAO,IAAI;GAAE,CAAC;GACxG,OAAO;EACT;;CAEF,OAAO;AACT;;;;;;AAQA,SAAS,sBAAsB,OAAkC,OAA6B;CAG5F,IAAI,MAAM,SAAS,iBAAiB;EAClC,IAAI,MAAM,OAAO;GAEf,gBAAgB,MAAM,OAAO,KAAK;GAClC,IAAI,OAAO,MAAM,MAAM,kBAAkB,UACvC,MAAM,mBAAmB,MAAM,MAAM;EAEzC;EACA,IAAI,MAAM,OAAO,aACf,MAAM,cAAc,KAAK,MAAM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AAC;CACzE;AACF;;;;AAKA,SAAgB,wBACd,QACA,MACA,eACA,aACA,eACG;CACH,MAAM,QAAwB;EAC5B,eAAe,CAAC;EAChB,eAAe,CAAC;EAChB,YAAY;EACZ,eAAe;EACf,aAAa,KAAA;EACb,cAAc,KAAA;EACd,kBAAkB,KAAA;EAClB,0BAA0B,KAAA;EAC1B,sBAAsB,KAAA;EACtB,WAAW,CAAC;EACZ,kBAAkB,CAAC;CACrB;CAEA,OAAO,GAAG,gBAAgB,UAAmB;EAC3C,aAAa,OAAoC,OAAO,eAAe,IAAI;CAC7E,CAAC;CAID,OAAO,GAAG,iBAAiB;EACzB,cAAc,MAAM,OAAO,qBAAqB,gBAAgB,CAAC,CAAC,CAAC;CACrE,CAAC;CAID,OAAO,GAAG,aAAa;EACrB,IAAI,KAAK,YAAY,KAAK,OAAO,SAE/B,KAAK,UACH,aAAa,UAAU,eAAe,WAAW,IAAI;GAAE,MAAM;GAAmB,SAAS;EAAY,CACvG;EAEF,cAAc,MAAM,OAAO,qBAAqB,gBAAgB,CAAC,CAAC,CAAC;CACrE,CAAC;CAED,OAAO,GAAG,UAAU,UAAmB;EAGrC,iBAAiB,OAAO,EACtB,WAAW;GACT,SAAS;GACT,MAAM;EACR,EACF,CAAC;EAED,IAAI,KAAK,YAAY,GAAG;GACtB,KAAK,UAAU;IAAE,MAAM;IAAmB,SAAS;GAAiB,CAAC;GACrE,cAAc,MAAM,OAAO,qBAAqB,gBAAgB,EAAE,MAAM,CAAC,CAAC;EAC5E;CACF,CAAC;CAED,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"streaming.js","names":[],"sources":["../../../../src/ai/anthropic-ai/streaming.ts"],"sourcesContent":["import { captureException, SPAN_STATUS_ERROR } from '@sentry/core';\nimport type { Span } from '@sentry/core';\nimport type { GenAiSpanResult } from '../core/span-hooks';\nimport { endStreamSpan, getErrorStatus } from '../core/utils';\nimport { recordTimeToFirstChunk } from '../core/time-to-first-chunk';\nimport type { AnthropicAiStreamingEvent } from './types';\nimport { mapAnthropicErrorToStatusMessage } from './utils';\n\n/**\n * State object used to accumulate information from a stream of Anthropic AI events.\n */\ninterface StreamingState {\n /** Collected response text fragments (for output recording). */\n responseTexts: string[];\n /** Reasons for finishing the response, as reported by the API. */\n finishReasons: string[];\n /** The response ID. */\n responseId: string;\n /** The model name. */\n responseModel: string;\n /** Number of input tokens, not counting cache reads and writes. */\n inputTokens: number | undefined;\n /** Number of prompt/input tokens used, including cache reads and writes. */\n promptTokens: number | undefined;\n /** Number of completion/output tokens used. */\n completionTokens: number | undefined;\n /** Number of cache creation input tokens used. */\n cacheCreationInputTokens: number | undefined;\n /** Number of cache read input tokens used. */\n cacheReadInputTokens: number | undefined;\n /** Accumulated tool calls (finalized) */\n toolCalls: Array<Record<string, unknown>>;\n /** In-progress tool call blocks keyed by index */\n activeToolBlocks: Record<\n number,\n {\n id?: string;\n name?: string;\n inputJsonParts: string[];\n }\n >;\n}\n\n/**\n * Checks if an event is an error event\n * @param event - The event to process\n * @param state - The state of the streaming process\n * @param recordOutputs - Whether to record outputs\n * @param span - The span to update\n * @returns Whether an error occurred\n */\n\nfunction isErrorEvent(event: AnthropicAiStreamingEvent, span: Span): boolean {\n if ('type' in event && typeof event.type === 'string') {\n if (event.type === 'error') {\n // The SDK surfaces this error to the caller (the async iterator rejects / their `error`\n // listener fires), so we only mark the span failed and do not record it.\n span.setStatus({ code: SPAN_STATUS_ERROR, message: mapAnthropicErrorToStatusMessage(event.error?.type) });\n return true;\n }\n }\n return false;\n}\n\n/**\n * Processes the message metadata of an event\n * @param event - The event to process\n * @param state - The state of the streaming process\n */\n\nfunction handleMessageMetadata(event: AnthropicAiStreamingEvent, state: StreamingState): void {\n // Cumulative token counts and the final stop reason both arrive on the message_delta event.\n // @see https://docs.anthropic.com/en/docs/build-with-claude/streaming#event-types\n if (event.type === 'message_delta') {\n if (event.usage) {\n // Input and cache counts can grow after message_start (e.g. with server tools), so the last value wins.\n applyInputUsage(event.usage, state);\n if (typeof event.usage.output_tokens === 'number') {\n state.completionTokens = event.usage.output_tokens;\n }\n }\n if (event.delta?.stop_reason) {\n state.finishReasons.push(event.delta.stop_reason);\n }\n }\n\n if (event.message) {\n const message = event.message;\n\n if (message.id) state.responseId = message.id;\n if (message.model) state.responseModel = message.model;\n\n if (message.usage) {\n applyInputUsage(message.usage, state);\n }\n }\n}\n\n/**\n * Records the input and cache token counts of a usage object that are numbers.\n */\nfunction applyInputUsage(\n usage: {\n input_tokens?: number | null;\n cache_creation_input_tokens?: number | null;\n cache_read_input_tokens?: number | null;\n },\n state: StreamingState,\n): void {\n if (typeof usage.input_tokens === 'number') state.inputTokens = usage.input_tokens;\n if (typeof usage.cache_creation_input_tokens === 'number')\n state.cacheCreationInputTokens = usage.cache_creation_input_tokens;\n if (typeof usage.cache_read_input_tokens === 'number') state.cacheReadInputTokens = usage.cache_read_input_tokens;\n\n if (typeof state.inputTokens === 'number') {\n state.promptTokens = state.inputTokens + (state.cacheCreationInputTokens ?? 0) + (state.cacheReadInputTokens ?? 0);\n }\n}\n\n/**\n * Handle start of a content block (e.g., tool_use)\n */\nfunction handleContentBlockStart(event: AnthropicAiStreamingEvent, state: StreamingState): void {\n if (event.type !== 'content_block_start' || typeof event.index !== 'number' || !event.content_block) return;\n if (event.content_block.type === 'tool_use' || event.content_block.type === 'server_tool_use') {\n state.activeToolBlocks[event.index] = {\n id: event.content_block.id,\n name: event.content_block.name,\n inputJsonParts: [],\n };\n }\n}\n\n/**\n * Handle deltas of a content block, including input_json_delta for tool_use\n */\nfunction handleContentBlockDelta(\n event: AnthropicAiStreamingEvent,\n state: StreamingState,\n recordOutputs: boolean,\n): void {\n if (event.type !== 'content_block_delta' || !event.delta) return;\n\n // Accumulate tool_use input JSON deltas only when we have an index and an active tool block\n if (\n typeof event.index === 'number' &&\n 'partial_json' in event.delta &&\n typeof event.delta.partial_json === 'string'\n ) {\n const active = state.activeToolBlocks[event.index];\n if (active) {\n active.inputJsonParts.push(event.delta.partial_json);\n }\n }\n\n // Accumulate streamed response text regardless of index\n if (recordOutputs && typeof event.delta.text === 'string') {\n state.responseTexts.push(event.delta.text);\n }\n}\n\n/**\n * Handle stop of a content block; finalize tool_use entries\n */\nfunction handleContentBlockStop(event: AnthropicAiStreamingEvent, state: StreamingState): void {\n if (event.type !== 'content_block_stop' || typeof event.index !== 'number') return;\n\n const active = state.activeToolBlocks[event.index];\n if (!active) return;\n\n const raw = active.inputJsonParts.join('');\n let parsedInput: unknown;\n\n try {\n parsedInput = raw ? JSON.parse(raw) : {};\n } catch {\n parsedInput = { __unparsed: raw };\n }\n\n state.toolCalls.push({\n type: 'tool_use',\n id: active.id,\n name: active.name,\n input: parsedInput,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete state.activeToolBlocks[event.index];\n}\n\n/**\n * Whether an event carries new model output, which is what `gen_ai.response.time_to_first_chunk` measures.\n * `message_start`, `ping`, empty block starts, signatures and stop events do not.\n */\nfunction hasOutput(event: AnthropicAiStreamingEvent): boolean {\n if (event.type === 'content_block_start') {\n // A tool call's name and redacted thinking arrive on the event that opens the block.\n return !!(event.content_block?.name || event.content_block?.type === 'redacted_thinking');\n }\n if (event.type === 'content_block_delta') {\n return !!(event.delta?.text || event.delta?.partial_json || event.delta?.thinking);\n }\n return false;\n}\n\n/**\n * Processes an event\n * @param event - The event to process\n * @param state - The state of the streaming process\n * @param recordOutputs - Whether to record outputs\n * @param span - The span to update\n */\nfunction processEvent(\n event: AnthropicAiStreamingEvent,\n state: StreamingState,\n recordOutputs: boolean,\n span: Span,\n): void {\n if (!(event && typeof event === 'object')) {\n return;\n }\n\n const isError = isErrorEvent(event, span);\n if (isError) return;\n\n if (hasOutput(event)) {\n recordTimeToFirstChunk(span);\n }\n\n handleMessageMetadata(event, state);\n\n // Tool call events are sent via 3 separate events:\n // - content_block_start (start of the tool call)\n // - content_block_delta (delta aka input of the tool call)\n // - content_block_stop (end of the tool call)\n // We need to handle them all to capture the full tool call.\n handleContentBlockStart(event, state);\n handleContentBlockDelta(event, state, recordOutputs);\n handleContentBlockStop(event, state);\n}\n\n/**\n * Instruments an async iterable stream of Anthropic events, updates the span with\n * streaming attributes and (optionally) the aggregated output text, and yields\n * each event from the input stream unchanged.\n */\nexport async function* instrumentAsyncIterableStream(\n stream: AsyncIterable<AnthropicAiStreamingEvent>,\n span: Span,\n recordOutputs: boolean,\n beforeSpanEnd?: (result: GenAiSpanResult<never>) => void,\n): AsyncGenerator<AnthropicAiStreamingEvent, void, unknown> {\n const state: StreamingState = {\n responseTexts: [],\n finishReasons: [],\n responseId: '',\n responseModel: '',\n inputTokens: undefined,\n promptTokens: undefined,\n completionTokens: undefined,\n cacheCreationInputTokens: undefined,\n cacheReadInputTokens: undefined,\n toolCalls: [],\n activeToolBlocks: {},\n };\n const result: GenAiSpanResult<never> = {};\n\n try {\n for await (const event of stream) {\n processEvent(event, state, recordOutputs, span);\n yield event;\n }\n } catch (error) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n result.error = error;\n throw error;\n } finally {\n endStreamSpan(span, state, recordOutputs, () => beforeSpanEnd?.(result));\n }\n}\n\n/**\n * Instruments a MessageStream by registering event handlers and preserving the original stream API.\n */\nexport function instrumentMessageStream<R extends { on: (...args: unknown[]) => void; aborted?: boolean }>(\n stream: R,\n span: Span,\n recordOutputs: boolean,\n abortSignal?: AbortSignal,\n beforeSpanEnd?: (result: GenAiSpanResult<never>) => void,\n): R {\n const state: StreamingState = {\n responseTexts: [],\n finishReasons: [],\n responseId: '',\n responseModel: '',\n inputTokens: undefined,\n promptTokens: undefined,\n completionTokens: undefined,\n cacheCreationInputTokens: undefined,\n cacheReadInputTokens: undefined,\n toolCalls: [],\n activeToolBlocks: {},\n };\n\n stream.on('streamEvent', (event: unknown) => {\n processEvent(event as AnthropicAiStreamingEvent, state, recordOutputs, span);\n });\n\n // The event fired when a message is done being streamed by the API. Corresponds to the message_stop SSE event.\n // @see https://github.com/anthropics/anthropic-sdk-typescript/blob/d3be31f5a4e6ebb4c0a2f65dbb8f381ae73a9166/helpers.md?plain=1#L42-L44\n stream.on('message', () => {\n endStreamSpan(span, state, recordOutputs, () => beforeSpanEnd?.({}));\n });\n\n // Fires last on every stream, so a stream that stops without 'message' (aborted, or the body closed early) still\n // ends its span. An 'abort' listener would also stop the SDK from raising an unobserved abort as a rejection.\n stream.on('end', () => {\n if (span.isRecording() && stream.aborted) {\n // `aborted` is also set when the caller's `AbortSignal.timeout()` fires, which is a timeout, not a cancellation.\n span.setStatus(\n abortSignal?.aborted ? getErrorStatus(abortSignal) : { code: SPAN_STATUS_ERROR, message: 'cancelled' },\n );\n }\n endStreamSpan(span, state, recordOutputs, () => beforeSpanEnd?.({}));\n });\n\n stream.on('error', (error: unknown) => {\n // Attaching this listener stops the stream error from being raised as an unhandled rejection, so\n // we capture it here to avoid swallowing it (e.g. for callers that don't await/iterate the stream).\n captureException(error, {\n mechanism: {\n handled: false,\n type: 'auto.ai.anthropic.stream_error',\n },\n });\n\n if (span.isRecording()) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n endStreamSpan(span, state, recordOutputs, () => beforeSpanEnd?.({ error }));\n }\n });\n\n return stream;\n}\n"],"mappings":";;;;;;;;;;;;;AAoDA,SAAS,aAAa,OAAkC,MAAqB;CAC3E,IAAI,UAAU,SAAS,OAAO,MAAM,SAAS,UACvC;MAAA,MAAM,SAAS,SAAS;GAG1B,KAAK,UAAU;IAAE,MAAM;IAAmB,SAAS,iCAAiC,MAAM,OAAO,IAAI;GAAE,CAAC;GACxG,OAAO;EACT;;CAEF,OAAO;AACT;;;;;;AAQA,SAAS,sBAAsB,OAAkC,OAA6B;CAG5F,IAAI,MAAM,SAAS,iBAAiB;EAClC,IAAI,MAAM,OAAO;GAEf,gBAAgB,MAAM,OAAO,KAAK;GAClC,IAAI,OAAO,MAAM,MAAM,kBAAkB,UACvC,MAAM,mBAAmB,MAAM,MAAM;EAEzC;EACA,IAAI,MAAM,OAAO,aAC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AAC;CAED,OAAO;AACT"}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
+
import { SPAN_STATUS_ERROR, captureException, fill, getActiveSpan, getCurrentScope, getDefaultCurrentScope, getDefaultIsolationScope, getIsolationScope, getOriginalFunction, handleCallbackErrors, startInactiveSpan, startNewTrace, startSpan, stringify, withActiveSpan, withScope } from "@sentry/core";
|
|
2
|
+
import { GEN_AI_CONVERSATION_ID, GEN_AI_OPERATION_NAME, GEN_AI_PROVIDER_NAME, GEN_AI_TOOL_CALL_ARGUMENTS, GEN_AI_TOOL_CALL_RESULT, GEN_AI_TOOL_DESCRIPTION, GEN_AI_TOOL_NAME, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
|
|
3
|
+
import { GEN_AI_EXECUTE_TOOL, GEN_AI_INVOKE_AGENT } from "@sentry/conventions/op";
|
|
1
4
|
import { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from "../core/gen-ai-attributes.js";
|
|
2
5
|
import { runGenAiSpanEnd, runGenAiSpanStart } from "../core/span-hooks.js";
|
|
3
6
|
import { getErrorStatus, resolveGenAiCallRecording } from "../core/utils.js";
|
|
4
7
|
import { withCleanScopes } from "../../utils/withCleanScopes.js";
|
|
5
8
|
import { ANTHROPIC_AI_ORIGIN } from "./constants.js";
|
|
6
|
-
import { GEN_AI_CONVERSATION_ID, GEN_AI_OPERATION_NAME, GEN_AI_PROVIDER_NAME, GEN_AI_TOOL_CALL_ARGUMENTS, GEN_AI_TOOL_CALL_RESULT, GEN_AI_TOOL_DESCRIPTION, GEN_AI_TOOL_NAME, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
|
|
7
|
-
import { SPAN_STATUS_ERROR, captureException, fill, getActiveSpan, getCurrentScope, getDefaultCurrentScope, getDefaultIsolationScope, getIsolationScope, getOriginalFunction, handleCallbackErrors, startInactiveSpan, startNewTrace, startSpan, stringify, withActiveSpan, withScope } from "@sentry/core";
|
|
8
|
-
import { GEN_AI_EXECUTE_TOOL, GEN_AI_INVOKE_AGENT } from "@sentry/conventions/op";
|
|
9
9
|
// src/ai/anthropic-ai/tool-runner.ts
|
|
10
10
|
/** Wrap the `toolRunner()` method of `owner` so the runners it returns trace their tool calls. */
|
|
11
11
|
function instrumentToolRunnerFactory(owner, instrumentRunner, options) {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { extractSystemInstructions, getTokenUsageAttributes } from "../core/utils.js";
|
|
2
|
-
import { GEN_AI_INPUT_MESSAGES, GEN_AI_RESPONSE_ID, GEN_AI_RESPONSE_MODEL, GEN_AI_RESPONSE_TEXT, GEN_AI_RESPONSE_TOOL_CALLS, GEN_AI_SYSTEM_INSTRUCTIONS } from "@sentry/conventions/attributes";
|
|
3
1
|
import { SPAN_STATUS_ERROR, captureException, isObjectLike, stringify } from "@sentry/core";
|
|
2
|
+
import { GEN_AI_INPUT_MESSAGES, GEN_AI_RESPONSE_ID, GEN_AI_RESPONSE_MODEL, GEN_AI_RESPONSE_TEXT, GEN_AI_RESPONSE_TOOL_CALLS, GEN_AI_SYSTEM_INSTRUCTIONS } from "@sentry/conventions/attributes";
|
|
3
|
+
import { extractSystemInstructions, getTokenUsageAttributes } from "../core/utils.js";
|
|
4
4
|
// src/ai/anthropic-ai/utils.ts
|
|
5
5
|
/**
|
|
6
6
|
* The `gen_ai.provider.name` of the client that owns an SDK resource such as `messages`. The SDK's clients
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { DEBUG_BUILD } from "../../debug-build.js";
|
|
2
1
|
import { debug } from "@sentry/core";
|
|
2
|
+
import { DEBUG_BUILD } from "../../debug-build.js";
|
|
3
3
|
// src/ai/core/span-hooks.ts
|
|
4
4
|
/** Runs {@link GenAiSpanHooks.onSpanStart}. */
|
|
5
5
|
function runGenAiSpanStart(hooks, span, call) {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK } from "@sentry/conventions/attributes";
|
|
2
1
|
import { spanToJSON, timestampInSeconds } from "@sentry/core";
|
|
2
|
+
import { GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK } from "@sentry/conventions/attributes";
|
|
3
3
|
// src/ai/core/time-to-first-chunk.ts
|
|
4
4
|
/**
|
|
5
5
|
* Sets `gen_ai.response.time_to_first_chunk` on a streamed span, in seconds from the span start.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { DEBUG_BUILD } from "../../debug-build.js";
|
|
2
|
-
import { GEN_AI_OUTPUT_MESSAGES, GEN_AI_RESPONSE_FINISH_REASONS, GEN_AI_RESPONSE_ID, GEN_AI_RESPONSE_MODEL, GEN_AI_RESPONSE_STREAMING, GEN_AI_RESPONSE_TEXT, GEN_AI_RESPONSE_TOOL_CALLS, GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, GEN_AI_USAGE_INPUT_TOKENS, GEN_AI_USAGE_OUTPUT_TOKENS, GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, GEN_AI_USAGE_TOTAL_TOKENS } from "@sentry/conventions/attributes";
|
|
3
1
|
import { SPAN_STATUS_ERROR, debug, getClient, isObjectLike, isThenable, stringify } from "@sentry/core";
|
|
2
|
+
import { GEN_AI_OUTPUT_MESSAGES, GEN_AI_RESPONSE_FINISH_REASONS, GEN_AI_RESPONSE_ID, GEN_AI_RESPONSE_MODEL, GEN_AI_RESPONSE_STREAMING, GEN_AI_RESPONSE_TEXT, GEN_AI_RESPONSE_TOOL_CALLS, GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, GEN_AI_USAGE_INPUT_TOKENS, GEN_AI_USAGE_OUTPUT_TOKENS, GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, GEN_AI_USAGE_TOTAL_TOKENS } from "@sentry/conventions/attributes";
|
|
4
3
|
import { FUNCTION } from "@sentry/conventions/op";
|
|
4
|
+
import { DEBUG_BUILD } from "../../debug-build.js";
|
|
5
5
|
// src/ai/core/utils.ts
|
|
6
6
|
/**
|
|
7
7
|
* Shared utils for AI integrations (OpenAI, Anthropic, Verce.AI, etc.)
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { LRUMap, consoleSandbox, continueTrace, getActiveSpan, getDefaultIsolationScope, getIsolationScope, sentryTraceFromTraceparent, startNewTrace, startSpan, withActiveSpan, withScope } from "@sentry/core";
|
|
2
|
+
import { GEN_AI_AGENT_NAME, GEN_AI_CONVERSATION_ID, GEN_AI_OPERATION_NAME, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
|
|
1
3
|
import { getGenAiSpanOp } from "../core/utils.js";
|
|
2
4
|
import { getOrchestrionInjectedModules } from "../../orchestrion/detect.js";
|
|
3
5
|
import { piAiModuleNames } from "../../orchestrion/config/pi-ai.js";
|
|
@@ -6,8 +8,6 @@ import { isBun, isCloudflareWorkers, isDeno } from "../../utils/runtime.js";
|
|
|
6
8
|
import { withCleanScopes } from "../../utils/withCleanScopes.js";
|
|
7
9
|
import { FLUE_INSTRUMENTATION_KEY, FLUE_OPERATION, FLUE_ORIGIN, MAX_TRACKED_FLUE_SPANS } from "./constants.js";
|
|
8
10
|
import { endToolSpan, startToolSpan } from "./utils.js";
|
|
9
|
-
import { GEN_AI_AGENT_NAME, GEN_AI_CONVERSATION_ID, GEN_AI_OPERATION_NAME, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
|
|
10
|
-
import { LRUMap, consoleSandbox, continueTrace, getActiveSpan, getDefaultIsolationScope, getIsolationScope, sentryTraceFromTraceparent, startNewTrace, startSpan, withActiveSpan, withScope } from "@sentry/core";
|
|
11
11
|
// src/ai/flue/index.ts
|
|
12
12
|
let checkedPiAiInstrumentation = false;
|
|
13
13
|
/**
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
+
import { SPAN_STATUS_ERROR, captureException, isObjectLike, startInactiveSpan, stringify, withActiveSpan } from "@sentry/core";
|
|
2
|
+
import { GEN_AI_CONVERSATION_ID, GEN_AI_OPERATION_NAME, GEN_AI_TOOL_CALL_ARGUMENTS, GEN_AI_TOOL_CALL_RESULT, GEN_AI_TOOL_NAME, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
|
|
1
3
|
import { runGenAiSpanEnd, runGenAiSpanStart } from "../core/span-hooks.js";
|
|
2
4
|
import { getGenAiSpanOp, resolveGenAiCallRecording } from "../core/utils.js";
|
|
3
5
|
import { piAiContentToString } from "../pi-ai/messages.js";
|
|
4
6
|
import { FLUE_ORIGIN } from "./constants.js";
|
|
5
|
-
import { GEN_AI_CONVERSATION_ID, GEN_AI_OPERATION_NAME, GEN_AI_TOOL_CALL_ARGUMENTS, GEN_AI_TOOL_CALL_RESULT, GEN_AI_TOOL_NAME, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
|
|
6
|
-
import { SPAN_STATUS_ERROR, captureException, isObjectLike, startInactiveSpan, stringify, withActiveSpan } from "@sentry/core";
|
|
7
7
|
// src/ai/flue/utils.ts
|
|
8
8
|
const TOOL_SPANS_RECORDING_OUTPUTS = /* @__PURE__ */ new WeakSet();
|
|
9
9
|
const TOOL_SPAN_END_HOOKS = /* @__PURE__ */ new WeakMap();
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { getEvaluationInputMessages, getEvaluationOutputMessages, getTokenUsageAttributes } from "../core/utils.js";
|
|
2
1
|
import { GEN_AI_OUTPUT_MESSAGES } from "@sentry/conventions/attributes";
|
|
3
2
|
import { isObjectLike } from "@sentry/core";
|
|
3
|
+
import { getEvaluationInputMessages, getEvaluationOutputMessages, getTokenUsageAttributes } from "../core/utils.js";
|
|
4
4
|
// src/ai/google-genai/decisions.ts
|
|
5
5
|
/**
|
|
6
6
|
* Serialize a decisions request. Its evidence is `input` where Jev's is `state`; it is recorded as `state`
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
+
import { getClient, handleCallbackErrors, hasSpanStreamingEnabled, startSpan, startSpanManual, stringify } from "@sentry/core";
|
|
2
|
+
import { GEN_AI_EMBEDDINGS_INPUT, GEN_AI_INPUT_MESSAGES, GEN_AI_OPERATION_NAME, GEN_AI_PROVIDER_NAME, GEN_AI_REQUEST_FREQUENCY_PENALTY, GEN_AI_REQUEST_MAX_TOKENS, GEN_AI_REQUEST_MODEL, GEN_AI_REQUEST_PRESENCE_PENALTY, GEN_AI_REQUEST_TEMPERATURE, GEN_AI_REQUEST_TOP_K, GEN_AI_REQUEST_TOP_P, GEN_AI_RESPONSE_MODEL, GEN_AI_RESPONSE_TEXT, GEN_AI_RESPONSE_TOOL_CALLS, GEN_AI_SYSTEM_INSTRUCTIONS, GEN_AI_TOOL_DEFINITIONS, GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
|
|
1
3
|
import { runGenAiSpanEnd, runGenAiSpanStart } from "../core/span-hooks.js";
|
|
2
4
|
import { buildMethodPath, getErrorStatus, getGenAiSpanOp, getRequestSignal, getTokenUsageAttributes, resolveGenAiCallRecording } from "../core/utils.js";
|
|
3
5
|
import { GOOGLE_GENAI_METHOD_REGISTRY, GOOGLE_GENAI_SYSTEM_NAME } from "./constants.js";
|
|
4
6
|
import { addDecisionResponseAttributes, getDecisionInputMessages } from "./decisions.js";
|
|
5
7
|
import { instrumentStream } from "./streaming.js";
|
|
6
8
|
import { candidatesToMessageParts, contentUnionToMessages, setOutputMessagesAttribute, systemInstructionToText } from "./utils.js";
|
|
7
|
-
import { GEN_AI_EMBEDDINGS_INPUT, GEN_AI_INPUT_MESSAGES, GEN_AI_OPERATION_NAME, GEN_AI_PROVIDER_NAME, GEN_AI_REQUEST_FREQUENCY_PENALTY, GEN_AI_REQUEST_MAX_TOKENS, GEN_AI_REQUEST_MODEL, GEN_AI_REQUEST_PRESENCE_PENALTY, GEN_AI_REQUEST_TEMPERATURE, GEN_AI_REQUEST_TOP_K, GEN_AI_REQUEST_TOP_P, GEN_AI_RESPONSE_MODEL, GEN_AI_RESPONSE_TEXT, GEN_AI_RESPONSE_TOOL_CALLS, GEN_AI_SYSTEM_INSTRUCTIONS, GEN_AI_TOOL_DEFINITIONS, GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
|
|
8
|
-
import { getClient, handleCallbackErrors, hasSpanStreamingEnabled, startSpan, startSpanManual, stringify } from "@sentry/core";
|
|
9
9
|
// src/ai/google-genai/index.ts
|
|
10
10
|
/**
|
|
11
11
|
* Extract model from parameters or chat context object
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
+
import { SPAN_STATUS_ERROR, captureException } from "@sentry/core";
|
|
1
2
|
import { endStreamSpan, getErrorStatus } from "../core/utils.js";
|
|
2
3
|
import { recordTimeToFirstChunk } from "../core/time-to-first-chunk.js";
|
|
3
4
|
import { candidatesToMessageParts, setOutputMessagesAttribute } from "./utils.js";
|
|
4
|
-
import { SPAN_STATUS_ERROR, captureException } from "@sentry/core";
|
|
5
5
|
// src/ai/google-genai/streaming.ts
|
|
6
6
|
/**
|
|
7
7
|
* Checks if a response chunk contains an error
|
|
@@ -59,6 +59,13 @@ function handleCandidateContent(chunk, state, recordOutputs) {
|
|
|
59
59
|
}
|
|
60
60
|
}
|
|
61
61
|
/**
|
|
62
|
+
* Whether a chunk carries new model output, which is what `gen_ai.response.time_to_first_chunk` measures.
|
|
63
|
+
* Chunks with only usage, a finish reason or a thought signature do not.
|
|
64
|
+
*/
|
|
65
|
+
function hasOutput(chunk) {
|
|
66
|
+
return (chunk.candidates ?? []).some((candidate) => (candidate?.content?.parts ?? []).some((part) => !!(part.text || part.functionCall || part.inlineData)));
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
62
69
|
* Processes a single chunk from the Google GenAI stream
|
|
63
70
|
* @param chunk - The chunk to process
|
|
64
71
|
* @param state - The state of the streaming process
|
|
@@ -67,7 +74,7 @@ function handleCandidateContent(chunk, state, recordOutputs) {
|
|
|
67
74
|
*/
|
|
68
75
|
function processChunk(chunk, state, recordOutputs, span) {
|
|
69
76
|
if (!chunk || isErrorChunk(chunk, span)) return;
|
|
70
|
-
recordTimeToFirstChunk(span);
|
|
77
|
+
if (hasOutput(chunk)) recordTimeToFirstChunk(span);
|
|
71
78
|
handleResponseMetadata(chunk, state);
|
|
72
79
|
handleCandidateContent(chunk, state, recordOutputs);
|
|
73
80
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"streaming.js","names":[],"sources":["../../../../src/ai/google-genai/streaming.ts"],"sourcesContent":["import { captureException, SPAN_STATUS_ERROR } from '@sentry/core';\nimport type { Span } from '@sentry/core';\nimport type { GenAiSpanResult } from '../core/span-hooks';\nimport { endStreamSpan, getErrorStatus } from '../core/utils';\nimport { recordTimeToFirstChunk } from '../core/time-to-first-chunk';\nimport type { GoogleGenAIResponse } from './types';\nimport type { MessagePart } from './utils';\nimport { candidatesToMessageParts, setOutputMessagesAttribute } from './utils';\n\n/**\n * State object used to accumulate information from a stream of Google GenAI events.\n */\ninterface StreamingState {\n /** Collected response text fragments (for output recording). */\n responseTexts: string[];\n /** Reasons for finishing the response, as reported by the API. */\n finishReasons: string[];\n /** The response ID. */\n responseId?: string;\n /** The model name. */\n responseModel?: string;\n /** Number of prompt/input tokens used. Tool-use prompt tokens are added when the stream ends. */\n promptTokens?: number;\n toolUsePromptTokens?: number;\n /** Number of completion/output tokens used. */\n completionTokens?: number;\n candidateTokens?: number;\n reasoningOutputTokens?: number;\n /** Number of total tokens used. */\n totalTokens?: number;\n cacheReadInputTokens?: number;\n /** Accumulated tool calls (finalized) */\n toolCalls: Array<Record<string, unknown>>;\n /** Accumulated output message parts (for output recording). */\n outputParts: MessagePart[];\n}\n\n/**\n * Checks if a response chunk contains an error\n * @param chunk - The response chunk to check\n * @param span - The span to update if error is found\n * @returns Whether an error occurred\n */\nfunction isErrorChunk(chunk: GoogleGenAIResponse, span: Span): boolean {\n const feedback = chunk?.promptFeedback;\n if (feedback?.blockReason) {\n const message = feedback.blockReasonMessage ?? feedback.blockReason;\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n captureException(`Content blocked: ${message}`, {\n mechanism: { handled: false, type: 'auto.ai.google_genai' },\n });\n return true;\n }\n return false;\n}\n\n/**\n * Processes response metadata from a chunk\n * @param chunk - The response chunk to process\n * @param state - The state of the streaming process\n */\nfunction handleResponseMetadata(chunk: GoogleGenAIResponse, state: StreamingState): void {\n if (typeof chunk.responseId === 'string') state.responseId = chunk.responseId;\n if (typeof chunk.modelVersion === 'string') state.responseModel = chunk.modelVersion;\n\n const usage = chunk.usageMetadata;\n if (usage) {\n if (typeof usage.promptTokenCount === 'number') state.promptTokens = usage.promptTokenCount;\n if (typeof usage.toolUsePromptTokenCount === 'number') state.toolUsePromptTokens = usage.toolUsePromptTokenCount;\n if (typeof usage.candidatesTokenCount === 'number') state.candidateTokens = usage.candidatesTokenCount;\n if (typeof usage.thoughtsTokenCount === 'number') state.reasoningOutputTokens = usage.thoughtsTokenCount;\n if (state.candidateTokens !== undefined || state.reasoningOutputTokens !== undefined) {\n state.completionTokens = (state.candidateTokens ?? 0) + (state.reasoningOutputTokens ?? 0);\n }\n if (typeof usage.totalTokenCount === 'number') state.totalTokens = usage.totalTokenCount;\n if (typeof usage.cachedContentTokenCount === 'number') state.cacheReadInputTokens = usage.cachedContentTokenCount;\n }\n}\n\n/**\n * Processes candidate content from a response chunk\n * @param chunk - The response chunk to process\n * @param state - The state of the streaming process\n * @param recordOutputs - Whether to record outputs\n */\nfunction handleCandidateContent(chunk: GoogleGenAIResponse, state: StreamingState, recordOutputs: boolean): void {\n // The SDK getter already extracts function calls from candidate parts.\n if (Array.isArray(chunk.functionCalls)) {\n state.toolCalls.push(...chunk.functionCalls);\n }\n\n if (recordOutputs) {\n state.outputParts.push(...candidatesToMessageParts(chunk.candidates));\n }\n\n for (const candidate of chunk.candidates ?? []) {\n if (candidate?.finishReason && !state.finishReasons.includes(candidate.finishReason)) {\n state.finishReasons.push(candidate.finishReason);\n }\n\n for (const part of candidate?.content?.parts ?? []) {\n if (recordOutputs && part.text) state.responseTexts.push(part.text);\n }\n }\n}\n\n/**\n * Processes a single chunk from the Google GenAI stream\n * @param chunk - The chunk to process\n * @param state - The state of the streaming process\n * @param recordOutputs - Whether to record outputs\n * @param span - The span to update\n */\nfunction processChunk(chunk: GoogleGenAIResponse, state: StreamingState, recordOutputs: boolean, span: Span): void {\n if (!chunk || isErrorChunk(chunk, span)) return;\n recordTimeToFirstChunk(span);\n handleResponseMetadata(chunk, state);\n handleCandidateContent(chunk, state, recordOutputs);\n}\n\n/**\n * Instruments an async iterable stream of Google GenAI response chunks, updates the span with\n * streaming attributes and (optionally) the aggregated output text, and yields\n * each chunk from the input stream unchanged.\n */\nexport async function* instrumentStream(\n stream: AsyncIterable<GoogleGenAIResponse>,\n span: Span,\n recordOutputs: boolean,\n abortSignal?: AbortSignal,\n beforeSpanEnd?: (result: GenAiSpanResult<never>) => void,\n): AsyncGenerator<GoogleGenAIResponse, void, unknown> {\n const state: StreamingState = {\n responseTexts: [],\n finishReasons: [],\n toolCalls: [],\n outputParts: [],\n };\n const result: GenAiSpanResult<never> = {};\n\n try {\n for await (const chunk of stream) {\n processChunk(chunk, state, recordOutputs, span);\n yield chunk;\n }\n } catch (error) {\n span.setStatus(getErrorStatus(abortSignal));\n result.error = error;\n throw error;\n } finally {\n if (recordOutputs) {\n setOutputMessagesAttribute(span, state.outputParts);\n }\n if (typeof state.promptTokens === 'number') state.promptTokens += state.toolUsePromptTokens ?? 0;\n endStreamSpan(span, state, recordOutputs, () => beforeSpanEnd?.(result));\n }\n}\n"],"mappings":";;;;;;;;;;;AA2CA,SAAS,aAAa,OAA4B,MAAqB;CACrE,MAAM,WAAW,OAAO;CACxB,IAAI,UAAU,aAAa;EACzB,MAAM,UAAU,SAAS,sBAAsB,SAAS;EACxD,KAAK,UAAU;GAAE,MAAM;GAAmB,SAAS;EAAiB,CAAC;EACrE,iBAAiB,oBAAoB,WAAW,EAC9C,WAAW;GAAE,SAAS;GAAO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OAA4B,OAAuB,eAAwB,MAAkB;CACjH,IAAI,CAAC,SAAS,aAAa,OAAO,IAAI,GAAG;CACzC,uBAAuB,IAAI;
|
|
1
|
+
{"version":3,"file":"streaming.js","names":[],"sources":["../../../../src/ai/google-genai/streaming.ts"],"sourcesContent":["import { captureException, SPAN_STATUS_ERROR } from '@sentry/core';\nimport type { Span } from '@sentry/core';\nimport type { GenAiSpanResult } from '../core/span-hooks';\nimport { endStreamSpan, getErrorStatus } from '../core/utils';\nimport { recordTimeToFirstChunk } from '../core/time-to-first-chunk';\nimport type { GoogleGenAIResponse } from './types';\nimport type { MessagePart } from './utils';\nimport { candidatesToMessageParts, setOutputMessagesAttribute } from './utils';\n\n/**\n * State object used to accumulate information from a stream of Google GenAI events.\n */\ninterface StreamingState {\n /** Collected response text fragments (for output recording). */\n responseTexts: string[];\n /** Reasons for finishing the response, as reported by the API. */\n finishReasons: string[];\n /** The response ID. */\n responseId?: string;\n /** The model name. */\n responseModel?: string;\n /** Number of prompt/input tokens used. Tool-use prompt tokens are added when the stream ends. */\n promptTokens?: number;\n toolUsePromptTokens?: number;\n /** Number of completion/output tokens used. */\n completionTokens?: number;\n candidateTokens?: number;\n reasoningOutputTokens?: number;\n /** Number of total tokens used. */\n totalTokens?: number;\n cacheReadInputTokens?: number;\n /** Accumulated tool calls (finalized) */\n toolCalls: Array<Record<string, unknown>>;\n /** Accumulated output message parts (for output recording). */\n outputParts: MessagePart[];\n}\n\n/**\n * Checks if a response chunk contains an error\n * @param chunk - The response chunk to check\n * @param span - The span to update if error is found\n * @returns Whether an error occurred\n */\nfunction isErrorChunk(chunk: GoogleGenAIResponse, span: Span): boolean {\n const feedback = chunk?.promptFeedback;\n if (feedback?.blockReason) {\n const message = feedback.blockReasonMessage ?? feedback.blockReason;\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n captureException(`Content blocked: ${message}`, {\n mechanism: { handled: false, type: 'auto.ai.google_genai' },\n });\n return true;\n }\n return false;\n}\n\n/**\n * Processes response metadata from a chunk\n * @param chunk - The response chunk to process\n * @param state - The state of the streaming process\n */\nfunction handleResponseMetadata(chunk: GoogleGenAIResponse, state: StreamingState): void {\n if (typeof chunk.responseId === 'string') state.responseId = chunk.responseId;\n if (typeof chunk.modelVersion === 'string') state.responseModel = chunk.modelVersion;\n\n const usage = chunk.usageMetadata;\n if (usage) {\n if (typeof usage.promptTokenCount === 'number') state.promptTokens = usage.promptTokenCount;\n if (typeof usage.toolUsePromptTokenCount === 'number') state.toolUsePromptTokens = usage.toolUsePromptTokenCount;\n if (typeof usage.candidatesTokenCount === 'number') state.candidateTokens = usage.candidatesTokenCount;\n if (typeof usage.thoughtsTokenCount === 'number') state.reasoningOutputTokens = usage.thoughtsTokenCount;\n if (state.candidateTokens !== undefined || state.reasoningOutputTokens !== undefined) {\n state.completionTokens = (state.candidateTokens ?? 0) + (state.reasoningOutputTokens ?? 0);\n }\n if (typeof usage.totalTokenCount === 'number') state.totalTokens = usage.totalTokenCount;\n if (typeof usage.cachedContentTokenCount === 'number') state.cacheReadInputTokens = usage.cachedContentTokenCount;\n }\n}\n\n/**\n * Processes candidate content from a response chunk\n * @param chunk - The response chunk to process\n * @param state - The state of the streaming process\n * @param recordOutputs - Whether to record outputs\n */\nfunction handleCandidateContent(chunk: GoogleGenAIResponse, state: StreamingState, recordOutputs: boolean): void {\n // The SDK getter already extracts function calls from candidate parts.\n if (Array.isArray(chunk.functionCalls)) {\n state.toolCalls.push(...chunk.functionCalls);\n }\n\n if (recordOutputs) {\n state.outputParts.push(...candidatesToMessageParts(chunk.candidates));\n }\n\n for (const candidate of chunk.candidates ?? []) {\n if (candidate?.finishReason && !state.finishReasons.includes(candidate.finishReason)) {\n state.finishReasons.push(candidate.finishReason);\n }\n\n for (const part of candidate?.content?.parts ?? []) {\n if (recordOutputs && part.text) state.responseTexts.push(part.text);\n }\n }\n}\n\n/**\n * Whether a chunk carries new model output, which is what `gen_ai.response.time_to_first_chunk` measures.\n * Chunks with only usage, a finish reason or a thought signature do not.\n */\nfunction hasOutput(chunk: GoogleGenAIResponse): boolean {\n return (chunk.candidates ?? []).some(candidate =>\n (candidate?.content?.parts ?? []).some(part => !!(part.text || part.functionCall || part.inlineData)),\n );\n}\n\n/**\n * Processes a single chunk from the Google GenAI stream\n * @param chunk - The chunk to process\n * @param state - The state of the streaming process\n * @param recordOutputs - Whether to record outputs\n * @param span - The span to update\n */\nfunction processChunk(chunk: GoogleGenAIResponse, state: StreamingState, recordOutputs: boolean, span: Span): void {\n if (!chunk || isErrorChunk(chunk, span)) return;\n if (hasOutput(chunk)) {\n recordTimeToFirstChunk(span);\n }\n handleResponseMetadata(chunk, state);\n handleCandidateContent(chunk, state, recordOutputs);\n}\n\n/**\n * Instruments an async iterable stream of Google GenAI response chunks, updates the span with\n * streaming attributes and (optionally) the aggregated output text, and yields\n * each chunk from the input stream unchanged.\n */\nexport async function* instrumentStream(\n stream: AsyncIterable<GoogleGenAIResponse>,\n span: Span,\n recordOutputs: boolean,\n abortSignal?: AbortSignal,\n beforeSpanEnd?: (result: GenAiSpanResult<never>) => void,\n): AsyncGenerator<GoogleGenAIResponse, void, unknown> {\n const state: StreamingState = {\n responseTexts: [],\n finishReasons: [],\n toolCalls: [],\n outputParts: [],\n };\n const result: GenAiSpanResult<never> = {};\n\n try {\n for await (const chunk of stream) {\n processChunk(chunk, state, recordOutputs, span);\n yield chunk;\n }\n } catch (error) {\n span.setStatus(getErrorStatus(abortSignal));\n result.error = error;\n throw error;\n } finally {\n if (recordOutputs) {\n setOutputMessagesAttribute(span, state.outputParts);\n }\n if (typeof state.promptTokens === 'number') state.promptTokens += state.toolUsePromptTokens ?? 0;\n endStreamSpan(span, state, recordOutputs, () => beforeSpanEnd?.(result));\n }\n}\n"],"mappings":";;;;;;;;;;;AA2CA,SAAS,aAAa,OAA4B,MAAqB;CACrE,MAAM,WAAW,OAAO;CACxB,IAAI,UAAU,aAAa;EACzB,MAAM,UAAU,SAAS,sBAAsB,SAAS;EACxD,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S,CAAC,GAC/C,IAAI,iBAAiB,KAAK,MAAM,MAAM,cAAc,KAAK,KAAK,IAAI;CAEtE;AACF;;;;;AAMA,SAAS,UAAU,OAAqC;CACtD,QAAQ,MAAM,cAAc,CAAC,EAAA,CAAG,MAAK,eAClC,WAAW,SAAS,SAAS,CAAC,EAAA,CAAG,MAAK,SAAQ,CAAC,EAAE,KAAK,QAAQ,KAAK,gBAAgB,KAAK,WAAW,CACtG;AACF;;;;;;;;AASA,SAAS,aAAa,OAA4B,OAAuB,eAAwB,MAAkB;CACjH,IAAI,CAAC,SAAS,aAAa,OAAO,IAAI,GAAG;CACzC,IAAI,UAAU,KAAK,GACjB,uBAAuB,IAAI;CAE7B,uBAAuB,OAAO,KAAK;CACnC,uBAAuB,OAAO,OAAO,aAAa;AACpD;;;;;;AAOA,gBAAuB,iBACrB,QACA,MACA,eACA,aACA,eACoD;CACpD,MAAM,QAAwB;EAC5B,eAAe,CAAC;EAChB,eAAe,CAAC;EAChB,WAAW,CAAC;EACZ,aAAa,CAAC;CAChB;CACA,MAAM,SAAiC,CAAC;CAExC,IAAI;EACF,WAAW,MAAM,SAAS,QAAQ;GAChC,aAAa,OAAO,OAAO,eAAe,IAAI;GAC9C,MAAM;EACR;CACF,SAAS,OAAO;EACd,KAAK,UAAU,eAAe,WAAW,CAAC;EAC1C,OAAO,QAAQ;EACf,MAAM;CACR,UAAU;EACR,IAAI,eACF,2BAA2B,MAAM,MAAM,WAAW;EAEpD,IAAI,OAAO,MAAM,iBAAiB,UAAU,MAAM,gBAAgB,MAAM,uBAAuB;EAC/F,cAAc,MAAM,OAAO,qBAAqB,gBAAgB,MAAM,CAAC;CACzE;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { GEN_AI_OUTPUT_MESSAGES } from "@sentry/conventions/attributes";
|
|
2
1
|
import { isObjectLike, stringify } from "@sentry/core";
|
|
2
|
+
import { GEN_AI_OUTPUT_MESSAGES } from "@sentry/conventions/attributes";
|
|
3
3
|
// src/ai/google-genai/utils.ts
|
|
4
4
|
function normalizeRole(role) {
|
|
5
5
|
return role === "model" ? "assistant" : role;
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
+
import { SPAN_STATUS_ERROR, getClient, hasSpanStreamingEnabled, startSpan, stringify } from "@sentry/core";
|
|
2
|
+
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";
|
|
3
|
+
import { GEN_AI_EMBEDDINGS } from "@sentry/conventions/op";
|
|
1
4
|
import { GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE, GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE } from "../core/gen-ai-attributes.js";
|
|
2
5
|
import { runGenAiSpanEnd, runGenAiSpanStart } from "../core/span-hooks.js";
|
|
3
6
|
import { resolveGenAiCallRecording } from "../core/utils.js";
|
|
4
7
|
import { LANGCHAIN_ORIGIN } from "./constants.js";
|
|
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";
|
|
6
|
-
import { SPAN_STATUS_ERROR, getClient, hasSpanStreamingEnabled, startSpan, stringify } from "@sentry/core";
|
|
7
|
-
import { GEN_AI_EMBEDDINGS } from "@sentry/conventions/op";
|
|
8
8
|
// src/ai/langchain/embeddings.ts
|
|
9
9
|
/**
|
|
10
10
|
* Infers the AI provider system name from the embedding class instance.
|