@sentry/server-utils 10.61.0 → 10.63.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/index.js +6 -0
- package/build/cjs/index.js.map +1 -1
- package/build/cjs/integrations/tracing-channel/fastify/errors.js +42 -0
- package/build/cjs/integrations/tracing-channel/fastify/errors.js.map +1 -0
- package/build/cjs/integrations/tracing-channel/fastify/index.js +34 -0
- package/build/cjs/integrations/tracing-channel/fastify/index.js.map +1 -0
- package/build/cjs/integrations/tracing-channel/fastify/instrumentation.js +279 -0
- package/build/cjs/integrations/tracing-channel/fastify/instrumentation.js.map +1 -0
- package/build/cjs/integrations/tracing-channel/fastify/utils.js +11 -0
- package/build/cjs/integrations/tracing-channel/fastify/utils.js.map +1 -0
- package/build/cjs/integrations/tracing-channel/lru-memoizer.js +31 -0
- package/build/cjs/integrations/tracing-channel/lru-memoizer.js.map +1 -0
- package/build/cjs/integrations/tracing-channel/mysql.js +44 -82
- package/build/cjs/integrations/tracing-channel/mysql.js.map +1 -1
- package/build/cjs/orchestrion/channels.js +2 -1
- package/build/cjs/orchestrion/channels.js.map +1 -1
- package/build/cjs/orchestrion/config.js +6 -0
- package/build/cjs/orchestrion/config.js.map +1 -1
- package/build/cjs/orchestrion/index.js +2 -0
- package/build/cjs/orchestrion/index.js.map +1 -1
- package/build/cjs/tracing-channel.js +50 -11
- package/build/cjs/tracing-channel.js.map +1 -1
- package/build/cjs/vercel-ai/index.js +23 -0
- package/build/cjs/vercel-ai/index.js.map +1 -0
- package/build/cjs/vercel-ai/vercel-ai-dc-subscriber.js +362 -0
- package/build/cjs/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -0
- package/build/esm/index.js +2 -0
- package/build/esm/index.js.map +1 -1
- package/build/esm/integrations/tracing-channel/fastify/errors.js +39 -0
- package/build/esm/integrations/tracing-channel/fastify/errors.js.map +1 -0
- package/build/esm/integrations/tracing-channel/fastify/index.js +30 -0
- package/build/esm/integrations/tracing-channel/fastify/index.js.map +1 -0
- package/build/esm/integrations/tracing-channel/fastify/instrumentation.js +277 -0
- package/build/esm/integrations/tracing-channel/fastify/instrumentation.js.map +1 -0
- package/build/esm/integrations/tracing-channel/fastify/utils.js +8 -0
- package/build/esm/integrations/tracing-channel/fastify/utils.js.map +1 -0
- package/build/esm/integrations/tracing-channel/lru-memoizer.js +29 -0
- package/build/esm/integrations/tracing-channel/lru-memoizer.js.map +1 -0
- package/build/esm/integrations/tracing-channel/mysql.js +45 -83
- package/build/esm/integrations/tracing-channel/mysql.js.map +1 -1
- package/build/esm/orchestrion/channels.js +2 -1
- package/build/esm/orchestrion/channels.js.map +1 -1
- package/build/esm/orchestrion/config.js +6 -0
- package/build/esm/orchestrion/config.js.map +1 -1
- package/build/esm/orchestrion/index.js +1 -0
- package/build/esm/orchestrion/index.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/esm/tracing-channel.js +51 -12
- package/build/esm/tracing-channel.js.map +1 -1
- package/build/esm/vercel-ai/index.js +21 -0
- package/build/esm/vercel-ai/index.js.map +1 -0
- package/build/esm/vercel-ai/vercel-ai-dc-subscriber.js +357 -0
- package/build/esm/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -0
- package/build/types/index.d.ts +2 -0
- package/build/types/index.d.ts.map +1 -1
- package/build/types/integrations/tracing-channel/fastify/errors.d.ts +12 -0
- package/build/types/integrations/tracing-channel/fastify/errors.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/fastify/index.d.ts +66 -0
- package/build/types/integrations/tracing-channel/fastify/index.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/fastify/instrumentation.d.ts +10 -0
- package/build/types/integrations/tracing-channel/fastify/instrumentation.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/fastify/types.d.ts +32 -0
- package/build/types/integrations/tracing-channel/fastify/types.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/fastify/utils.d.ts +9 -0
- package/build/types/integrations/tracing-channel/fastify/utils.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/lru-memoizer.d.ts +10 -0
- package/build/types/integrations/tracing-channel/lru-memoizer.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/mysql.d.ts +3 -1
- package/build/types/integrations/tracing-channel/mysql.d.ts.map +1 -1
- package/build/types/orchestrion/channels.d.ts +1 -0
- package/build/types/orchestrion/channels.d.ts.map +1 -1
- package/build/types/orchestrion/config.d.ts.map +1 -1
- package/build/types/orchestrion/index.d.ts +1 -0
- package/build/types/orchestrion/index.d.ts.map +1 -1
- package/build/types/tracing-channel.d.ts +22 -0
- package/build/types/tracing-channel.d.ts.map +1 -1
- package/build/types/vercel-ai/index.d.ts +27 -0
- package/build/types/vercel-ai/index.d.ts.map +1 -0
- package/build/types/vercel-ai/vercel-ai-dc-subscriber.d.ts +62 -0
- package/build/types/vercel-ai/vercel-ai-dc-subscriber.d.ts.map +1 -0
- package/build/types-ts3.8/index.d.ts +3 -0
- package/build/types-ts3.8/integrations/tracing-channel/fastify/errors.d.ts +12 -0
- package/build/types-ts3.8/integrations/tracing-channel/fastify/index.d.ts +66 -0
- package/build/types-ts3.8/integrations/tracing-channel/fastify/instrumentation.d.ts +10 -0
- package/build/types-ts3.8/integrations/tracing-channel/fastify/types.d.ts +32 -0
- package/build/types-ts3.8/integrations/tracing-channel/fastify/utils.d.ts +9 -0
- package/build/types-ts3.8/integrations/tracing-channel/lru-memoizer.d.ts +10 -0
- package/build/types-ts3.8/integrations/tracing-channel/mysql.d.ts +3 -1
- package/build/types-ts3.8/node-diagnostics-channel.d.ts +19 -0
- package/build/types-ts3.8/orchestrion/channels.d.ts +1 -0
- package/build/types-ts3.8/orchestrion/index.d.ts +1 -0
- package/build/types-ts3.8/tracing-channel.d.ts +22 -0
- package/build/types-ts3.8/vercel-ai/index.d.ts +27 -0
- package/build/types-ts3.8/vercel-ai/vercel-ai-dc-subscriber.d.ts +62 -0
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.js","sources":["../../../src/orchestrion/config.ts"],"sourcesContent":["import type { InstrumentationConfig } from '@apm-js-collab/code-transformer';\n\n/**\n * The central list of channel injections orchestrion should perform.\n *\n * This module has NO side effects — it's the only thing both the runtime hook\n * (`runtime/import-hook.mjs`) and the bundler plugins (`bundler/vite.ts`, …)\n * import from. Adding a new instrumented method is one entry here plus one\n * subscriber in `integrations/<lib>/tracing-channel.ts`.\n *\n * `channelName` here is the unprefixed suffix; the actual diagnostics_channel\n * name is `orchestrion:${module.name}:${channelName}` (see `channels.ts`).\n */\nexport const SENTRY_INSTRUMENTATIONS: InstrumentationConfig[] = [\n {\n channelName: 'query',\n module: { name: 'mysql', versionRange: '>=2.0.0 <3', filePath: 'lib/Connection.js' },\n // `Connection` in mysql v2 is a constructor function (NOT a class):\n // `function Connection(options) { ... }`\n // `Connection.prototype.query = function query(sql, values, cb) { ... }`\n // orchestrion's `className`+`methodName` query only matches `class` declarations.\n // The named function expression on the right-hand side of the prototype\n // assignment is what we want — that's matched by `expressionName: 'query'`,\n // which produces the esquery selector\n // `AssignmentExpression[left.property.name=\"query\"] > FunctionExpression[async]`.\n // `Auto` so both `connection.query(sql, cb)` and `connection.query(sql)`\n // (streamable, no callback) get channel events. The transform picks\n // `wrapCallback` when the last arg is a function and `wrapPromise`\n // otherwise — for mysql's no-callback path the latter publishes\n // `start`/`end` synchronously around the original call and stores the\n // returned `Query` emitter on `ctx.result`, which the integration uses to\n // attach `'end'`/`'error'` listeners that finish the span.\n functionQuery: { expressionName: 'query', kind: 'Auto' },\n },\n];\n\n/**\n * The unique set of package names instrumented by `SENTRY_INSTRUMENTATIONS`\n * (e.g. `['mysql']`).\n *\n * Bundler plugins MUST ensure these are actually bundled rather than\n * externalized: an externalized dependency is resolved from `node_modules` at\n * runtime and never passes through the code transform's `onLoad`, so its\n * diagnostics_channel calls are silently never injected.\n */\nexport const INSTRUMENTED_MODULE_NAMES: string[] = Array.from(new Set(SENTRY_INSTRUMENTATIONS.map(i => i.module.name)));\n\n/**\n * Returns `external` with any instrumented packages removed, so a bundler that\n * uses an \"external\" denylist (esbuild, Bun, Rollup) still bundles — and thus\n * transforms — them. Matches an exact package name (`'mysql'`) or a subpath\n * (`'mysql/lib/...'`); wildcard/other patterns are left untouched. `undefined`\n * is returned unchanged.\n *\n * (Vite uses an `ssr.noExternal` allowlist instead, so it consumes\n * `INSTRUMENTED_MODULE_NAMES` directly rather than this helper.)\n */\nexport function withoutInstrumentedExternals(external: readonly string[] | undefined): string[] | undefined {\n if (!external) {\n return undefined;\n }\n return external.filter(\n entry => !INSTRUMENTED_MODULE_NAMES.some(name => entry === name || entry.startsWith(`${name}/`)),\n );\n}\n"],"names":[],"mappings":"AAaO,MAAM,uBAAA,GAAmD;AAAA,EAC9D;AAAA,IACE,WAAA,EAAa,OAAA;AAAA,IACb,QAAQ,EAAE,IAAA,EAAM,SAAS,YAAA,EAAc,YAAA,EAAc,UAAU,mBAAA,EAAoB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAgBnF,aAAA,EAAe,EAAE,cAAA,EAAgB,OAAA,EAAS,MAAM,MAAA;AAAO;
|
|
1
|
+
{"version":3,"file":"config.js","sources":["../../../src/orchestrion/config.ts"],"sourcesContent":["import type { InstrumentationConfig } from '@apm-js-collab/code-transformer';\n\n/**\n * The central list of channel injections orchestrion should perform.\n *\n * This module has NO side effects — it's the only thing both the runtime hook\n * (`runtime/import-hook.mjs`) and the bundler plugins (`bundler/vite.ts`, …)\n * import from. Adding a new instrumented method is one entry here plus one\n * subscriber in `integrations/<lib>/tracing-channel.ts`.\n *\n * `channelName` here is the unprefixed suffix; the actual diagnostics_channel\n * name is `orchestrion:${module.name}:${channelName}` (see `channels.ts`).\n */\nexport const SENTRY_INSTRUMENTATIONS: InstrumentationConfig[] = [\n {\n channelName: 'query',\n module: { name: 'mysql', versionRange: '>=2.0.0 <3', filePath: 'lib/Connection.js' },\n // `Connection` in mysql v2 is a constructor function (NOT a class):\n // `function Connection(options) { ... }`\n // `Connection.prototype.query = function query(sql, values, cb) { ... }`\n // orchestrion's `className`+`methodName` query only matches `class` declarations.\n // The named function expression on the right-hand side of the prototype\n // assignment is what we want — that's matched by `expressionName: 'query'`,\n // which produces the esquery selector\n // `AssignmentExpression[left.property.name=\"query\"] > FunctionExpression[async]`.\n // `Auto` so both `connection.query(sql, cb)` and `connection.query(sql)`\n // (streamable, no callback) get channel events. The transform picks\n // `wrapCallback` when the last arg is a function and `wrapPromise`\n // otherwise — for mysql's no-callback path the latter publishes\n // `start`/`end` synchronously around the original call and stores the\n // returned `Query` emitter on `ctx.result`, which the integration uses to\n // attach `'end'`/`'error'` listeners that finish the span.\n functionQuery: { expressionName: 'query', kind: 'Auto' },\n },\n {\n channelName: 'load',\n // `>=2.1.0` only: the named `function memoizedFunction()` the selector targets exists from 2.1.0\n module: { name: 'lru-memoizer', versionRange: '>=2.1.0 <4', filePath: 'lib/async.js' },\n functionQuery: { functionName: 'memoizedFunction', kind: 'Callback' },\n },\n];\n\n/**\n * The unique set of package names instrumented by `SENTRY_INSTRUMENTATIONS`\n * (e.g. `['mysql']`).\n *\n * Bundler plugins MUST ensure these are actually bundled rather than\n * externalized: an externalized dependency is resolved from `node_modules` at\n * runtime and never passes through the code transform's `onLoad`, so its\n * diagnostics_channel calls are silently never injected.\n */\nexport const INSTRUMENTED_MODULE_NAMES: string[] = Array.from(new Set(SENTRY_INSTRUMENTATIONS.map(i => i.module.name)));\n\n/**\n * Returns `external` with any instrumented packages removed, so a bundler that\n * uses an \"external\" denylist (esbuild, Bun, Rollup) still bundles — and thus\n * transforms — them. Matches an exact package name (`'mysql'`) or a subpath\n * (`'mysql/lib/...'`); wildcard/other patterns are left untouched. `undefined`\n * is returned unchanged.\n *\n * (Vite uses an `ssr.noExternal` allowlist instead, so it consumes\n * `INSTRUMENTED_MODULE_NAMES` directly rather than this helper.)\n */\nexport function withoutInstrumentedExternals(external: readonly string[] | undefined): string[] | undefined {\n if (!external) {\n return undefined;\n }\n return external.filter(\n entry => !INSTRUMENTED_MODULE_NAMES.some(name => entry === name || entry.startsWith(`${name}/`)),\n );\n}\n"],"names":[],"mappings":"AAaO,MAAM,uBAAA,GAAmD;AAAA,EAC9D;AAAA,IACE,WAAA,EAAa,OAAA;AAAA,IACb,QAAQ,EAAE,IAAA,EAAM,SAAS,YAAA,EAAc,YAAA,EAAc,UAAU,mBAAA,EAAoB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAgBnF,aAAA,EAAe,EAAE,cAAA,EAAgB,OAAA,EAAS,MAAM,MAAA;AAAO,GACzD;AAAA,EACA;AAAA,IACE,WAAA,EAAa,MAAA;AAAA;AAAA,IAEb,QAAQ,EAAE,IAAA,EAAM,gBAAgB,YAAA,EAAc,YAAA,EAAc,UAAU,cAAA,EAAe;AAAA,IACrF,aAAA,EAAe,EAAE,YAAA,EAAc,kBAAA,EAAoB,MAAM,UAAA;AAAW;AAExE;AAWO,MAAM,yBAAA,GAAsC,KAAA,CAAM,IAAA,CAAK,IAAI,GAAA,CAAI,uBAAA,CAAwB,GAAA,CAAI,CAAA,CAAA,KAAK,CAAA,CAAE,MAAA,CAAO,IAAI,CAAC,CAAC;AAY/G,SAAS,6BAA6B,QAAA,EAA+D;AAC1G,EAAA,IAAI,CAAC,QAAA,EAAU;AACb,IAAA,OAAO,MAAA;AAAA,EACT;AACA,EAAA,OAAO,QAAA,CAAS,MAAA;AAAA,IACd,CAAA,KAAA,KAAS,CAAC,yBAAA,CAA0B,IAAA,CAAK,CAAA,IAAA,KAAQ,KAAA,KAAU,IAAA,IAAQ,KAAA,CAAM,UAAA,CAAW,CAAA,EAAG,IAAI,CAAA,CAAA,CAAG,CAAC;AAAA,GACjG;AACF;;;;"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
export { detectOrchestrionSetup } from './detect.js';
|
|
2
2
|
export { mysqlChannelIntegration } from '../integrations/tracing-channel/mysql.js';
|
|
3
|
+
export { lruMemoizerChannelIntegration } from '../integrations/tracing-channel/lru-memoizer.js';
|
|
3
4
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;"}
|
package/build/esm/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"type":"module","version":"10.
|
|
1
|
+
{"type":"module","version":"10.63.0","sideEffects":false}
|
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { getAsyncContextStrategy, getMainCarrier, debug, captureException, SPAN_STATUS_ERROR } from '@sentry/core';
|
|
2
2
|
import { DEBUG_BUILD } from './debug-build.js';
|
|
3
|
+
import { ERROR_TYPE } from '@sentry/conventions/attributes';
|
|
3
4
|
|
|
4
5
|
const NOOP = () => {
|
|
5
6
|
};
|
|
6
7
|
function bindTracingChannelToSpan(channel, getSpan, opts) {
|
|
7
8
|
const handle = bindSpanToChannelStore(channel, getSpan);
|
|
8
9
|
const beforeSpanEnd = opts?.beforeSpanEnd;
|
|
10
|
+
const deferSpanEnd = opts?.deferSpanEnd;
|
|
9
11
|
const getErrorHint = (e) => {
|
|
10
12
|
if (typeof opts?.captureError === "function") {
|
|
11
13
|
return opts.captureError(e);
|
|
@@ -17,11 +19,36 @@ function bindTracingChannelToSpan(channel, getSpan, opts) {
|
|
|
17
19
|
}
|
|
18
20
|
};
|
|
19
21
|
};
|
|
22
|
+
const annotateSpanError = (span, error) => {
|
|
23
|
+
if (opts?.captureError) {
|
|
24
|
+
captureException(error, getErrorHint(error));
|
|
25
|
+
}
|
|
26
|
+
const { message, attributes } = getErrorInfo(error);
|
|
27
|
+
span.setStatus({ code: SPAN_STATUS_ERROR, message });
|
|
28
|
+
span.setAttributes(attributes);
|
|
29
|
+
};
|
|
30
|
+
const makeDeferredEnd = (span, data) => {
|
|
31
|
+
let ended = false;
|
|
32
|
+
return (error) => {
|
|
33
|
+
if (ended) {
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
ended = true;
|
|
37
|
+
if (error !== void 0) {
|
|
38
|
+
annotateSpanError(span, error);
|
|
39
|
+
}
|
|
40
|
+
endBoundSpan(data, beforeSpanEnd);
|
|
41
|
+
};
|
|
42
|
+
};
|
|
20
43
|
const subscribers = {
|
|
21
44
|
start: NOOP,
|
|
22
45
|
asyncStart: NOOP,
|
|
23
46
|
end(data) {
|
|
24
47
|
if ("error" in data || "result" in data) {
|
|
48
|
+
const span = data._sentrySpan;
|
|
49
|
+
if (span && deferSpanEnd?.({ span, data, end: makeDeferredEnd(span, data) })) {
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
25
52
|
endBoundSpan(data, beforeSpanEnd);
|
|
26
53
|
}
|
|
27
54
|
},
|
|
@@ -30,12 +57,13 @@ function bindTracingChannelToSpan(channel, getSpan, opts) {
|
|
|
30
57
|
if (!span) {
|
|
31
58
|
return;
|
|
32
59
|
}
|
|
33
|
-
|
|
34
|
-
captureException(data.error, getErrorHint(data.error));
|
|
35
|
-
}
|
|
36
|
-
span.setStatus({ code: SPAN_STATUS_ERROR, message: getErrorMessage(data.error) });
|
|
60
|
+
annotateSpanError(span, data.error);
|
|
37
61
|
},
|
|
38
62
|
asyncEnd(data) {
|
|
63
|
+
const span = data._sentrySpan;
|
|
64
|
+
if (span && deferSpanEnd?.({ span, data, end: makeDeferredEnd(span, data) })) {
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
39
67
|
endBoundSpan(data, beforeSpanEnd);
|
|
40
68
|
}
|
|
41
69
|
};
|
|
@@ -49,7 +77,7 @@ function bindTracingChannelToSpan(channel, getSpan, opts) {
|
|
|
49
77
|
};
|
|
50
78
|
}
|
|
51
79
|
function bindSpanToChannelStore(channel, getSpan) {
|
|
52
|
-
const binding =
|
|
80
|
+
const binding = getAsyncContextStrategy(getMainCarrier()).getTracingChannelBinding?.();
|
|
53
81
|
if (!binding) {
|
|
54
82
|
DEBUG_BUILD && debug.log("[TracingChannel] Could not access async context binding.");
|
|
55
83
|
return {
|
|
@@ -59,17 +87,22 @@ function bindSpanToChannelStore(channel, getSpan) {
|
|
|
59
87
|
}
|
|
60
88
|
const asyncLocalStorage = binding.asyncLocalStorage;
|
|
61
89
|
channel.start.bindStore(asyncLocalStorage, (data) => {
|
|
90
|
+
data._sentryCallerStore = asyncLocalStorage.getStore();
|
|
62
91
|
const span = getSpan(data);
|
|
63
92
|
if (!span) {
|
|
64
|
-
return
|
|
93
|
+
return data._sentryCallerStore;
|
|
65
94
|
}
|
|
66
95
|
data._sentrySpan = span;
|
|
67
96
|
return binding.getStoreWithActiveSpan(span);
|
|
68
97
|
});
|
|
98
|
+
channel.asyncStart.bindStore(asyncLocalStorage, (data) => {
|
|
99
|
+
return data._sentryCallerStore;
|
|
100
|
+
});
|
|
69
101
|
return {
|
|
70
102
|
channel,
|
|
71
103
|
unbind: () => {
|
|
72
104
|
channel.start.unbindStore(asyncLocalStorage);
|
|
105
|
+
channel.asyncStart.unbindStore(asyncLocalStorage);
|
|
73
106
|
}
|
|
74
107
|
};
|
|
75
108
|
}
|
|
@@ -81,11 +114,17 @@ function endBoundSpan(data, beforeSpanEnd) {
|
|
|
81
114
|
beforeSpanEnd?.(span, data);
|
|
82
115
|
span.end();
|
|
83
116
|
}
|
|
84
|
-
function
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
117
|
+
function getErrorInfo(error) {
|
|
118
|
+
const isObject = !!error && typeof error === "object";
|
|
119
|
+
const raw = isObject ? "message" in error ? error.message : void 0 : error;
|
|
120
|
+
const message = raw ? String(raw) : "unknown_error";
|
|
121
|
+
const type = isObject && "name" in error ? String(error.name) : "unknown";
|
|
122
|
+
return {
|
|
123
|
+
message,
|
|
124
|
+
attributes: {
|
|
125
|
+
[ERROR_TYPE]: type
|
|
126
|
+
}
|
|
127
|
+
};
|
|
89
128
|
}
|
|
90
129
|
|
|
91
130
|
export { bindTracingChannelToSpan };
|
|
@@ -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 { _INTERNAL_getTracingChannelBinding, debug, captureException, SPAN_STATUS_ERROR } from '@sentry/core';\nimport { DEBUG_BUILD } from './debug-build';\n\nexport type TracingChannelPayloadWithSpan<TData extends object> = TData & {\n _sentrySpan?: Span;\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/** 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 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 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 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 if (opts?.captureError) {\n captureException(data.error, getErrorHint(data.error));\n }\n\n span.setStatus({ code: SPAN_STATUS_ERROR, message: getErrorMessage(data.error) });\n },\n asyncEnd(data) {\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 = _INTERNAL_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 const span = getSpan(data);\n if (!span) {\n // Leave the active context untouched so nested operations keep parenting to the enclosing span.\n return asyncLocalStorage.getStore() as TData;\n }\n data._sentrySpan = span;\n\n return binding.getStoreWithActiveSpan(span) as TData;\n });\n\n return {\n channel,\n unbind: () => {\n // Removes the store\n channel.start.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\n/** Best-effort short message for a span status: an error-like's `message`, otherwise its string form. */\nfunction getErrorMessage(error: unknown): string {\n if (error && typeof error === 'object' && 'message' in error && typeof error.message === 'string') {\n return error.message;\n }\n return String(error);\n}\n"],"names":[],"mappings":"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"}
|
|
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;\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 const message = raw ? String(raw) : 'unknown_error';\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,MAAA,gBAAA,CAAiB,KAAA,EAAO,YAAA,CAAa,KAAK,CAAC,CAAA;AAAA,IAC7C;AAEA,IAAA,MAAM,EAAE,OAAA,EAAS,UAAA,EAAW,GAAI,aAAa,KAAK,CAAA;AAClD,IAAA,IAAA,CAAK,SAAA,CAAU,EAAE,IAAA,EAAM,iBAAA,EAAmB,SAAS,CAAA;AACnD,IAAA,IAAA,CAAK,cAAc,UAAU,CAAA;AAAA,EAC/B,CAAA;AAGA,EAAA,MAAM,eAAA,GAAkB,CAAC,IAAA,EAAY,IAAA,KAA+C;AAClF,IAAA,IAAI,KAAA,GAAQ,KAAA;AAEZ,IAAA,OAAO,CAAC,KAAA,KAA0B;AAChC,MAAA,IAAI,KAAA,EAAO;AACT,QAAA;AAAA,MACF;AAEA,MAAA,KAAA,GAAQ,IAAA;AACR,MAAA,IAAI,UAAU,MAAA,EAAW;AACvB,QAAA,iBAAA,CAAkB,MAAM,KAAK,CAAA;AAAA,MAC/B;AAEA,MAAA,YAAA,CAAa,MAAM,aAAa,CAAA;AAAA,IAClC,CAAA;AAAA,EACF,CAAA;AAEA,EAAA,MAAM,WAAA,GAAwF;AAAA,IAC5F,KAAA,EAAO,IAAA;AAAA,IACP,UAAA,EAAY,IAAA;AAAA,IACZ,IAAI,IAAA,EAAM;AAGR,MAAA,IAAI,OAAA,IAAW,IAAA,IAAQ,QAAA,IAAY,IAAA,EAAM;AACvC,QAAA,MAAM,OAAO,IAAA,CAAK,WAAA;AAClB,QAAA,IAAI,IAAA,IAAQ,YAAA,GAAe,EAAE,IAAA,EAAM,IAAA,EAAM,GAAA,EAAK,eAAA,CAAgB,IAAA,EAAM,IAAI,CAAA,EAAG,CAAA,EAAG;AAC5E,UAAA;AAAA,QACF;AACA,QAAA,YAAA,CAAa,MAAM,aAAa,CAAA;AAAA,MAClC;AAAA,IACF,CAAA;AAAA,IACA,MAAM,IAAA,EAAM;AAGV,MAAA,MAAM,OAAO,IAAA,CAAK,WAAA;AAClB,MAAA,IAAI,CAAC,IAAA,EAAM;AACT,QAAA;AAAA,MACF;AAEA,MAAA,iBAAA,CAAkB,IAAA,EAAM,KAAK,KAAK,CAAA;AAAA,IACpC,CAAA;AAAA,IACA,SAAS,IAAA,EAAM;AACb,MAAA,MAAM,OAAO,IAAA,CAAK,WAAA;AAClB,MAAA,IAAI,IAAA,IAAQ,YAAA,GAAe,EAAE,IAAA,EAAM,IAAA,EAAM,GAAA,EAAK,eAAA,CAAgB,IAAA,EAAM,IAAI,CAAA,EAAG,CAAA,EAAG;AAC5E,QAAA;AAAA,MACF;AACA,MAAA,YAAA,CAAa,MAAM,aAAa,CAAA;AAAA,IAClC;AAAA,GACF;AAEA,EAAA,MAAA,CAAO,OAAA,CAAQ,UAAU,WAAW,CAAA;AAEpC,EAAA,OAAO;AAAA,IACL,SAAS,MAAA,CAAO,OAAA;AAAA,IAChB,QAAQ,MAAM;AACZ,MAAA,MAAA,CAAO,OAAA,CAAQ,YAAY,WAAW,CAAA;AACtC,MAAA,MAAA,CAAO,MAAA,EAAO;AAAA,IAChB;AAAA,GACF;AACF;AASA,SAAS,sBAAA,CACP,SACA,OAAA,EACoC;AAEpC,EAAA,MAAM,OAAA,GAAU,uBAAA,CAAwB,cAAA,EAAgB,EAAE,wBAAA,IAA2B;AAIrF,EAAA,IAAI,CAAC,OAAA,EAAS;AACZ,IAAA,WAAA,IAAe,KAAA,CAAM,IAAI,0DAA0D,CAAA;AAEnF,IAAA,OAAO;AAAA,MACL,OAAA;AAAA,MACA,MAAA,EAAQ;AAAA,KACV;AAAA,EACF;AAGA,EAAA,MAAM,oBAAoB,OAAA,CAAQ,iBAAA;AAOlC,EAAA,OAAA,CAAQ,KAAA,CAAM,SAAA,CAAU,iBAAA,EAAmB,CAAC,IAAA,KAA+C;AAGzF,IAAA,IAAA,CAAK,kBAAA,GAAqB,kBAAkB,QAAA,EAAS;AAErD,IAAA,MAAM,IAAA,GAAO,QAAQ,IAAI,CAAA;AACzB,IAAA,IAAI,CAAC,IAAA,EAAM;AAET,MAAA,OAAO,IAAA,CAAK,kBAAA;AAAA,IACd;AACA,IAAA,IAAA,CAAK,WAAA,GAAc,IAAA;AAEnB,IAAA,OAAO,OAAA,CAAQ,uBAAuB,IAAI,CAAA;AAAA,EAC5C,CAAC,CAAA;AAKD,EAAA,OAAA,CAAQ,UAAA,CAAW,SAAA,CAAU,iBAAA,EAAmB,CAAC,IAAA,KAA+C;AAC9F,IAAA,OAAO,IAAA,CAAK,kBAAA;AAAA,EACd,CAAC,CAAA;AAED,EAAA,OAAO;AAAA,IACL,OAAA;AAAA,IACA,QAAQ,MAAM;AAEZ,MAAA,OAAA,CAAQ,KAAA,CAAM,YAAY,iBAAiB,CAAA;AAC3C,MAAA,OAAA,CAAQ,UAAA,CAAW,YAAY,iBAAiB,CAAA;AAAA,IAClD;AAAA,GACF;AACF;AAEA,SAAS,YAAA,CACP,MACA,aAAA,EACM;AACN,EAAA,MAAM,OAAO,IAAA,CAAK,WAAA;AAClB,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,QAAA,GAAW,CAAC,CAAC,KAAA,IAAS,OAAO,KAAA,KAAU,QAAA;AAC7C,EAAA,MAAM,MAAM,QAAA,GAAY,SAAA,IAAa,KAAA,GAAQ,KAAA,CAAM,UAAU,MAAA,GAAa,KAAA;AAE1E,EAAA,MAAM,OAAA,GAAU,GAAA,GAAM,MAAA,CAAO,GAAG,CAAA,GAAI,eAAA;AACpC,EAAA,MAAM,OAAO,QAAA,IAAY,MAAA,IAAU,QAAQ,MAAA,CAAO,KAAA,CAAM,IAAI,CAAA,GAAI,SAAA;AAEhE,EAAA,OAAO;AAAA,IACL,OAAA;AAAA,IACA,UAAA,EAAY;AAAA,MACV,CAAC,UAAU,GAAG;AAAA;AAChB,GACF;AACF;;;;"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { defineIntegration, waitForTracingChannelBinding } from '@sentry/core';
|
|
2
|
+
import { subscribeVercelAiTracingChannel } from './vercel-ai-dc-subscriber.js';
|
|
3
|
+
import * as diagnosticsChannel from 'node:diagnostics_channel';
|
|
4
|
+
|
|
5
|
+
const _vercelAiIntegration = ((options = {}) => {
|
|
6
|
+
return {
|
|
7
|
+
name: "VercelAI",
|
|
8
|
+
setupOnce() {
|
|
9
|
+
if (!diagnosticsChannel.tracingChannel) {
|
|
10
|
+
return;
|
|
11
|
+
}
|
|
12
|
+
waitForTracingChannelBinding(() => {
|
|
13
|
+
subscribeVercelAiTracingChannel(diagnosticsChannel.tracingChannel, options);
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
});
|
|
18
|
+
const vercelAiIntegration = defineIntegration(_vercelAiIntegration);
|
|
19
|
+
|
|
20
|
+
export { vercelAiIntegration };
|
|
21
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../src/vercel-ai/index.ts"],"sourcesContent":["import { defineIntegration, waitForTracingChannelBinding, type IntegrationFn } from '@sentry/core';\nimport { subscribeVercelAiTracingChannel } from './vercel-ai-dc-subscriber';\nimport * as dc from 'node:diagnostics_channel';\n\ntype VercelAiOptions = {\n /**\n * Enable or disable input recording. Enabled if `dataCollection.genAI.inputs` (or the deprecated `sendDefaultPii` option) is `true`\n * or if you set `isEnabled` to `true` in your ai SDK method telemetry settings.\n * Integration-level options take precedence over global `dataCollection` config.\n */\n recordInputs?: boolean;\n\n /**\n * Enable or disable output recording. Enabled if `dataCollection.genAI.outputs` (or the deprecated `sendDefaultPii` option) is `true`\n * or if you set `isEnabled` to `true` in your ai SDK method telemetry settings.\n * Integration-level options take precedence over global `dataCollection` config.\n */\n recordOutputs?: boolean;\n\n /**\n * Enable or disable truncation of recorded input messages.\n * Defaults to `true`.\n */\n enableTruncation?: boolean;\n};\n\nconst _vercelAiIntegration = ((options: VercelAiOptions = {}) => {\n return {\n name: 'VercelAI' as const,\n setupOnce() {\n // Bail if this is not available\n if (!dc.tracingChannel) {\n return;\n }\n\n // Subscribe to the `ai` SDK's native telemetry tracing channel (ai >= 7).\n // This is a no-op on versions that don't publish to the channel, so it is always safe to call.\n waitForTracingChannelBinding(() => {\n subscribeVercelAiTracingChannel(dc.tracingChannel, options);\n });\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Auto-instrument the `ai` SDK's native telemetry tracing channel (ai >= 7).\n */\nexport const vercelAiIntegration = defineIntegration(_vercelAiIntegration);\n"],"names":["dc"],"mappings":";;;;AA0BA,MAAM,oBAAA,IAAwB,CAAC,OAAA,GAA2B,EAAC,KAAM;AAC/D,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,UAAA;AAAA,IACN,SAAA,GAAY;AAEV,MAAA,IAAI,CAACA,mBAAG,cAAA,EAAgB;AACtB,QAAA;AAAA,MACF;AAIA,MAAA,4BAAA,CAA6B,MAAM;AACjC,QAAA,+BAAA,CAAgCA,kBAAA,CAAG,gBAAgB,OAAO,CAAA;AAAA,MAC5D,CAAC,CAAA;AAAA,IACH;AAAA,GACF;AACF,CAAA,CAAA;AAKO,MAAM,mBAAA,GAAsB,kBAAkB,oBAAoB;;;;"}
|
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
import { GEN_AI_EMBEDDINGS_INPUT, GEN_AI_OPERATION_NAME, GEN_AI_FUNCTION_ID, GEN_AI_RESPONSE_STREAMING, GEN_AI_REQUEST_AVAILABLE_TOOLS, GEN_AI_TOOL_INPUT, GEN_AI_TOOL_NAME, GEN_AI_TOOL_TYPE, 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_INPUT_MESSAGES, GEN_AI_REQUEST_MODEL, GEN_AI_SYSTEM } from '@sentry/conventions/attributes';
|
|
2
|
+
import { GEN_AI_INVOKE_AGENT_SPAN_OP, GEN_AI_EXECUTE_TOOL_SPAN_OP } from '@sentry/conventions/op';
|
|
3
|
+
import { startInactiveSpan, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, getProviderMetadataAttributes, GEN_AI_CONVERSATION_ID_ATTRIBUTE, spanToJSON, SPAN_STATUS_ERROR, withScope, spanToTraceContext, captureException, getClient, shouldEnableTruncation, getTruncatedJsonString, GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE, GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE } from '@sentry/core';
|
|
4
|
+
import { bindTracingChannelToSpan } from '../tracing-channel.js';
|
|
5
|
+
|
|
6
|
+
const AI_SDK_TELEMETRY_TRACING_CHANNEL = "ai:telemetry";
|
|
7
|
+
const ORIGIN = "auto.vercelai.channel";
|
|
8
|
+
const GEN_AI_TOOL_CALL_ID_ATTRIBUTE = "gen_ai.tool.call.id";
|
|
9
|
+
const GEN_AI_TOOL_DESCRIPTION_ATTRIBUTE = "gen_ai.tool.description";
|
|
10
|
+
const GEN_AI_EMBEDDINGS_OPERATION = "embeddings";
|
|
11
|
+
const GEN_AI_RERANK_OPERATION = "rerank";
|
|
12
|
+
const GEN_AI_GENERATE_CONTENT_OPERATION = "generate_content";
|
|
13
|
+
const VERCEL_AI_OPERATION_ID_ATTRIBUTE = "vercel.ai.operationId";
|
|
14
|
+
const VERCEL_AI_MODEL_PROVIDER_ATTRIBUTE = "vercel.ai.model.provider";
|
|
15
|
+
const VERCEL_AI_SETTINGS_MAX_RETRIES_ATTRIBUTE = "vercel.ai.settings.maxRetries";
|
|
16
|
+
const operationIdByCallId = /* @__PURE__ */ new Map();
|
|
17
|
+
const toolDescriptionsByCallId = /* @__PURE__ */ new Map();
|
|
18
|
+
const ROOT_OPERATION_TYPES = /* @__PURE__ */ new Set(["generateText", "streamText", "embed", "rerank"]);
|
|
19
|
+
function clearOperationId(data) {
|
|
20
|
+
if (!ROOT_OPERATION_TYPES.has(data.type)) {
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
const callId = asString(data.event.callId);
|
|
24
|
+
if (callId) {
|
|
25
|
+
operationIdByCallId.delete(callId);
|
|
26
|
+
toolDescriptionsByCallId.delete(callId);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function recordToolDescriptions(callId, tools) {
|
|
30
|
+
if (!callId || !Array.isArray(tools)) {
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
let descriptions = toolDescriptionsByCallId.get(callId);
|
|
34
|
+
for (const tool of tools) {
|
|
35
|
+
if (isRecord(tool) && typeof tool.name === "string" && typeof tool.description === "string") {
|
|
36
|
+
descriptions = descriptions ?? /* @__PURE__ */ new Map();
|
|
37
|
+
if (!descriptions.has(tool.name)) {
|
|
38
|
+
descriptions.set(tool.name, tool.description);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
if (descriptions) {
|
|
43
|
+
toolDescriptionsByCallId.set(callId, descriptions);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
function resolveToolDescription(callId, toolName, tools) {
|
|
47
|
+
const fromMap = callId ? toolDescriptionsByCallId.get(callId)?.get(toolName) : void 0;
|
|
48
|
+
if (fromMap) {
|
|
49
|
+
return fromMap;
|
|
50
|
+
}
|
|
51
|
+
if (Array.isArray(tools)) {
|
|
52
|
+
const match = tools.find((tool) => isRecord(tool) && tool.name === toolName);
|
|
53
|
+
return isRecord(match) ? asString(match.description) : void 0;
|
|
54
|
+
}
|
|
55
|
+
if (isRecord(tools)) {
|
|
56
|
+
const tool = tools[toolName];
|
|
57
|
+
return isRecord(tool) ? asString(tool.description) : void 0;
|
|
58
|
+
}
|
|
59
|
+
return void 0;
|
|
60
|
+
}
|
|
61
|
+
let subscribed = false;
|
|
62
|
+
function subscribeVercelAiTracingChannel(tracingChannel, options = {}) {
|
|
63
|
+
if (subscribed) {
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
subscribed = true;
|
|
67
|
+
bindTracingChannelToSpan(
|
|
68
|
+
tracingChannel(AI_SDK_TELEMETRY_TRACING_CHANNEL),
|
|
69
|
+
(data) => createSpanFromMessage(data, options),
|
|
70
|
+
{
|
|
71
|
+
// The helper ends the span; we enrich it from the settled result first (tokens, output messages,
|
|
72
|
+
// finish reasons, response model/id, provider metadata) and drop the per-operation `callId` maps.
|
|
73
|
+
beforeSpanEnd: (span, data) => {
|
|
74
|
+
enrichSpanOnEnd(span, data, options);
|
|
75
|
+
clearOperationId(data);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
function createSpanFromMessage(data, channelOptions) {
|
|
81
|
+
const { type, event } = data;
|
|
82
|
+
if (type === "step" || !event || typeof event !== "object") {
|
|
83
|
+
return void 0;
|
|
84
|
+
}
|
|
85
|
+
const { recordInputs, enableTruncation } = getRecordingOptions(event, channelOptions);
|
|
86
|
+
const provider = asString(event.provider);
|
|
87
|
+
const modelId = asString(event.modelId);
|
|
88
|
+
const callId = asString(event.callId);
|
|
89
|
+
const maxRetries = asNumber(event.maxRetries);
|
|
90
|
+
if (recordInputs) {
|
|
91
|
+
recordToolDescriptions(callId, event.tools);
|
|
92
|
+
}
|
|
93
|
+
const baseAttributes = {
|
|
94
|
+
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: ORIGIN,
|
|
95
|
+
...provider ? { [GEN_AI_SYSTEM]: provider, [VERCEL_AI_MODEL_PROVIDER_ATTRIBUTE]: provider } : {},
|
|
96
|
+
...modelId ? { [GEN_AI_REQUEST_MODEL]: modelId } : {},
|
|
97
|
+
...maxRetries !== void 0 ? { [VERCEL_AI_SETTINGS_MAX_RETRIES_ATTRIBUTE]: maxRetries } : {}
|
|
98
|
+
};
|
|
99
|
+
switch (type) {
|
|
100
|
+
case "generateText":
|
|
101
|
+
case "streamText":
|
|
102
|
+
return buildInvokeAgentSpan(event, baseAttributes, recordInputs, enableTruncation, callId, type === "streamText");
|
|
103
|
+
case "languageModelCall":
|
|
104
|
+
return buildModelCallSpan(event, baseAttributes, recordInputs, enableTruncation, callId, modelId);
|
|
105
|
+
case "executeTool":
|
|
106
|
+
return buildToolSpan(event, recordInputs);
|
|
107
|
+
case "embed":
|
|
108
|
+
return startGenAiSpan(GEN_AI_EMBEDDINGS_OPERATION, modelId, {
|
|
109
|
+
...baseAttributes,
|
|
110
|
+
...recordInputs && event.value !== void 0 ? { [GEN_AI_EMBEDDINGS_INPUT]: safeStringify(event.value) } : {}
|
|
111
|
+
});
|
|
112
|
+
case "rerank":
|
|
113
|
+
return startGenAiSpan(GEN_AI_RERANK_OPERATION, modelId, baseAttributes);
|
|
114
|
+
default:
|
|
115
|
+
return void 0;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
function startGenAiSpan(operation, suffix, attributes) {
|
|
119
|
+
return startInactiveSpan({
|
|
120
|
+
name: suffix ? `${operation} ${suffix}` : operation,
|
|
121
|
+
op: `gen_ai.${operation}`,
|
|
122
|
+
attributes: { [GEN_AI_OPERATION_NAME]: operation, ...attributes }
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
function buildInvokeAgentSpan(event, baseAttributes, recordInputs, enableTruncation, callId, isStream) {
|
|
126
|
+
const functionId = asString(event.functionId);
|
|
127
|
+
const operationId = asString(event.operationId) ?? (isStream ? "ai.streamText" : "ai.generateText");
|
|
128
|
+
if (callId) {
|
|
129
|
+
operationIdByCallId.set(callId, { operationId, isStream });
|
|
130
|
+
}
|
|
131
|
+
return startGenAiSpan(GEN_AI_INVOKE_AGENT_SPAN_OP, functionId, {
|
|
132
|
+
...baseAttributes,
|
|
133
|
+
[VERCEL_AI_OPERATION_ID_ATTRIBUTE]: operationId,
|
|
134
|
+
[GEN_AI_RESPONSE_STREAMING]: isStream,
|
|
135
|
+
...functionId ? { [GEN_AI_FUNCTION_ID]: functionId } : {},
|
|
136
|
+
...recordInputs ? buildInputMessageAttributes(event, enableTruncation) : {}
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
function buildModelCallSpan(event, baseAttributes, recordInputs, enableTruncation, callId, modelId) {
|
|
140
|
+
const parent = callId ? operationIdByCallId.get(callId) : void 0;
|
|
141
|
+
const operationId = parent ? `${parent.operationId}.${parent.isStream ? "doStream" : "doGenerate"}` : "ai.generateText.doGenerate";
|
|
142
|
+
return startGenAiSpan(GEN_AI_GENERATE_CONTENT_OPERATION, modelId, {
|
|
143
|
+
...baseAttributes,
|
|
144
|
+
[VERCEL_AI_OPERATION_ID_ATTRIBUTE]: operationId,
|
|
145
|
+
...recordInputs ? buildInputMessageAttributes(event, enableTruncation) : {},
|
|
146
|
+
...recordInputs && Array.isArray(event.tools) ? { [GEN_AI_REQUEST_AVAILABLE_TOOLS]: safeStringify(event.tools) } : {}
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
function buildToolSpan(event, recordInputs) {
|
|
150
|
+
const toolCall = isRecord(event.toolCall) ? event.toolCall : {};
|
|
151
|
+
const toolName = asString(toolCall.toolName);
|
|
152
|
+
const toolCallId = asString(event.toolCallId) ?? asString(toolCall.toolCallId);
|
|
153
|
+
const toolInput = toolCall.input ?? toolCall.args;
|
|
154
|
+
const description = recordInputs && toolName ? resolveToolDescription(asString(event.callId), toolName, event.tools) : void 0;
|
|
155
|
+
return startGenAiSpan(GEN_AI_EXECUTE_TOOL_SPAN_OP, toolName, {
|
|
156
|
+
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: ORIGIN,
|
|
157
|
+
[GEN_AI_TOOL_TYPE]: "function",
|
|
158
|
+
...toolName ? { [GEN_AI_TOOL_NAME]: toolName } : {},
|
|
159
|
+
...toolCallId ? { [GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: toolCallId } : {},
|
|
160
|
+
...description ? { [GEN_AI_TOOL_DESCRIPTION_ATTRIBUTE]: description } : {},
|
|
161
|
+
...recordInputs && toolInput !== void 0 ? { [GEN_AI_TOOL_INPUT]: safeStringify(toolInput) } : {}
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
function enrichSpanOnEnd(span, data, channelOptions) {
|
|
165
|
+
const { type, result } = data;
|
|
166
|
+
if (!isRecord(result)) {
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
const { recordOutputs } = getRecordingOptions(data.event, channelOptions);
|
|
170
|
+
if (type === "executeTool") {
|
|
171
|
+
if (recordOutputs) {
|
|
172
|
+
span.setAttribute(GEN_AI_TOOL_OUTPUT, safeStringify(result.output ?? result));
|
|
173
|
+
}
|
|
174
|
+
const output = isRecord(result.output) ? result.output : void 0;
|
|
175
|
+
if (output?.type === "tool-error") {
|
|
176
|
+
captureToolError(span, data, output.error);
|
|
177
|
+
}
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
const usage = isRecord(result.usage) ? result.usage : void 0;
|
|
181
|
+
if (usage) {
|
|
182
|
+
const inputTokens = tokenCount(usage.inputTokens) ?? tokenCount(usage.tokens);
|
|
183
|
+
const outputTokens = tokenCount(usage.outputTokens);
|
|
184
|
+
const totalTokens = tokenCount(usage.totalTokens) ?? sum(inputTokens, outputTokens);
|
|
185
|
+
if (inputTokens !== void 0) {
|
|
186
|
+
span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, inputTokens);
|
|
187
|
+
}
|
|
188
|
+
if (outputTokens !== void 0) {
|
|
189
|
+
span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, outputTokens);
|
|
190
|
+
}
|
|
191
|
+
if (totalTokens !== void 0) {
|
|
192
|
+
span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, totalTokens);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
const finishReason = getFinishReason(result);
|
|
196
|
+
if (finishReason && type === "languageModelCall") {
|
|
197
|
+
span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, safeStringify([finishReason]));
|
|
198
|
+
}
|
|
199
|
+
const response = isRecord(result.response) ? result.response : void 0;
|
|
200
|
+
const responseId = asString(response?.id) ?? asString(result.responseId);
|
|
201
|
+
if (responseId) {
|
|
202
|
+
span.setAttribute(GEN_AI_RESPONSE_ID, responseId);
|
|
203
|
+
}
|
|
204
|
+
const responseModel = asString(response?.modelId) ?? asString(data.event.modelId);
|
|
205
|
+
if (responseModel) {
|
|
206
|
+
span.setAttribute(GEN_AI_RESPONSE_MODEL, responseModel);
|
|
207
|
+
}
|
|
208
|
+
const providerMetadata = result.providerMetadata;
|
|
209
|
+
const providerAttributes = getProviderMetadataAttributes(providerMetadata);
|
|
210
|
+
if (GEN_AI_CONVERSATION_ID_ATTRIBUTE in providerAttributes && spanToJSON(span).data[GEN_AI_CONVERSATION_ID_ATTRIBUTE]) {
|
|
211
|
+
delete providerAttributes[GEN_AI_CONVERSATION_ID_ATTRIBUTE];
|
|
212
|
+
}
|
|
213
|
+
span.setAttributes(providerAttributes);
|
|
214
|
+
if (recordOutputs) {
|
|
215
|
+
const parts = type === "languageModelCall" && Array.isArray(result.content) ? partsFromContent(result.content) : partsFromTextAndToolCalls(result.text, result.toolCalls);
|
|
216
|
+
const outputMessages = buildOutputMessages(parts, finishReason);
|
|
217
|
+
if (outputMessages) {
|
|
218
|
+
span.setAttribute(GEN_AI_OUTPUT_MESSAGES, outputMessages);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
function normalizeFinishReason(finishReason) {
|
|
223
|
+
return finishReason === "tool-calls" ? "tool_call" : finishReason ?? "stop";
|
|
224
|
+
}
|
|
225
|
+
function getFinishReason(result) {
|
|
226
|
+
const finishReason = result.finishReason;
|
|
227
|
+
if (typeof finishReason === "string") {
|
|
228
|
+
return finishReason;
|
|
229
|
+
}
|
|
230
|
+
return isRecord(finishReason) ? asString(finishReason.unified) : void 0;
|
|
231
|
+
}
|
|
232
|
+
function tokenCount(value) {
|
|
233
|
+
return asNumber(value) ?? (isRecord(value) ? asNumber(value.total) : void 0);
|
|
234
|
+
}
|
|
235
|
+
function buildOutputMessages(parts, finishReason) {
|
|
236
|
+
if (!parts.length) {
|
|
237
|
+
return void 0;
|
|
238
|
+
}
|
|
239
|
+
return safeStringify([{ role: "assistant", parts, finish_reason: normalizeFinishReason(finishReason) }]);
|
|
240
|
+
}
|
|
241
|
+
function toolCallPart(toolCall) {
|
|
242
|
+
const args = toolCall.input ?? toolCall.args;
|
|
243
|
+
return {
|
|
244
|
+
type: "tool_call",
|
|
245
|
+
id: asString(toolCall.toolCallId),
|
|
246
|
+
name: asString(toolCall.toolName),
|
|
247
|
+
arguments: typeof args === "string" ? args : safeStringify(args ?? {})
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
function partsFromContent(content) {
|
|
251
|
+
const parts = [];
|
|
252
|
+
for (const item of content) {
|
|
253
|
+
if (!isRecord(item)) {
|
|
254
|
+
continue;
|
|
255
|
+
}
|
|
256
|
+
if (item.type === "text" && typeof item.text === "string") {
|
|
257
|
+
parts.push({ type: "text", content: item.text });
|
|
258
|
+
} else if (item.type === "tool-call") {
|
|
259
|
+
parts.push(toolCallPart(item));
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
return parts;
|
|
263
|
+
}
|
|
264
|
+
function partsFromTextAndToolCalls(text, toolCalls) {
|
|
265
|
+
const parts = [];
|
|
266
|
+
if (typeof text === "string" && text.length) {
|
|
267
|
+
parts.push({ type: "text", content: text });
|
|
268
|
+
}
|
|
269
|
+
if (Array.isArray(toolCalls)) {
|
|
270
|
+
for (const toolCall of toolCalls) {
|
|
271
|
+
if (isRecord(toolCall)) {
|
|
272
|
+
parts.push(toolCallPart(toolCall));
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
return parts;
|
|
277
|
+
}
|
|
278
|
+
function captureToolError(span, data, error) {
|
|
279
|
+
span.setStatus({
|
|
280
|
+
code: SPAN_STATUS_ERROR,
|
|
281
|
+
message: error instanceof Error ? error.message : "tool_error"
|
|
282
|
+
});
|
|
283
|
+
const toolCall = isRecord(data.event.toolCall) ? data.event.toolCall : {};
|
|
284
|
+
const toolName = asString(toolCall.toolName);
|
|
285
|
+
const toolCallId = asString(data.event.toolCallId) ?? asString(toolCall.toolCallId);
|
|
286
|
+
withScope((scope) => {
|
|
287
|
+
scope.setContext("trace", spanToTraceContext(span));
|
|
288
|
+
if (toolName) {
|
|
289
|
+
scope.setTag("vercel.ai.tool.name", toolName);
|
|
290
|
+
}
|
|
291
|
+
if (toolCallId) {
|
|
292
|
+
scope.setTag("vercel.ai.tool.callId", toolCallId);
|
|
293
|
+
}
|
|
294
|
+
scope.setLevel("error");
|
|
295
|
+
captureException(
|
|
296
|
+
error instanceof Error ? error : new Error(typeof error === "string" ? error : "Tool execution failed"),
|
|
297
|
+
{
|
|
298
|
+
mechanism: { type: "auto.vercelai.channel", handled: false }
|
|
299
|
+
}
|
|
300
|
+
);
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
function getRecordingOptions(event, channelOptions) {
|
|
304
|
+
const genAI = getClient()?.getDataCollectionOptions().genAI;
|
|
305
|
+
return {
|
|
306
|
+
recordInputs: resolveRecording(channelOptions.recordInputs, event.recordInputs, genAI?.inputs),
|
|
307
|
+
recordOutputs: resolveRecording(channelOptions.recordOutputs, event.recordOutputs, genAI?.outputs),
|
|
308
|
+
enableTruncation: shouldEnableTruncation(channelOptions.enableTruncation)
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
function resolveRecording(integrationOption, perCallOption, globalDefault) {
|
|
312
|
+
if (typeof integrationOption === "boolean") {
|
|
313
|
+
return integrationOption;
|
|
314
|
+
}
|
|
315
|
+
if (typeof perCallOption === "boolean") {
|
|
316
|
+
return perCallOption;
|
|
317
|
+
}
|
|
318
|
+
return globalDefault === true;
|
|
319
|
+
}
|
|
320
|
+
function buildInputMessageAttributes(event, enableTruncation) {
|
|
321
|
+
const attributes = {};
|
|
322
|
+
const instructions = asString(event.instructions);
|
|
323
|
+
if (instructions) {
|
|
324
|
+
attributes[GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE] = safeStringify([{ type: "text", content: instructions }]);
|
|
325
|
+
}
|
|
326
|
+
const messages = event.messages ?? event.prompt;
|
|
327
|
+
if (messages !== void 0) {
|
|
328
|
+
attributes[GEN_AI_INPUT_MESSAGES] = enableTruncation ? getTruncatedJsonString(messages) : safeStringify(messages);
|
|
329
|
+
attributes[GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE] = Array.isArray(messages) ? messages.length : 1;
|
|
330
|
+
}
|
|
331
|
+
return attributes;
|
|
332
|
+
}
|
|
333
|
+
function asString(value) {
|
|
334
|
+
return typeof value === "string" ? value : void 0;
|
|
335
|
+
}
|
|
336
|
+
function asNumber(value) {
|
|
337
|
+
return typeof value === "number" && !isNaN(value) ? value : void 0;
|
|
338
|
+
}
|
|
339
|
+
function sum(a, b) {
|
|
340
|
+
return a === void 0 && b === void 0 ? void 0 : (a ?? 0) + (b ?? 0);
|
|
341
|
+
}
|
|
342
|
+
function isRecord(value) {
|
|
343
|
+
return typeof value === "object" && value !== null;
|
|
344
|
+
}
|
|
345
|
+
function safeStringify(value) {
|
|
346
|
+
if (typeof value === "string") {
|
|
347
|
+
return value;
|
|
348
|
+
}
|
|
349
|
+
try {
|
|
350
|
+
return JSON.stringify(value);
|
|
351
|
+
} catch {
|
|
352
|
+
return "[unserializable]";
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
export { clearOperationId, createSpanFromMessage, enrichSpanOnEnd, subscribeVercelAiTracingChannel };
|
|
357
|
+
//# sourceMappingURL=vercel-ai-dc-subscriber.js.map
|