braintrust 3.24.0 → 3.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dev/dist/index.d.mts +5 -0
  2. package/dev/dist/index.d.ts +5 -0
  3. package/dev/dist/index.js +2614 -1567
  4. package/dev/dist/index.mjs +2037 -990
  5. package/dist/apply-auto-instrumentation.js +200 -199
  6. package/dist/apply-auto-instrumentation.mjs +8 -7
  7. package/dist/auto-instrumentations/bundler/esbuild.cjs +596 -462
  8. package/dist/auto-instrumentations/bundler/esbuild.mjs +2 -2
  9. package/dist/auto-instrumentations/bundler/next.cjs +596 -462
  10. package/dist/auto-instrumentations/bundler/next.mjs +3 -3
  11. package/dist/auto-instrumentations/bundler/rollup.cjs +596 -462
  12. package/dist/auto-instrumentations/bundler/rollup.mjs +2 -2
  13. package/dist/auto-instrumentations/bundler/vite.cjs +596 -462
  14. package/dist/auto-instrumentations/bundler/vite.mjs +2 -2
  15. package/dist/auto-instrumentations/bundler/webpack-loader.cjs +596 -462
  16. package/dist/auto-instrumentations/bundler/webpack.cjs +596 -462
  17. package/dist/auto-instrumentations/bundler/webpack.mjs +3 -3
  18. package/dist/auto-instrumentations/{chunk-BURMPO7L.mjs → chunk-7P6563SW.mjs} +1 -1
  19. package/dist/auto-instrumentations/{chunk-F43DNLPD.mjs → chunk-CZ24KNHT.mjs} +569 -442
  20. package/dist/auto-instrumentations/{chunk-GSZHTAQW.mjs → chunk-JPVCUKTY.mjs} +30 -21
  21. package/dist/auto-instrumentations/hook.mjs +648 -476
  22. package/dist/auto-instrumentations/index.cjs +568 -442
  23. package/dist/auto-instrumentations/index.mjs +1 -1
  24. package/dist/browser.d.mts +7 -0
  25. package/dist/browser.d.ts +7 -0
  26. package/dist/browser.js +2022 -971
  27. package/dist/browser.mjs +2022 -971
  28. package/dist/{chunk-XE5FS7QY.mjs → chunk-2SANLSWX.mjs} +1375 -597
  29. package/dist/{chunk-7F6GCRHH.mjs → chunk-ABR2QWDP.mjs} +702 -456
  30. package/dist/{chunk-SU6EHKJV.js → chunk-GSIDVFE6.js} +2176 -1398
  31. package/dist/{chunk-7AUY2XWX.js → chunk-P25IOOU4.js} +704 -458
  32. package/dist/cli.js +2005 -958
  33. package/dist/edge-light.js +2022 -971
  34. package/dist/edge-light.mjs +2022 -971
  35. package/dist/index.d.mts +7 -0
  36. package/dist/index.d.ts +7 -0
  37. package/dist/index.js +447 -402
  38. package/dist/index.mjs +72 -27
  39. package/dist/instrumentation/index.d.mts +5 -0
  40. package/dist/instrumentation/index.d.ts +5 -0
  41. package/dist/instrumentation/index.js +1990 -981
  42. package/dist/instrumentation/index.mjs +1990 -981
  43. package/dist/vitest-evals-reporter.js +16 -16
  44. package/dist/vitest-evals-reporter.mjs +2 -2
  45. package/dist/workerd.js +2022 -971
  46. package/dist/workerd.mjs +2022 -971
  47. package/package.json +2 -2
@@ -5019,7 +5019,51 @@ var SpanCache = class {
5019
5019
  };
5020
5020
 
5021
5021
  // src/span-origin.ts
5022
- var SDK_VERSION = true ? "3.24.0" : "0.0.0";
5022
+ var INSTRUMENTATION_NAMES = {
5023
+ AI_SDK: "ai-sdk",
5024
+ ANTHROPIC: "anthropic",
5025
+ BEDROCK_RUNTIME: "bedrock-runtime",
5026
+ BRAINTRUST_JS_LOGGER: "braintrust-js-logger",
5027
+ CLAUDE_AGENT_SDK: "claude-agent-sdk",
5028
+ COHERE: "cohere",
5029
+ CURSOR_SDK: "cursor-sdk",
5030
+ EVE: "eve",
5031
+ FLUE: "flue",
5032
+ GENKIT: "genkit",
5033
+ GITHUB_COPILOT: "github-copilot",
5034
+ GOOGLE_ADK: "google-adk",
5035
+ GOOGLE_GENAI: "google-genai",
5036
+ GROQ: "groq",
5037
+ HUGGINGFACE: "huggingface",
5038
+ LANGCHAIN: "langchain",
5039
+ LANGSMITH: "langsmith",
5040
+ MASTRA: "mastra",
5041
+ MISTRAL: "mistral",
5042
+ OPENAI: "openai",
5043
+ OPENAI_AGENTS: "openai-agents",
5044
+ OPENAI_CODEX: "openai-codex",
5045
+ OPENROUTER: "openrouter",
5046
+ OPENROUTER_AGENT: "openrouter-agent",
5047
+ PI_CODING_AGENT: "pi-coding-agent",
5048
+ STRANDS_AGENT_SDK: "strands-agent-sdk"
5049
+ };
5050
+ var INTERNAL_SPAN_INSTRUMENTATION_NAME = /* @__PURE__ */ Symbol.for(
5051
+ "braintrust.spanInstrumentationName"
5052
+ );
5053
+ var SDK_VERSION = true ? "3.25.0" : "0.0.0";
5054
+ function withSpanInstrumentationName(args, instrumentationName) {
5055
+ return {
5056
+ ...args,
5057
+ [INTERNAL_SPAN_INSTRUMENTATION_NAME]: instrumentationName
5058
+ };
5059
+ }
5060
+ function getSpanInstrumentationName(args) {
5061
+ if (typeof args !== "object" || args === null) {
5062
+ return void 0;
5063
+ }
5064
+ const value = args[INTERNAL_SPAN_INSTRUMENTATION_NAME];
5065
+ return isSpanInstrumentationName(value) ? value : void 0;
5066
+ }
5023
5067
  function detectSpanOriginEnvironment(explicit) {
5024
5068
  if (explicit) return explicit;
5025
5069
  const envType = isomorph_default.getEnv("BRAINTRUST_ENVIRONMENT_TYPE");
@@ -5091,6 +5135,9 @@ function mergeSpanOriginContext(context, instrumentationName, environment) {
5091
5135
  };
5092
5136
  return next;
5093
5137
  }
5138
+ function isSpanInstrumentationName(value) {
5139
+ return Object.values(INSTRUMENTATION_NAMES).some((name) => name === value);
5140
+ }
5094
5141
  function firstPresent(entries) {
5095
5142
  return entries.find(([key]) => Boolean(isomorph_default.getEnv(key)))?.[1];
5096
5143
  }
@@ -5385,6 +5432,7 @@ var BraintrustState = class _BraintrustState {
5385
5432
  });
5386
5433
  this.spanCache = new SpanCache({ disabled: loginParams.disableSpanCache });
5387
5434
  this.spanOriginEnvironment = detectSpanOriginEnvironment();
5435
+ this._internalSetTraceContextSigningSecret(loginParams.apiKey);
5388
5436
  }
5389
5437
  loginParams;
5390
5438
  id;
@@ -5422,6 +5470,18 @@ var BraintrustState = class _BraintrustState {
5422
5470
  _contextManager = null;
5423
5471
  _otelFlushCallback = null;
5424
5472
  spanOriginEnvironment;
5473
+ traceContextSigningSecret;
5474
+ /** @internal */
5475
+ _internalSetTraceContextSigningSecret(secret) {
5476
+ const normalizedSecret = secret?.trim();
5477
+ if (normalizedSecret) {
5478
+ this.traceContextSigningSecret = normalizedSecret;
5479
+ }
5480
+ }
5481
+ /** @internal */
5482
+ _internalGetTraceContextSigningSecret() {
5483
+ return (this.traceContextSigningSecret ?? this.loginToken ?? isomorph_default.getEnv("BRAINTRUST_API_KEY"))?.trim();
5484
+ }
5425
5485
  resetLoginInfo() {
5426
5486
  this.appUrl = null;
5427
5487
  this.appPublicUrl = null;
@@ -5482,6 +5542,7 @@ var BraintrustState = class _BraintrustState {
5482
5542
  this.gitMetadataSettings = other.gitMetadataSettings;
5483
5543
  this.debugLogLevel = other.debugLogLevel;
5484
5544
  this.debugLogLevelConfigured = other.debugLogLevelConfigured;
5545
+ this.traceContextSigningSecret = other.traceContextSigningSecret;
5485
5546
  setGlobalDebugLogLevel(
5486
5547
  this.debugLogLevelConfigured ? this.debugLogLevel ?? false : void 0
5487
5548
  );
@@ -5569,6 +5630,7 @@ var BraintrustState = class _BraintrustState {
5569
5630
  return this.debugLogLevelConfigured;
5570
5631
  }
5571
5632
  async login(loginParams) {
5633
+ this._internalSetTraceContextSigningSecret(loginParams.apiKey);
5572
5634
  this.setDebugLogLevel(loginParams.debugLogLevel);
5573
5635
  if (this.apiUrl && !loginParams.forceLogin) {
5574
5636
  return;
@@ -7548,6 +7610,7 @@ function init(projectOrOptions, optionalOptions) {
7548
7610
  throw new Error("Cannot open and update an experiment at the same time");
7549
7611
  }
7550
7612
  const state = stateArg ?? _globalState;
7613
+ state._internalSetTraceContextSigningSecret(apiKey);
7551
7614
  state.enforceQueueSizeLimit(false);
7552
7615
  if (open) {
7553
7616
  if (isEmpty2(experiment)) {
@@ -8056,6 +8119,7 @@ function initLogger(options = {}) {
8056
8119
  project_id: projectId
8057
8120
  };
8058
8121
  const state = stateArg ?? _globalState;
8122
+ state._internalSetTraceContextSigningSecret(apiKey);
8059
8123
  state.setDebugLogLevel(debugLogLevel);
8060
8124
  state.spanOriginEnvironment = detectSpanOriginEnvironment(environment);
8061
8125
  state.enforceQueueSizeLimit(true);
@@ -9119,7 +9183,9 @@ function deepCopyEvent(event) {
9119
9183
  const ATTACHMENT_MARKER_KEY = "_bt_internal_saved_attachment_marker";
9120
9184
  const attachmentMarker = ++deepCopyEventMarkerCounter;
9121
9185
  const serialized = JSON.stringify(event, (_k, v) => {
9122
- if (v instanceof SpanImpl || v instanceof NoopSpan) {
9186
+ if (v instanceof Error) {
9187
+ return v.message;
9188
+ } else if (v instanceof SpanImpl || v instanceof NoopSpan) {
9123
9189
  return `<span>`;
9124
9190
  } else if (v instanceof Experiment2) {
9125
9191
  return `<experiment>`;
@@ -9787,6 +9853,7 @@ var SpanImpl = class _SpanImpl {
9787
9853
  constructor(args) {
9788
9854
  this._state = args.state;
9789
9855
  this._propagatedState = args.propagatedState;
9856
+ const instrumentationName = getSpanInstrumentationName(args) ?? INSTRUMENTATION_NAMES.BRAINTRUST_JS_LOGGER;
9790
9857
  const spanAttributes = args.spanAttributes ?? {};
9791
9858
  const rawEvent = args.event ?? {};
9792
9859
  const type = args.type ?? (args.parentSpanIds ? void 0 : args.defaultRootType);
@@ -9818,7 +9885,7 @@ var SpanImpl = class _SpanImpl {
9818
9885
  },
9819
9886
  context: mergeSpanOriginContext(
9820
9887
  { ...callerLocation },
9821
- "braintrust-js-logger",
9888
+ instrumentationName,
9822
9889
  this._state.spanOriginEnvironment
9823
9890
  ),
9824
9891
  span_attributes: {
@@ -11925,15 +11992,25 @@ function hasChoices(value) {
11925
11992
  function normalizeMetadata(metadata) {
11926
11993
  return isObject(metadata) ? metadata : void 0;
11927
11994
  }
11928
- function startSpanForEvent(config, event, channelName) {
11995
+ function startSpanForEvent(config, event, channelName, instrumentationName) {
11929
11996
  const { name, spanAttributes, spanInfoMetadata } = buildStartSpanArgs(
11930
11997
  config,
11931
11998
  event
11932
11999
  );
11933
- const span = startSpan({
11934
- name,
11935
- spanAttributes
11936
- });
12000
+ const spanArgs = withSpanInstrumentationName(
12001
+ {
12002
+ name,
12003
+ spanAttributes
12004
+ },
12005
+ instrumentationName
12006
+ );
12007
+ let span;
12008
+ try {
12009
+ span = config.startSpan?.(spanArgs) ?? startSpan(spanArgs);
12010
+ } catch (error) {
12011
+ debugLogger.error(`Error starting span for ${channelName}:`, error);
12012
+ span = startSpan(spanArgs);
12013
+ }
11937
12014
  const startTime = getCurrentUnixTimestamp();
11938
12015
  try {
11939
12016
  const { input, metadata } = config.extractInput(
@@ -11964,7 +12041,7 @@ function shouldTraceEvent(config, event, channelName) {
11964
12041
  return true;
11965
12042
  }
11966
12043
  }
11967
- function ensureSpanStateForEvent(states, config, event, channelName) {
12044
+ function ensureSpanStateForEvent(states, config, event, channelName, instrumentationName) {
11968
12045
  const key = event;
11969
12046
  const existing = states.get(key);
11970
12047
  if (existing) {
@@ -11973,11 +12050,16 @@ function ensureSpanStateForEvent(states, config, event, channelName) {
11973
12050
  if (!shouldTraceEvent(config, event, channelName)) {
11974
12051
  return void 0;
11975
12052
  }
11976
- const created = startSpanForEvent(config, event, channelName);
12053
+ const created = startSpanForEvent(
12054
+ config,
12055
+ event,
12056
+ channelName,
12057
+ instrumentationName
12058
+ );
11977
12059
  states.set(key, created);
11978
12060
  return created;
11979
12061
  }
11980
- function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelName) {
12062
+ function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelName, instrumentationName) {
11981
12063
  const state = _internalGetGlobalState();
11982
12064
  const startChannel = tracingChannel2.start;
11983
12065
  const contextManager = state?.contextManager;
@@ -11995,7 +12077,8 @@ function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelNam
11995
12077
  states,
11996
12078
  config,
11997
12079
  event,
11998
- channelName
12080
+ channelName,
12081
+ instrumentationName
11999
12082
  );
12000
12083
  return spanState ? contextManager.wrapSpanForStore(spanState.span) : currentSpanStore.getStore();
12001
12084
  }
@@ -12004,15 +12087,21 @@ function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelNam
12004
12087
  startChannel.unbindStore(currentSpanStore);
12005
12088
  };
12006
12089
  }
12007
- function logErrorAndEnd(states, event) {
12090
+ function logErrorAndEnd(states, event, channelName) {
12008
12091
  const spanData = states.get(event);
12009
12092
  if (!spanData) {
12010
12093
  return;
12011
12094
  }
12012
- spanData.span.log({
12013
- error: event.error.message
12014
- });
12015
- spanData.span.end();
12095
+ try {
12096
+ spanData.span.log({ error: event.error });
12097
+ } catch (error) {
12098
+ debugLogger.error(`Error logging failure for ${channelName}:`, error);
12099
+ }
12100
+ try {
12101
+ spanData.span.end();
12102
+ } catch (error) {
12103
+ debugLogger.error(`Error ending span for ${channelName}:`, error);
12104
+ }
12016
12105
  states.delete(event);
12017
12106
  }
12018
12107
  function runStreamingCompletionHook(args) {
@@ -12062,7 +12151,8 @@ function traceAsyncChannel(channel2, config) {
12062
12151
  tracingChannel2,
12063
12152
  states,
12064
12153
  config,
12065
- channelName
12154
+ channelName,
12155
+ channel2.instrumentationName
12066
12156
  );
12067
12157
  const handlers = {
12068
12158
  start: (event) => {
@@ -12073,7 +12163,8 @@ function traceAsyncChannel(channel2, config) {
12073
12163
  states,
12074
12164
  config,
12075
12165
  event,
12076
- channelName
12166
+ channelName,
12167
+ channel2.instrumentationName
12077
12168
  );
12078
12169
  },
12079
12170
  asyncEnd: (event) => {
@@ -12110,7 +12201,7 @@ function traceAsyncChannel(channel2, config) {
12110
12201
  }
12111
12202
  },
12112
12203
  error: (event) => {
12113
- logErrorAndEnd(states, event);
12204
+ logErrorAndEnd(states, event, channelName);
12114
12205
  }
12115
12206
  };
12116
12207
  tracingChannel2.subscribe(handlers);
@@ -12127,7 +12218,8 @@ function traceStreamingChannel(channel2, config) {
12127
12218
  tracingChannel2,
12128
12219
  states,
12129
12220
  config,
12130
- channelName
12221
+ channelName,
12222
+ channel2.instrumentationName
12131
12223
  );
12132
12224
  const handlers = {
12133
12225
  start: (event) => {
@@ -12138,7 +12230,8 @@ function traceStreamingChannel(channel2, config) {
12138
12230
  states,
12139
12231
  config,
12140
12232
  event,
12141
- channelName
12233
+ channelName,
12234
+ channel2.instrumentationName
12142
12235
  );
12143
12236
  },
12144
12237
  asyncEnd: (event) => {
@@ -12157,6 +12250,7 @@ function traceStreamingChannel(channel2, config) {
12157
12250
  }
12158
12251
  },
12159
12252
  onComplete: (chunks) => {
12253
+ let completion2;
12160
12254
  try {
12161
12255
  let output;
12162
12256
  let metrics;
@@ -12187,18 +12281,11 @@ function traceStreamingChannel(channel2, config) {
12187
12281
  } else if (metrics.time_to_first_token === void 0 && chunks.length > 0) {
12188
12282
  metrics.time_to_first_token = getCurrentUnixTimestamp() - startTime;
12189
12283
  }
12190
- runStreamingCompletionHook({
12191
- channelName,
12192
- chunks,
12193
- config,
12194
- endEvent: asyncEndEvent,
12284
+ completion2 = {
12195
12285
  ...metadata !== void 0 ? { metadata } : {},
12196
12286
  metrics,
12197
- output,
12198
- result: asyncEndEvent.result,
12199
- span,
12200
- startTime
12201
- });
12287
+ output
12288
+ };
12202
12289
  span.log({
12203
12290
  output,
12204
12291
  ...metadata !== void 0 ? { metadata } : {},
@@ -12210,11 +12297,49 @@ function traceStreamingChannel(channel2, config) {
12210
12297
  error
12211
12298
  );
12212
12299
  } finally {
12213
- span.end();
12300
+ try {
12301
+ span.end();
12302
+ } catch (error) {
12303
+ debugLogger.error(
12304
+ `Error ending span for ${channelName}:`,
12305
+ error
12306
+ );
12307
+ }
12214
12308
  states.delete(event);
12215
12309
  }
12310
+ if (completion2) {
12311
+ runStreamingCompletionHook({
12312
+ channelName,
12313
+ chunks,
12314
+ config,
12315
+ endEvent: asyncEndEvent,
12316
+ ...completion2.metadata !== void 0 ? { metadata: completion2.metadata } : {},
12317
+ metrics: completion2.metrics,
12318
+ output: completion2.output,
12319
+ result: asyncEndEvent.result,
12320
+ span,
12321
+ startTime
12322
+ });
12323
+ }
12216
12324
  },
12217
12325
  onError: (error) => {
12326
+ try {
12327
+ span.log({ error });
12328
+ } catch (loggingError) {
12329
+ debugLogger.error(
12330
+ `Error logging failure for ${channelName}:`,
12331
+ loggingError
12332
+ );
12333
+ }
12334
+ try {
12335
+ span.end();
12336
+ } catch (endingError) {
12337
+ debugLogger.error(
12338
+ `Error ending span for ${channelName}:`,
12339
+ endingError
12340
+ );
12341
+ }
12342
+ states.delete(event);
12218
12343
  runStreamingErrorHook({
12219
12344
  channelName,
12220
12345
  config,
@@ -12223,11 +12348,6 @@ function traceStreamingChannel(channel2, config) {
12223
12348
  span,
12224
12349
  startTime
12225
12350
  });
12226
- span.log({
12227
- error: error.message
12228
- });
12229
- span.end();
12230
- states.delete(event);
12231
12351
  }
12232
12352
  });
12233
12353
  return;
@@ -12242,6 +12362,7 @@ function traceStreamingChannel(channel2, config) {
12242
12362
  states.delete(event);
12243
12363
  return;
12244
12364
  }
12365
+ let completion;
12245
12366
  try {
12246
12367
  const output = config.extractOutput(
12247
12368
  asyncEndEvent.result,
@@ -12256,17 +12377,11 @@ function traceStreamingChannel(channel2, config) {
12256
12377
  asyncEndEvent.result,
12257
12378
  asyncEndEvent
12258
12379
  );
12259
- runStreamingCompletionHook({
12260
- channelName,
12261
- config,
12262
- endEvent: asyncEndEvent,
12380
+ completion = {
12263
12381
  ...normalizeMetadata(metadata) !== void 0 ? { metadata: normalizeMetadata(metadata) } : {},
12264
12382
  metrics,
12265
- output,
12266
- result: asyncEndEvent.result,
12267
- span,
12268
- startTime
12269
- });
12383
+ output
12384
+ };
12270
12385
  span.log({
12271
12386
  output,
12272
12387
  ...normalizeMetadata(metadata) !== void 0 ? { metadata: normalizeMetadata(metadata) } : {},
@@ -12275,12 +12390,30 @@ function traceStreamingChannel(channel2, config) {
12275
12390
  } catch (error) {
12276
12391
  debugLogger.error(`Error extracting output for ${channelName}:`, error);
12277
12392
  } finally {
12278
- span.end();
12393
+ try {
12394
+ span.end();
12395
+ } catch (error) {
12396
+ debugLogger.error(`Error ending span for ${channelName}:`, error);
12397
+ }
12279
12398
  states.delete(event);
12280
12399
  }
12400
+ if (completion) {
12401
+ runStreamingCompletionHook({
12402
+ channelName,
12403
+ config,
12404
+ endEvent: asyncEndEvent,
12405
+ ...completion.metadata !== void 0 ? { metadata: completion.metadata } : {},
12406
+ metrics: completion.metrics,
12407
+ output: completion.output,
12408
+ result: asyncEndEvent.result,
12409
+ span,
12410
+ startTime
12411
+ });
12412
+ }
12281
12413
  },
12282
12414
  error: (event) => {
12283
12415
  const spanData = states.get(event);
12416
+ logErrorAndEnd(states, event, channelName);
12284
12417
  if (spanData) {
12285
12418
  runStreamingErrorHook({
12286
12419
  channelName,
@@ -12291,7 +12424,6 @@ function traceStreamingChannel(channel2, config) {
12291
12424
  startTime: spanData.startTime
12292
12425
  });
12293
12426
  }
12294
- logErrorAndEnd(states, event);
12295
12427
  }
12296
12428
  };
12297
12429
  tracingChannel2.subscribe(handlers);
@@ -12308,7 +12440,8 @@ function traceSyncStreamChannel(channel2, config) {
12308
12440
  tracingChannel2,
12309
12441
  states,
12310
12442
  config,
12311
- channelName
12443
+ channelName,
12444
+ channel2.instrumentationName
12312
12445
  );
12313
12446
  const handlers = {
12314
12447
  start: (event) => {
@@ -12319,7 +12452,8 @@ function traceSyncStreamChannel(channel2, config) {
12319
12452
  states,
12320
12453
  config,
12321
12454
  event,
12322
- channelName
12455
+ channelName,
12456
+ channel2.instrumentationName
12323
12457
  );
12324
12458
  },
12325
12459
  end: (event) => {
@@ -12413,7 +12547,7 @@ function traceSyncStreamChannel(channel2, config) {
12413
12547
  handleResolvedResult(endEvent.result);
12414
12548
  },
12415
12549
  error: (event) => {
12416
- logErrorAndEnd(states, event);
12550
+ logErrorAndEnd(states, event, channelName);
12417
12551
  }
12418
12552
  };
12419
12553
  tracingChannel2.subscribe(handlers);
@@ -12592,7 +12726,8 @@ function processInputAttachments(input) {
12592
12726
  function channel(spec) {
12593
12727
  return spec;
12594
12728
  }
12595
- function defineChannels(pkg, channels) {
12729
+ function defineChannels(pkg, channels, options) {
12730
+ const { instrumentationName } = options;
12596
12731
  return Object.fromEntries(
12597
12732
  Object.entries(channels).map(([key, spec]) => {
12598
12733
  const fullChannelName = `orchestrion:${pkg}:${spec.channelName}`;
@@ -12605,6 +12740,7 @@ function defineChannels(pkg, channels) {
12605
12740
  key,
12606
12741
  {
12607
12742
  ...asyncSpec,
12743
+ instrumentationName,
12608
12744
  tracingChannel: tracingChannel3,
12609
12745
  tracePromise: (fn, context) => tracingChannel3().tracePromise(
12610
12746
  fn,
@@ -12622,6 +12758,7 @@ function defineChannels(pkg, channels) {
12622
12758
  key,
12623
12759
  {
12624
12760
  ...syncSpec,
12761
+ instrumentationName,
12625
12762
  tracingChannel: tracingChannel2,
12626
12763
  traceSync: (fn, context) => tracingChannel2().traceSync(
12627
12764
  fn,
@@ -12635,44 +12772,48 @@ function defineChannels(pkg, channels) {
12635
12772
  }
12636
12773
 
12637
12774
  // src/instrumentation/plugins/openai-channels.ts
12638
- var openAIChannels = defineChannels("openai", {
12639
- chatCompletionsCreate: channel({
12640
- channelName: "chat.completions.create",
12641
- kind: "async"
12642
- }),
12643
- embeddingsCreate: channel({
12644
- channelName: "embeddings.create",
12645
- kind: "async"
12646
- }),
12647
- betaChatCompletionsParse: channel({
12648
- channelName: "beta.chat.completions.parse",
12649
- kind: "async"
12650
- }),
12651
- betaChatCompletionsStream: channel({
12652
- channelName: "beta.chat.completions.stream",
12653
- kind: "sync-stream"
12654
- }),
12655
- moderationsCreate: channel({
12656
- channelName: "moderations.create",
12657
- kind: "async"
12658
- }),
12659
- responsesCreate: channel({
12660
- channelName: "responses.create",
12661
- kind: "async"
12662
- }),
12663
- responsesStream: channel({
12664
- channelName: "responses.stream",
12665
- kind: "sync-stream"
12666
- }),
12667
- responsesParse: channel({
12668
- channelName: "responses.parse",
12669
- kind: "async"
12670
- }),
12671
- responsesCompact: channel({
12672
- channelName: "responses.compact",
12673
- kind: "async"
12674
- })
12675
- });
12775
+ var openAIChannels = defineChannels(
12776
+ "openai",
12777
+ {
12778
+ chatCompletionsCreate: channel({
12779
+ channelName: "chat.completions.create",
12780
+ kind: "async"
12781
+ }),
12782
+ embeddingsCreate: channel({
12783
+ channelName: "embeddings.create",
12784
+ kind: "async"
12785
+ }),
12786
+ betaChatCompletionsParse: channel({
12787
+ channelName: "beta.chat.completions.parse",
12788
+ kind: "async"
12789
+ }),
12790
+ betaChatCompletionsStream: channel({
12791
+ channelName: "beta.chat.completions.stream",
12792
+ kind: "sync-stream"
12793
+ }),
12794
+ moderationsCreate: channel({
12795
+ channelName: "moderations.create",
12796
+ kind: "async"
12797
+ }),
12798
+ responsesCreate: channel({
12799
+ channelName: "responses.create",
12800
+ kind: "async"
12801
+ }),
12802
+ responsesStream: channel({
12803
+ channelName: "responses.stream",
12804
+ kind: "sync-stream"
12805
+ }),
12806
+ responsesParse: channel({
12807
+ channelName: "responses.parse",
12808
+ kind: "async"
12809
+ }),
12810
+ responsesCompact: channel({
12811
+ channelName: "responses.compact",
12812
+ kind: "async"
12813
+ })
12814
+ },
12815
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENAI }
12816
+ );
12676
12817
 
12677
12818
  // src/openai-utils.ts
12678
12819
  var BRAINTRUST_CACHED_STREAM_METRIC = "__braintrust_cached_metric";
@@ -13187,16 +13328,20 @@ function aggregateResponseStreamEvents(chunks, _streamResult, endEvent) {
13187
13328
  }
13188
13329
 
13189
13330
  // src/instrumentation/plugins/openai-codex-channels.ts
13190
- var openAICodexChannels = defineChannels("@openai/codex-sdk", {
13191
- run: channel({
13192
- channelName: "Thread.run",
13193
- kind: "async"
13194
- }),
13195
- runStreamed: channel({
13196
- channelName: "Thread.runStreamed",
13197
- kind: "async"
13198
- })
13199
- });
13331
+ var openAICodexChannels = defineChannels(
13332
+ "@openai/codex-sdk",
13333
+ {
13334
+ run: channel({
13335
+ channelName: "Thread.run",
13336
+ kind: "async"
13337
+ }),
13338
+ runStreamed: channel({
13339
+ channelName: "Thread.runStreamed",
13340
+ kind: "async"
13341
+ })
13342
+ },
13343
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENAI_CODEX }
13344
+ );
13200
13345
 
13201
13346
  // src/instrumentation/plugins/openai-codex-plugin.ts
13202
13347
  var PATCHED_STREAMED_TURN = /* @__PURE__ */ Symbol.for(
@@ -13284,10 +13429,15 @@ function startCodexRun(event, operation) {
13284
13429
  provider: "openai",
13285
13430
  ...event.moduleVersion ? { "openai_codex.version": event.moduleVersion } : {}
13286
13431
  };
13287
- const span = startSpan({
13288
- name: "OpenAI Codex",
13289
- spanAttributes: { type: "task" /* TASK */ }
13290
- });
13432
+ const span = startSpan(
13433
+ withSpanInstrumentationName(
13434
+ {
13435
+ name: "OpenAI Codex",
13436
+ spanAttributes: { type: "task" /* TASK */ }
13437
+ },
13438
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
13439
+ )
13440
+ );
13291
13441
  const startTime = getCurrentUnixTimestamp();
13292
13442
  safeLog(span, {
13293
13443
  input: sanitizedInput,
@@ -13436,7 +13586,12 @@ async function createCompletedItemSpan(state, item) {
13436
13586
  if (!spanArgs) {
13437
13587
  return;
13438
13588
  }
13439
- const span = startSpan(spanArgs.start);
13589
+ const span = startSpan(
13590
+ withSpanInstrumentationName(
13591
+ spanArgs.start,
13592
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
13593
+ )
13594
+ );
13440
13595
  safeLog(span, spanArgs.end);
13441
13596
  span.end();
13442
13597
  }
@@ -13478,15 +13633,20 @@ async function ensureActiveLlmSpan(state) {
13478
13633
  ...state.metadata["openai_codex.thread_id"] ? { "openai_codex.thread_id": state.metadata["openai_codex.thread_id"] } : {},
13479
13634
  "openai_codex.llm_sequence": sequence
13480
13635
  };
13481
- const span = startSpan({
13482
- event: {
13483
- ...sequence === 1 ? { input: state.input } : {},
13484
- metadata
13485
- },
13486
- name: "OpenAI Codex LLM",
13487
- parent: await state.span.export(),
13488
- spanAttributes: { type: "llm" /* LLM */ }
13489
- });
13636
+ const span = startSpan(
13637
+ withSpanInstrumentationName(
13638
+ {
13639
+ event: {
13640
+ ...sequence === 1 ? { input: state.input } : {},
13641
+ metadata
13642
+ },
13643
+ name: "OpenAI Codex LLM",
13644
+ parent: await state.span.export(),
13645
+ spanAttributes: { type: "llm" /* LLM */ }
13646
+ },
13647
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
13648
+ )
13649
+ );
13490
13650
  state.activeLlmSpan = {
13491
13651
  anonymousMessages: [],
13492
13652
  anonymousReasoning: [],
@@ -13532,7 +13692,15 @@ async function startCodexItemSpan(state, item) {
13532
13692
  if (!spanArgs) {
13533
13693
  return;
13534
13694
  }
13535
- state.activeItemSpans.set(itemId, startSpan(spanArgs.start));
13695
+ state.activeItemSpans.set(
13696
+ itemId,
13697
+ startSpan(
13698
+ withSpanInstrumentationName(
13699
+ spanArgs.start,
13700
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
13701
+ )
13702
+ )
13703
+ );
13536
13704
  }
13537
13705
  function updateCodexItem(state, item) {
13538
13706
  if (item.type === "agent_message" && typeof item.text === "string") {
@@ -13842,20 +14010,24 @@ function extractAnthropicCacheTokens(cacheReadTokens = 0, cacheCreationTokens =
13842
14010
  }
13843
14011
 
13844
14012
  // src/instrumentation/plugins/anthropic-channels.ts
13845
- var anthropicChannels = defineChannels("@anthropic-ai/sdk", {
13846
- messagesCreate: channel({
13847
- channelName: "messages.create",
13848
- kind: "async"
13849
- }),
13850
- betaMessagesCreate: channel({
13851
- channelName: "beta.messages.create",
13852
- kind: "async"
13853
- }),
13854
- betaMessagesToolRunner: channel({
13855
- channelName: "beta.messages.toolRunner",
13856
- kind: "sync-stream"
13857
- })
13858
- });
14013
+ var anthropicChannels = defineChannels(
14014
+ "@anthropic-ai/sdk",
14015
+ {
14016
+ messagesCreate: channel({
14017
+ channelName: "messages.create",
14018
+ kind: "async"
14019
+ }),
14020
+ betaMessagesCreate: channel({
14021
+ channelName: "beta.messages.create",
14022
+ kind: "async"
14023
+ }),
14024
+ betaMessagesToolRunner: channel({
14025
+ channelName: "beta.messages.toolRunner",
14026
+ kind: "sync-stream"
14027
+ })
14028
+ },
14029
+ { instrumentationName: INSTRUMENTATION_NAMES.ANTHROPIC }
14030
+ );
13859
14031
 
13860
14032
  // src/instrumentation/plugins/anthropic-plugin.ts
13861
14033
  var ANTHROPIC_TOOL_RUNNER_TOOL_WRAPPED = /* @__PURE__ */ Symbol.for(
@@ -13928,12 +14100,17 @@ var AnthropicPlugin = class extends BasePlugin {
13928
14100
  return;
13929
14101
  }
13930
14102
  const params = event.arguments[0] ?? {};
13931
- const span = startSpan({
13932
- name: "anthropic.beta.messages.toolRunner",
13933
- spanAttributes: {
13934
- type: "task" /* TASK */
13935
- }
13936
- });
14103
+ const span = startSpan(
14104
+ withSpanInstrumentationName(
14105
+ {
14106
+ name: "anthropic.beta.messages.toolRunner",
14107
+ spanAttributes: {
14108
+ type: "task" /* TASK */
14109
+ }
14110
+ },
14111
+ INSTRUMENTATION_NAMES.ANTHROPIC
14112
+ )
14113
+ );
13937
14114
  span.log({
13938
14115
  input: processAttachmentsInInput(
13939
14116
  coalesceInput(params.messages ?? [], params.system)
@@ -14074,19 +14251,22 @@ function wrapAnthropicToolRunnerTool(tool, index, state) {
14074
14251
  return finalizeError(error);
14075
14252
  }
14076
14253
  },
14077
- {
14078
- event: {
14079
- input: getAnthropicToolRunnerInput(args),
14080
- metadata: {
14081
- "gen_ai.tool.name": toolName,
14082
- provider: "anthropic"
14254
+ withSpanInstrumentationName(
14255
+ {
14256
+ event: {
14257
+ input: getAnthropicToolRunnerInput(args),
14258
+ metadata: {
14259
+ "gen_ai.tool.name": toolName,
14260
+ provider: "anthropic"
14261
+ }
14262
+ },
14263
+ name: `tool: ${toolName}`,
14264
+ spanAttributes: {
14265
+ type: "tool" /* TOOL */
14083
14266
  }
14084
14267
  },
14085
- name: `tool: ${toolName}`,
14086
- spanAttributes: {
14087
- type: "tool" /* TOOL */
14088
- }
14089
- }
14268
+ INSTRUMENTATION_NAMES.ANTHROPIC
14269
+ )
14090
14270
  );
14091
14271
  },
14092
14272
  writable: runDescriptor?.writable ?? true
@@ -14681,6 +14861,267 @@ function currentWorkflowAgentWrapperSpan() {
14681
14861
  return void 0;
14682
14862
  }
14683
14863
 
14864
+ // src/wrappers/ai-sdk/harness-agent-context.ts
14865
+ var BRAINTRUST_TURN_CONTEXT_KEY = "__braintrust_trace_context";
14866
+ var sessionTurnParents = /* @__PURE__ */ new WeakMap();
14867
+ var wrapperTurnParents = /* @__PURE__ */ new WeakMap();
14868
+ var patchedLifecycleMethods = /* @__PURE__ */ new WeakMap();
14869
+ var harnessTurnParentStore;
14870
+ function serializedTurnContext(value) {
14871
+ if (!isObject(value)) {
14872
+ return void 0;
14873
+ }
14874
+ const context = value[BRAINTRUST_TURN_CONTEXT_KEY];
14875
+ if (!isObject(context) || typeof context.parent !== "string" || typeof context.sessionId !== "string" || typeof context.signature !== "string") {
14876
+ return void 0;
14877
+ }
14878
+ const expectedSignature = signTurnContext({
14879
+ parent: context.parent,
14880
+ sessionId: context.sessionId
14881
+ });
14882
+ if (!expectedSignature || !isomorph_default.timingSafeEqual?.(context.signature, expectedSignature)) {
14883
+ return void 0;
14884
+ }
14885
+ const parent = SpanComponentsV4.fromStr(context.parent);
14886
+ if (!parent.data.row_id || !parent.data.root_span_id || !parent.data.span_id) {
14887
+ return void 0;
14888
+ }
14889
+ return {
14890
+ parent: context.parent,
14891
+ sessionId: context.sessionId
14892
+ };
14893
+ }
14894
+ function signTurnContext(context) {
14895
+ const secret = _internalGetGlobalState()._internalGetTraceContextSigningSecret();
14896
+ return secret ? isomorph_default.hmacSha256?.(
14897
+ secret,
14898
+ JSON.stringify([BRAINTRUST_TURN_CONTEXT_KEY, context])
14899
+ ) : void 0;
14900
+ }
14901
+ function continuationParentFromCreateSessionParams(params) {
14902
+ if (!isObject(params)) {
14903
+ return void 0;
14904
+ }
14905
+ const continuation = params.continueFrom ?? (isObject(params.resumeFrom) ? params.resumeFrom.continueFrom : void 0);
14906
+ const context = serializedTurnContext(continuation);
14907
+ if (!context) {
14908
+ return void 0;
14909
+ }
14910
+ if (params.sessionId !== context.sessionId) {
14911
+ return void 0;
14912
+ }
14913
+ return context.parent;
14914
+ }
14915
+ function exportSpanSynchronously(span) {
14916
+ const parentInfo = span.getParentInfo();
14917
+ if (!parentInfo) {
14918
+ return void 0;
14919
+ }
14920
+ const objectId = parentInfo.objectId.getSync().value;
14921
+ if (!objectId && !parentInfo.computeObjectMetadataArgs) {
14922
+ return void 0;
14923
+ }
14924
+ return new SpanComponentsV4({
14925
+ object_type: parentInfo.objectType,
14926
+ ...objectId ? { object_id: objectId } : {
14927
+ compute_object_metadata_args: parentInfo.computeObjectMetadataArgs ?? {}
14928
+ },
14929
+ row_id: span.id,
14930
+ root_span_id: span.rootSpanId,
14931
+ span_id: span.spanId
14932
+ }).toStr();
14933
+ }
14934
+ function exportedParent(parent) {
14935
+ return typeof parent === "string" ? parent : exportSpanSynchronously(parent);
14936
+ }
14937
+ function addSerializedContext(args) {
14938
+ if (!isObject(args.continuation) || args.sessionId === void 0) {
14939
+ return;
14940
+ }
14941
+ const parent = exportedParent(args.parent);
14942
+ if (!parent) {
14943
+ return;
14944
+ }
14945
+ const context = {
14946
+ parent,
14947
+ sessionId: args.sessionId
14948
+ };
14949
+ const signature = signTurnContext(context);
14950
+ if (!signature) {
14951
+ return;
14952
+ }
14953
+ Object.defineProperty(args.continuation, BRAINTRUST_TURN_CONTEXT_KEY, {
14954
+ configurable: true,
14955
+ enumerable: true,
14956
+ value: {
14957
+ ...context,
14958
+ signature
14959
+ },
14960
+ writable: true
14961
+ });
14962
+ }
14963
+ function lifecycleMethodDescriptor(session, method) {
14964
+ let owner = session;
14965
+ while (owner) {
14966
+ const descriptor = Object.getOwnPropertyDescriptor(owner, method);
14967
+ if (descriptor) {
14968
+ return { descriptor, owner };
14969
+ }
14970
+ owner = Object.getPrototypeOf(owner);
14971
+ }
14972
+ return void 0;
14973
+ }
14974
+ function patchLifecycleMethod(session, method) {
14975
+ let resolvedDescriptor;
14976
+ try {
14977
+ resolvedDescriptor = lifecycleMethodDescriptor(session, method);
14978
+ } catch {
14979
+ return;
14980
+ }
14981
+ if (!resolvedDescriptor || !("value" in resolvedDescriptor.descriptor) || typeof resolvedDescriptor.descriptor.value !== "function") {
14982
+ return;
14983
+ }
14984
+ const { descriptor, owner } = resolvedDescriptor;
14985
+ const patched = patchedLifecycleMethods.get(owner);
14986
+ if (patched?.has(method)) {
14987
+ return;
14988
+ }
14989
+ const original = descriptor.value;
14990
+ const replacement = function(...args) {
14991
+ const result = Reflect.apply(original, this, args);
14992
+ const addContext = (state) => {
14993
+ try {
14994
+ const parent = sessionTurnParents.get(this);
14995
+ if (!parent) {
14996
+ return;
14997
+ }
14998
+ const continuation = method === "suspendTurn" ? state : isObject(state) ? state.continueFrom : void 0;
14999
+ addSerializedContext({
15000
+ continuation,
15001
+ parent,
15002
+ sessionId: typeof this.sessionId === "string" ? this.sessionId : void 0
15003
+ });
15004
+ } catch {
15005
+ }
15006
+ };
15007
+ try {
15008
+ if (isObject(result) && typeof result.then === "function") {
15009
+ void Promise.resolve(result).then(addContext, () => {
15010
+ });
15011
+ } else {
15012
+ addContext(result);
15013
+ }
15014
+ } catch {
15015
+ }
15016
+ return result;
15017
+ };
15018
+ try {
15019
+ Object.defineProperty(owner, method, {
15020
+ ...descriptor,
15021
+ value: replacement
15022
+ });
15023
+ const ownerMethods = patched ?? /* @__PURE__ */ new Set();
15024
+ ownerMethods.add(method);
15025
+ if (!patched) {
15026
+ patchedLifecycleMethods.set(owner, ownerMethods);
15027
+ }
15028
+ } catch {
15029
+ }
15030
+ }
15031
+ function patchLifecycleMethods(session) {
15032
+ patchLifecycleMethod(session, "suspendTurn");
15033
+ patchLifecycleMethod(session, "detach");
15034
+ patchLifecycleMethod(session, "stop");
15035
+ }
15036
+ function registerHarnessTurnSpan(args) {
15037
+ if (!isObject(args.session)) {
15038
+ return;
15039
+ }
15040
+ const session = args.session;
15041
+ sessionTurnParents.set(session, args.span);
15042
+ wrapperTurnParents.set(args.span, args.span);
15043
+ patchLifecycleMethods(session);
15044
+ }
15045
+ function harnessContinuationParent(session) {
15046
+ return isObject(session) ? sessionTurnParents.get(session) : void 0;
15047
+ }
15048
+ function captureHarnessCreateSessionParent(params) {
15049
+ try {
15050
+ return continuationParentFromCreateSessionParams(params);
15051
+ } catch {
15052
+ return void 0;
15053
+ }
15054
+ }
15055
+ function registerHarnessSessionParent(session, parent) {
15056
+ if (!parent || !isObject(session)) {
15057
+ return;
15058
+ }
15059
+ const harnessSession = session;
15060
+ sessionTurnParents.set(harnessSession, parent);
15061
+ patchLifecycleMethods(harnessSession);
15062
+ }
15063
+ function currentHarnessTurnParent() {
15064
+ return harnessTurnParentStore?.getStore() ?? wrapperTurnParents.get(currentSpan());
15065
+ }
15066
+ function bindHarnessTurnParentToStart(tracingChannel2, parentFromEvent) {
15067
+ const startChannel = tracingChannel2.start;
15068
+ if (!startChannel) {
15069
+ return () => {
15070
+ };
15071
+ }
15072
+ harnessTurnParentStore ??= isomorph_default.newAsyncLocalStorage();
15073
+ const store = harnessTurnParentStore;
15074
+ startChannel.bindStore(
15075
+ store,
15076
+ (event) => parentFromEvent(event) ?? store.getStore()
15077
+ );
15078
+ return () => {
15079
+ startChannel.unbindStore(store);
15080
+ };
15081
+ }
15082
+ function startHarnessTurnChildSpan(parent, args) {
15083
+ const spanArgs = withSpanInstrumentationName(
15084
+ args,
15085
+ INSTRUMENTATION_NAMES.AI_SDK
15086
+ );
15087
+ return typeof parent === "string" ? startSpan({ ...spanArgs, parent }) : parent.startSpan(spanArgs);
15088
+ }
15089
+ function updateHarnessTurn(parent, update = {}) {
15090
+ if (!parent) {
15091
+ return;
15092
+ }
15093
+ const log3 = (event) => {
15094
+ if (typeof parent === "string") {
15095
+ updateSpan({ exported: parent, ...event });
15096
+ } else {
15097
+ parent.log(event);
15098
+ }
15099
+ };
15100
+ try {
15101
+ if (Object.prototype.hasOwnProperty.call(update, "output")) {
15102
+ log3({ output: null });
15103
+ }
15104
+ log3(update);
15105
+ } catch {
15106
+ }
15107
+ }
15108
+ function endHarnessTurn(parent) {
15109
+ const endTime = getCurrentUnixTimestamp();
15110
+ if (!parent) {
15111
+ return endTime;
15112
+ }
15113
+ try {
15114
+ const event = { metrics: { end: endTime } };
15115
+ if (typeof parent === "string") {
15116
+ updateSpan({ exported: parent, ...event });
15117
+ } else {
15118
+ parent.log(event);
15119
+ }
15120
+ } catch {
15121
+ }
15122
+ return endTime;
15123
+ }
15124
+
14684
15125
  // src/wrappers/ai-sdk/telemetry.ts
14685
15126
  function braintrustAISDKTelemetry() {
14686
15127
  const operations = /* @__PURE__ */ new Map();
@@ -14699,14 +15140,17 @@ function braintrustAISDKTelemetry() {
14699
15140
  console.error(`Error in Braintrust AI SDK telemetry ${name}:`, error);
14700
15141
  }
14701
15142
  };
14702
- const startChildSpan = (operationKey, name, type, event) => {
15143
+ const startChildSpan = (operationKey, name, type, event, parentOverride) => {
14703
15144
  const parent = operations.get(operationKey)?.span;
14704
- const spanArgs = {
14705
- name,
14706
- spanAttributes: { type },
14707
- ...event ? { event } : {}
14708
- };
14709
- const span = parent ? parent.startSpan(spanArgs) : startSpan(spanArgs);
15145
+ const spanArgs = withSpanInstrumentationName(
15146
+ {
15147
+ name,
15148
+ spanAttributes: { type },
15149
+ ...event ? { event } : {}
15150
+ },
15151
+ INSTRUMENTATION_NAMES.AI_SDK
15152
+ );
15153
+ const span = parentOverride ? startHarnessTurnChildSpan(parentOverride, spanArgs) : parent ? parent.startSpan(spanArgs) : startSpan(spanArgs);
14710
15154
  const state = operations.get(operationKey);
14711
15155
  if (state && type === "llm" /* LLM */) {
14712
15156
  state.hadModelChild = true;
@@ -14986,14 +15430,30 @@ function braintrustAISDKTelemetry() {
14986
15430
  const workflowAgent = operationName === "WorkflowAgent.stream";
14987
15431
  const wrapperSpan = workflowAgent ? currentWorkflowAgentWrapperSpan() : void 0;
14988
15432
  const ownsSpan = !wrapperSpan;
14989
- const span = ownsSpan ? startSpan({
14990
- name: operationName,
14991
- spanAttributes: { type: "function" /* FUNCTION */ }
14992
- }) : wrapperSpan;
15433
+ const harnessTurnParent = currentHarnessTurnParent();
15434
+ const span = ownsSpan ? harnessTurnParent ? startHarnessTurnChildSpan(
15435
+ harnessTurnParent,
15436
+ withSpanInstrumentationName(
15437
+ {
15438
+ name: operationName,
15439
+ spanAttributes: { type: "function" /* FUNCTION */ }
15440
+ },
15441
+ INSTRUMENTATION_NAMES.AI_SDK
15442
+ )
15443
+ ) : startSpan(
15444
+ withSpanInstrumentationName(
15445
+ {
15446
+ name: operationName,
15447
+ spanAttributes: { type: "function" /* FUNCTION */ }
15448
+ },
15449
+ INSTRUMENTATION_NAMES.AI_SDK
15450
+ )
15451
+ ) : wrapperSpan;
14993
15452
  const operationKey = createOperationKey(event, operationName);
14994
15453
  registerOperation({
14995
15454
  callId: event.callId,
14996
15455
  hadModelChild: false,
15456
+ harnessTurnParent,
14997
15457
  loggedInput: false,
14998
15458
  operationName,
14999
15459
  operationKey,
@@ -15234,7 +15694,8 @@ function braintrustAISDKTelemetry() {
15234
15694
  toolCallId,
15235
15695
  ...typeof event.toolCall.toolName === "string" ? { toolName: event.toolCall.toolName } : {}
15236
15696
  }
15237
- }
15697
+ },
15698
+ state?.harnessTurnParent
15238
15699
  );
15239
15700
  toolSpans.set(toolCallId, { operationKey, span });
15240
15701
  });
@@ -15470,92 +15931,102 @@ function finishOutput(result, operationName) {
15470
15931
  }
15471
15932
 
15472
15933
  // src/instrumentation/plugins/ai-sdk-channels.ts
15473
- var aiSDKChannels = defineChannels("ai", {
15474
- generateText: channel({
15475
- channelName: "generateText",
15476
- kind: "async"
15477
- }),
15478
- streamText: channel({
15479
- channelName: "streamText",
15480
- kind: "async"
15481
- }),
15482
- streamTextSync: channel({
15483
- channelName: "streamText.sync",
15484
- kind: "sync-stream"
15485
- }),
15486
- generateObject: channel({
15487
- channelName: "generateObject",
15488
- kind: "async"
15489
- }),
15490
- streamObject: channel({
15491
- channelName: "streamObject",
15492
- kind: "async"
15493
- }),
15494
- streamObjectSync: channel({
15495
- channelName: "streamObject.sync",
15496
- kind: "sync-stream"
15497
- }),
15498
- embed: channel(
15499
- {
15934
+ var aiSDKChannels = defineChannels(
15935
+ "ai",
15936
+ {
15937
+ generateText: channel({
15938
+ channelName: "generateText",
15939
+ kind: "async"
15940
+ }),
15941
+ streamText: channel({
15942
+ channelName: "streamText",
15943
+ kind: "async"
15944
+ }),
15945
+ streamTextSync: channel({
15946
+ channelName: "streamText.sync",
15947
+ kind: "sync-stream"
15948
+ }),
15949
+ generateObject: channel({
15950
+ channelName: "generateObject",
15951
+ kind: "async"
15952
+ }),
15953
+ streamObject: channel({
15954
+ channelName: "streamObject",
15955
+ kind: "async"
15956
+ }),
15957
+ streamObjectSync: channel({
15958
+ channelName: "streamObject.sync",
15959
+ kind: "sync-stream"
15960
+ }),
15961
+ embed: channel({
15500
15962
  channelName: "embed",
15501
15963
  kind: "async"
15502
- }
15503
- ),
15504
- embedMany: channel({
15505
- channelName: "embedMany",
15506
- kind: "async"
15507
- }),
15508
- rerank: channel({
15509
- channelName: "rerank",
15510
- kind: "async"
15511
- }),
15512
- agentGenerate: channel({
15513
- channelName: "Agent.generate",
15514
- kind: "async"
15515
- }),
15516
- agentStream: channel({
15517
- channelName: "Agent.stream",
15518
- kind: "async"
15519
- }),
15520
- agentStreamSync: channel({
15521
- channelName: "Agent.stream.sync",
15522
- kind: "sync-stream"
15523
- }),
15524
- toolLoopAgentGenerate: channel({
15525
- channelName: "ToolLoopAgent.generate",
15526
- kind: "async"
15527
- }),
15528
- toolLoopAgentStream: channel({
15529
- channelName: "ToolLoopAgent.stream",
15530
- kind: "async"
15531
- }),
15532
- workflowAgentStream: channel({
15533
- channelName: "WorkflowAgent.stream",
15534
- kind: "async"
15535
- }),
15536
- v7CreateTelemetryDispatcher: channel({
15537
- channelName: "createTelemetryDispatcher",
15538
- kind: "sync-stream"
15539
- })
15540
- });
15541
- var harnessAgentChannels = defineChannels("@ai-sdk/harness", {
15542
- generate: channel({
15543
- channelName: "HarnessAgent.generate",
15544
- kind: "async"
15545
- }),
15546
- stream: channel({
15547
- channelName: "HarnessAgent.stream",
15548
- kind: "async"
15549
- }),
15550
- continueGenerate: channel({
15551
- channelName: "HarnessAgent.continueGenerate",
15552
- kind: "async"
15553
- }),
15554
- continueStream: channel({
15555
- channelName: "HarnessAgent.continueStream",
15556
- kind: "async"
15557
- })
15558
- });
15964
+ }),
15965
+ embedMany: channel({
15966
+ channelName: "embedMany",
15967
+ kind: "async"
15968
+ }),
15969
+ rerank: channel({
15970
+ channelName: "rerank",
15971
+ kind: "async"
15972
+ }),
15973
+ agentGenerate: channel({
15974
+ channelName: "Agent.generate",
15975
+ kind: "async"
15976
+ }),
15977
+ agentStream: channel({
15978
+ channelName: "Agent.stream",
15979
+ kind: "async"
15980
+ }),
15981
+ agentStreamSync: channel({
15982
+ channelName: "Agent.stream.sync",
15983
+ kind: "sync-stream"
15984
+ }),
15985
+ toolLoopAgentGenerate: channel({
15986
+ channelName: "ToolLoopAgent.generate",
15987
+ kind: "async"
15988
+ }),
15989
+ toolLoopAgentStream: channel({
15990
+ channelName: "ToolLoopAgent.stream",
15991
+ kind: "async"
15992
+ }),
15993
+ workflowAgentStream: channel({
15994
+ channelName: "WorkflowAgent.stream",
15995
+ kind: "async"
15996
+ }),
15997
+ v7CreateTelemetryDispatcher: channel({
15998
+ channelName: "createTelemetryDispatcher",
15999
+ kind: "sync-stream"
16000
+ })
16001
+ },
16002
+ { instrumentationName: INSTRUMENTATION_NAMES.AI_SDK }
16003
+ );
16004
+ var harnessAgentChannels = defineChannels(
16005
+ "@ai-sdk/harness",
16006
+ {
16007
+ createSession: channel({
16008
+ channelName: "HarnessAgent.createSession",
16009
+ kind: "async"
16010
+ }),
16011
+ generate: channel({
16012
+ channelName: "HarnessAgent.generate",
16013
+ kind: "async"
16014
+ }),
16015
+ stream: channel({
16016
+ channelName: "HarnessAgent.stream",
16017
+ kind: "async"
16018
+ }),
16019
+ continueGenerate: channel({
16020
+ channelName: "HarnessAgent.continueGenerate",
16021
+ kind: "async"
16022
+ }),
16023
+ continueStream: channel({
16024
+ channelName: "HarnessAgent.continueStream",
16025
+ kind: "async"
16026
+ })
16027
+ },
16028
+ { instrumentationName: INSTRUMENTATION_NAMES.AI_SDK }
16029
+ );
15559
16030
 
15560
16031
  // src/instrumentation/plugins/ai-sdk-plugin.ts
15561
16032
  var DEFAULT_DENY_OUTPUT_PATHS = [
@@ -15632,6 +16103,17 @@ var AISDKPlugin = class extends BasePlugin {
15632
16103
  subscribeToAISDK() {
15633
16104
  const denyOutputPaths = this.config.denyOutputPaths || DEFAULT_DENY_OUTPUT_PATHS;
15634
16105
  this.unsubscribers.push(subscribeToAISDKV7TelemetryDispatcher());
16106
+ this.unsubscribers.push(subscribeToHarnessAgentCreateSession());
16107
+ this.unsubscribers.push(
16108
+ subscribeToHarnessContinuation(
16109
+ harnessAgentChannels.continueGenerate,
16110
+ denyOutputPaths
16111
+ ),
16112
+ subscribeToHarnessContinuation(
16113
+ harnessAgentChannels.continueStream,
16114
+ denyOutputPaths
16115
+ )
16116
+ );
15635
16117
  this.unsubscribers.push(
15636
16118
  traceStreamingChannel(aiSDKChannels.generateText, {
15637
16119
  name: "generateText",
@@ -15827,8 +16309,9 @@ var AISDKPlugin = class extends BasePlugin {
15827
16309
  this.unsubscribers.push(
15828
16310
  traceStreamingChannel(harnessAgentChannels.generate, {
15829
16311
  name: "HarnessAgent.generate",
16312
+ startSpan: _internalStartSpanWithInitialMerge,
15830
16313
  type: "task" /* TASK */,
15831
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
16314
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
15832
16315
  extractOutput: (result, endEvent) => processAISDKOutput(
15833
16316
  result,
15834
16317
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -15840,8 +16323,9 @@ var AISDKPlugin = class extends BasePlugin {
15840
16323
  this.unsubscribers.push(
15841
16324
  traceStreamingChannel(harnessAgentChannels.stream, {
15842
16325
  name: "HarnessAgent.stream",
16326
+ startSpan: _internalStartSpanWithInitialMerge,
15843
16327
  type: "task" /* TASK */,
15844
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
16328
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
15845
16329
  extractOutput: (result, endEvent) => processAISDKOutput(
15846
16330
  result,
15847
16331
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -15866,8 +16350,10 @@ var AISDKPlugin = class extends BasePlugin {
15866
16350
  this.unsubscribers.push(
15867
16351
  traceStreamingChannel(harnessAgentChannels.continueGenerate, {
15868
16352
  name: "HarnessAgent.continueGenerate",
16353
+ shouldTrace: (args) => !harnessContinuationParent(harnessSessionFromArguments(args)),
16354
+ startSpan: _internalStartSpanWithInitialMerge,
15869
16355
  type: "task" /* TASK */,
15870
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
16356
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
15871
16357
  extractOutput: (result, endEvent) => processAISDKOutput(
15872
16358
  result,
15873
16359
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -15879,8 +16365,10 @@ var AISDKPlugin = class extends BasePlugin {
15879
16365
  this.unsubscribers.push(
15880
16366
  traceStreamingChannel(harnessAgentChannels.continueStream, {
15881
16367
  name: "HarnessAgent.continueStream",
16368
+ shouldTrace: (args) => !harnessContinuationParent(harnessSessionFromArguments(args)),
16369
+ startSpan: _internalStartSpanWithInitialMerge,
15882
16370
  type: "task" /* TASK */,
15883
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
16371
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
15884
16372
  extractOutput: (result, endEvent) => processAISDKOutput(
15885
16373
  result,
15886
16374
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -15972,6 +16460,8 @@ var AISDKPlugin = class extends BasePlugin {
15972
16460
  defaultDenyOutputPaths: denyOutputPaths,
15973
16461
  endEvent,
15974
16462
  onComplete: () => unregisterWorkflowAgentWrapperSpan(span),
16463
+ onCancel: () => unregisterWorkflowAgentWrapperSpan(span),
16464
+ onError: () => unregisterWorkflowAgentWrapperSpan(span),
15975
16465
  result,
15976
16466
  span,
15977
16467
  startTime
@@ -15980,6 +16470,153 @@ var AISDKPlugin = class extends BasePlugin {
15980
16470
  );
15981
16471
  }
15982
16472
  };
16473
+ function subscribeToHarnessAgentCreateSession() {
16474
+ const channel2 = harnessAgentChannels.createSession.tracingChannel();
16475
+ const parents = /* @__PURE__ */ new WeakMap();
16476
+ const handlers = {
16477
+ start: (event) => {
16478
+ const parent = captureHarnessCreateSessionParent(event.arguments?.[0]);
16479
+ if (parent) {
16480
+ parents.set(event, parent);
16481
+ }
16482
+ },
16483
+ asyncEnd: (event) => {
16484
+ registerHarnessSessionParent(event.result, parents.get(event));
16485
+ parents.delete(event);
16486
+ },
16487
+ error: (event) => {
16488
+ parents.delete(event);
16489
+ }
16490
+ };
16491
+ channel2.subscribe(handlers);
16492
+ return () => channel2.unsubscribe(handlers);
16493
+ }
16494
+ function harnessContinuationParentFromEvent(event) {
16495
+ try {
16496
+ return harnessContinuationParent(event.arguments?.[0]?.session);
16497
+ } catch {
16498
+ return void 0;
16499
+ }
16500
+ }
16501
+ function subscribeToHarnessContinuation(continuationChannel, defaultDenyOutputPaths) {
16502
+ const channel2 = continuationChannel.tracingChannel();
16503
+ const parents = /* @__PURE__ */ new WeakMap();
16504
+ const startTimes = /* @__PURE__ */ new WeakMap();
16505
+ const unbindParentStore = bindHarnessTurnParentToStart(
16506
+ channel2,
16507
+ harnessContinuationParentFromEvent
16508
+ );
16509
+ const handlers = {
16510
+ start: (event) => {
16511
+ const parent = harnessContinuationParentFromEvent(event);
16512
+ if (!parent) {
16513
+ return;
16514
+ }
16515
+ parents.set(event, parent);
16516
+ startTimes.set(event, getCurrentUnixTimestamp());
16517
+ try {
16518
+ const params = event.arguments?.[0];
16519
+ if (params) {
16520
+ prepareAISDKHarnessAgentInput(params, event.self);
16521
+ }
16522
+ } catch (error) {
16523
+ debugLogger.error(
16524
+ "Error preparing Harness continuation telemetry:",
16525
+ error
16526
+ );
16527
+ }
16528
+ },
16529
+ asyncEnd: (event) => {
16530
+ const parent = parents.get(event);
16531
+ const startTime = startTimes.get(event) ?? getCurrentUnixTimestamp();
16532
+ parents.delete(event);
16533
+ startTimes.delete(event);
16534
+ if (!parent) {
16535
+ return;
16536
+ }
16537
+ const endEvent = event;
16538
+ const span = {
16539
+ end: () => endHarnessTurn(parent),
16540
+ log: (update) => updateHarnessTurn(
16541
+ parent,
16542
+ Object.prototype.hasOwnProperty.call(update, "error") && !Object.prototype.hasOwnProperty.call(update, "output") ? { ...update, output: null } : update
16543
+ )
16544
+ };
16545
+ try {
16546
+ if (isAsyncIterable(endEvent.result)) {
16547
+ patchStreamIfNeeded(endEvent.result, {
16548
+ onComplete: (chunks) => {
16549
+ try {
16550
+ const { metadata, metrics, output } = aggregateAISDKChunks(
16551
+ chunks,
16552
+ endEvent.result,
16553
+ endEvent
16554
+ );
16555
+ span.log({
16556
+ ...metadata ? { metadata } : {},
16557
+ metrics,
16558
+ output
16559
+ });
16560
+ } catch (error) {
16561
+ debugLogger.error(
16562
+ "Error aggregating Harness continuation stream:",
16563
+ error
16564
+ );
16565
+ } finally {
16566
+ span.end();
16567
+ }
16568
+ },
16569
+ onError: (error) => {
16570
+ span.log({ error: toLoggedError(error), output: null });
16571
+ span.end();
16572
+ }
16573
+ });
16574
+ return;
16575
+ }
16576
+ if (patchAISDKStreamingResult({
16577
+ defaultDenyOutputPaths,
16578
+ endEvent,
16579
+ result: endEvent.result,
16580
+ resolvePromiseUsage: true,
16581
+ span,
16582
+ startTime
16583
+ })) {
16584
+ return;
16585
+ }
16586
+ finalizeAISDKChildTracing(endEvent);
16587
+ span.log({
16588
+ metrics: extractTokenMetrics(endEvent.result),
16589
+ output: processAISDKOutput(
16590
+ endEvent.result,
16591
+ resolveDenyOutputPaths(endEvent, defaultDenyOutputPaths)
16592
+ )
16593
+ });
16594
+ span.end();
16595
+ } catch (error) {
16596
+ debugLogger.error("Error tracing Harness continuation:", error);
16597
+ span.end();
16598
+ }
16599
+ },
16600
+ error: (event) => {
16601
+ const parent = parents.get(event);
16602
+ parents.delete(event);
16603
+ startTimes.delete(event);
16604
+ if (!parent) {
16605
+ return;
16606
+ }
16607
+ updateHarnessTurn(parent, {
16608
+ error: toLoggedError(event.error),
16609
+ output: null
16610
+ });
16611
+ endHarnessTurn(parent);
16612
+ }
16613
+ };
16614
+ channel2.subscribe(handlers);
16615
+ return () => {
16616
+ unbindParentStore();
16617
+ channel2.unsubscribe(handlers);
16618
+ };
16619
+ }
15983
16620
  function subscribeToAISDKV7TelemetryDispatcher() {
15984
16621
  const channel2 = aiSDKChannels.v7CreateTelemetryDispatcher.tracingChannel();
15985
16622
  const telemetry = braintrustAISDKTelemetry();
@@ -16432,7 +17069,13 @@ function prepareAISDKCallInput(params, event, span, defaultDenyOutputPaths, chil
16432
17069
  metadata
16433
17070
  };
16434
17071
  }
16435
- function prepareAISDKHarnessAgentInput(params, self) {
17072
+ function prepareAISDKHarnessAgentInput(params, self, span) {
17073
+ if (span) {
17074
+ registerHarnessTurnSpan({
17075
+ session: params.session,
17076
+ span
17077
+ });
17078
+ }
16436
17079
  if (isObject(self)) {
16437
17080
  try {
16438
17081
  if (isObject(self.settings)) {
@@ -16471,6 +17114,10 @@ function prepareAISDKHarnessAgentInput(params, self) {
16471
17114
  metadata
16472
17115
  };
16473
17116
  }
17117
+ function harnessSessionFromArguments(args) {
17118
+ const params = args[0];
17119
+ return isObject(params) ? params.session : void 0;
17120
+ }
16474
17121
  function prepareAISDKWorkflowAgentStreamInput(params, event, span, defaultDenyOutputPaths) {
16475
17122
  registerWorkflowAgentWrapperSpan(span);
16476
17123
  const { input } = processAISDKWorkflowAgentCallInput(params);
@@ -16918,19 +17565,22 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
16918
17565
  activeEntry.openSpans.delete(span);
16919
17566
  }
16920
17567
  },
16921
- {
16922
- name: "doGenerate",
16923
- spanAttributes: {
16924
- type: "llm" /* LLM */
17568
+ withSpanInstrumentationName(
17569
+ {
17570
+ name: "doGenerate",
17571
+ spanAttributes: {
17572
+ type: "llm" /* LLM */
17573
+ },
17574
+ event: buildAISDKModelStartEvent(
17575
+ callOptions,
17576
+ activeEntry.baseMetadata,
17577
+ {
17578
+ workflowAgent: activeEntry.childTracingOptions.workflowAgent
17579
+ }
17580
+ )
16925
17581
  },
16926
- event: buildAISDKModelStartEvent(
16927
- callOptions,
16928
- activeEntry.baseMetadata,
16929
- {
16930
- workflowAgent: activeEntry.childTracingOptions.workflowAgent
16931
- }
16932
- )
16933
- }
17582
+ INSTRUMENTATION_NAMES.AI_SDK
17583
+ )
16934
17584
  );
16935
17585
  };
16936
17586
  if (originalDoStream) {
@@ -16940,19 +17590,24 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
16940
17590
  return Reflect.apply(originalDoStream, resolvedModel, [callOptions]);
16941
17591
  }
16942
17592
  closeOpenAISDKModelPatchSpans(activeEntry);
16943
- const span = activeEntry.parentSpan.startSpan({
16944
- name: "doStream",
16945
- spanAttributes: {
16946
- type: "llm" /* LLM */
16947
- },
16948
- event: buildAISDKModelStartEvent(
16949
- callOptions,
16950
- activeEntry.baseMetadata,
17593
+ const span = activeEntry.parentSpan.startSpan(
17594
+ withSpanInstrumentationName(
16951
17595
  {
16952
- workflowAgent: activeEntry.childTracingOptions.workflowAgent
16953
- }
17596
+ name: "doStream",
17597
+ spanAttributes: {
17598
+ type: "llm" /* LLM */
17599
+ },
17600
+ event: buildAISDKModelStartEvent(
17601
+ callOptions,
17602
+ activeEntry.baseMetadata,
17603
+ {
17604
+ workflowAgent: activeEntry.childTracingOptions.workflowAgent
17605
+ }
17606
+ )
17607
+ },
17608
+ INSTRUMENTATION_NAMES.AI_SDK
16954
17609
  )
16955
- });
17610
+ );
16956
17611
  activeEntry.openSpans.add(span);
16957
17612
  const streamStartTime = getCurrentUnixTimestamp();
16958
17613
  const result = await withCurrent(
@@ -17124,12 +17779,17 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
17124
17779
  }
17125
17780
  if (isAsyncGenerator(result)) {
17126
17781
  return (async function* () {
17127
- const span = activeEntry.parentSpan.startSpan({
17128
- name: activeEntry.name,
17129
- spanAttributes: {
17130
- type: "tool" /* TOOL */
17131
- }
17132
- });
17782
+ const span = activeEntry.parentSpan.startSpan(
17783
+ withSpanInstrumentationName(
17784
+ {
17785
+ name: activeEntry.name,
17786
+ spanAttributes: {
17787
+ type: "tool" /* TOOL */
17788
+ }
17789
+ },
17790
+ INSTRUMENTATION_NAMES.AI_SDK
17791
+ )
17792
+ );
17133
17793
  span.log({ input: serializeToolExecutionInput(args) });
17134
17794
  try {
17135
17795
  let lastValue;
@@ -17153,12 +17813,15 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
17153
17813
  span.log({ output: awaitedResult });
17154
17814
  return awaitedResult;
17155
17815
  },
17156
- {
17157
- name: activeEntry.name,
17158
- spanAttributes: {
17159
- type: "tool" /* TOOL */
17160
- }
17161
- }
17816
+ withSpanInstrumentationName(
17817
+ {
17818
+ name: activeEntry.name,
17819
+ spanAttributes: {
17820
+ type: "tool" /* TOOL */
17821
+ }
17822
+ },
17823
+ INSTRUMENTATION_NAMES.AI_SDK
17824
+ )
17162
17825
  );
17163
17826
  };
17164
17827
  cleanup.push(() => {
@@ -17317,6 +17980,8 @@ function patchAISDKStreamingResult(args) {
17317
17980
  defaultDenyOutputPaths,
17318
17981
  endEvent,
17319
17982
  onComplete,
17983
+ onCancel,
17984
+ onError,
17320
17985
  result,
17321
17986
  resolvePromiseUsage,
17322
17987
  span,
@@ -17328,14 +17993,43 @@ function patchAISDKStreamingResult(args) {
17328
17993
  const resultRecord = result;
17329
17994
  attachKnownResultPromiseHandlers(resultRecord);
17330
17995
  let finalized = false;
17331
- const finalize = () => {
17996
+ const finalize = (outcome) => {
17332
17997
  if (finalized) {
17333
17998
  return;
17334
17999
  }
17335
18000
  finalized = true;
17336
- finalizeAISDKChildTracing(endEvent);
17337
- span.end();
17338
- onComplete?.();
18001
+ try {
18002
+ finalizeAISDKChildTracing(endEvent);
18003
+ } catch (error) {
18004
+ debugLogger.error("Error finalizing AI SDK child tracing:", error);
18005
+ }
18006
+ try {
18007
+ span.end();
18008
+ } catch (error) {
18009
+ debugLogger.error("Error ending AI SDK streaming span:", error);
18010
+ }
18011
+ if (outcome && "error" in outcome) {
18012
+ try {
18013
+ onError?.(outcome.error);
18014
+ } catch (error) {
18015
+ debugLogger.error("Error in AI SDK streaming error hook:", error);
18016
+ }
18017
+ } else if (outcome) {
18018
+ try {
18019
+ onComplete?.(outcome);
18020
+ } catch (error) {
18021
+ debugLogger.error("Error in AI SDK streaming completion hook:", error);
18022
+ }
18023
+ } else {
18024
+ try {
18025
+ onCancel?.();
18026
+ } catch (error) {
18027
+ debugLogger.error(
18028
+ "Error in AI SDK streaming cancellation hook:",
18029
+ error
18030
+ );
18031
+ }
18032
+ }
17339
18033
  };
17340
18034
  let outputLogged = false;
17341
18035
  const logStreamingOutput = async (firstChunkTime) => {
@@ -17369,15 +18063,29 @@ function patchAISDKStreamingResult(args) {
17369
18063
  resolveDenyOutputPaths(endEvent, defaultDenyOutputPaths)
17370
18064
  );
17371
18065
  const metadata = buildResolvedMetadataPayload(result).metadata;
17372
- span.log({
17373
- output,
17374
- ...metadata ? { metadata } : {},
17375
- metrics
17376
- });
18066
+ try {
18067
+ span.log({
18068
+ output,
18069
+ ...metadata ? { metadata } : {},
18070
+ metrics
18071
+ });
18072
+ } catch (error) {
18073
+ debugLogger.error("Error logging AI SDK streaming output:", error);
18074
+ }
18075
+ finalize({ metrics, output });
17377
18076
  } catch (error) {
17378
- span.log({ error: toLoggedError(error) });
17379
- } finally {
17380
- finalize();
18077
+ const loggedError = toLoggedError(error);
18078
+ try {
18079
+ span.log({ error: loggedError });
18080
+ } catch (loggingError) {
18081
+ debugLogger.error(
18082
+ "Error logging AI SDK streaming failure:",
18083
+ loggingError
18084
+ );
18085
+ }
18086
+ finalize({
18087
+ error: error instanceof Error ? error : new Error(String(loggedError))
18088
+ });
17381
18089
  }
17382
18090
  };
17383
18091
  const createAsyncIterableHooks = () => {
@@ -17394,11 +18102,16 @@ function patchAISDKStreamingResult(args) {
17394
18102
  onError: (error) => {
17395
18103
  if (!outputLogged) {
17396
18104
  outputLogged = true;
17397
- span.log({
17398
- error: error.message
17399
- });
18105
+ try {
18106
+ span.log({ error });
18107
+ } catch (loggingError) {
18108
+ debugLogger.error(
18109
+ "Error logging AI SDK stream failure:",
18110
+ loggingError
18111
+ );
18112
+ }
17400
18113
  }
17401
- finalize();
18114
+ finalize({ error });
17402
18115
  },
17403
18116
  onCancel: finalize
17404
18117
  };
@@ -17484,8 +18197,18 @@ function patchAISDKStreamingResult(args) {
17484
18197
  }
17485
18198
  controller.enqueue(value);
17486
18199
  } catch (error) {
17487
- span.log({ error: toLoggedError(error) });
17488
- finalize();
18200
+ const loggedError = toLoggedError(error);
18201
+ try {
18202
+ span.log({ error: loggedError });
18203
+ } catch (loggingError) {
18204
+ debugLogger.error(
18205
+ "Error logging AI SDK base stream failure:",
18206
+ loggingError
18207
+ );
18208
+ }
18209
+ finalize({
18210
+ error: error instanceof Error ? error : new Error(String(loggedError))
18211
+ });
17489
18212
  controller.error(error);
17490
18213
  }
17491
18214
  },
@@ -18274,7 +18997,8 @@ var claudeAgentSDKChannels = defineChannels(
18274
18997
  channelName: "query",
18275
18998
  kind: "sync-stream"
18276
18999
  })
18277
- }
19000
+ },
19001
+ { instrumentationName: INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK }
18278
19002
  );
18279
19003
 
18280
19004
  // src/instrumentation/plugins/claude-agent-sdk-instrumentation-constants.ts
@@ -18422,22 +19146,27 @@ function wrapLocalClaudeToolHandler(handler, getMetadata) {
18422
19146
  const spanName = metadata.serverName ? `tool: ${metadata.serverName}/${metadata.toolName}` : `tool: ${metadata.toolName}`;
18423
19147
  const runWithResolvedParent = async () => {
18424
19148
  const parent = toolUseId && localToolParentResolver ? await localToolParentResolver(toolUseId).catch(() => void 0) : void 0;
18425
- const span = startSpan({
18426
- event: {
18427
- input: handlerArgs[0],
18428
- metadata: {
18429
- "claude_agent_sdk.raw_tool_name": rawToolName,
18430
- "gen_ai.tool.name": metadata.toolName,
18431
- ...toolUseId && { "gen_ai.tool.call.id": toolUseId },
18432
- ...metadata.serverName && {
18433
- "mcp.server": metadata.serverName
18434
- }
18435
- }
18436
- },
18437
- name: spanName,
18438
- ...parent && { parent },
18439
- spanAttributes: { type: "tool" /* TOOL */ }
18440
- });
19149
+ const span = startSpan(
19150
+ withSpanInstrumentationName(
19151
+ {
19152
+ event: {
19153
+ input: handlerArgs[0],
19154
+ metadata: {
19155
+ "claude_agent_sdk.raw_tool_name": rawToolName,
19156
+ "gen_ai.tool.name": metadata.toolName,
19157
+ ...toolUseId && { "gen_ai.tool.call.id": toolUseId },
19158
+ ...metadata.serverName && {
19159
+ "mcp.server": metadata.serverName
19160
+ }
19161
+ }
19162
+ },
19163
+ name: spanName,
19164
+ ...parent && { parent },
19165
+ spanAttributes: { type: "tool" /* TOOL */ }
19166
+ },
19167
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
19168
+ )
19169
+ );
18441
19170
  const runHandler = () => Reflect.apply(handler, this, handlerArgs);
18442
19171
  const finalizeSuccess = (result) => {
18443
19172
  span.log({ output: result });
@@ -18762,14 +19491,19 @@ async function createLLMSpanForMessages(messages, promptMessages, conversationHi
18762
19491
  ).filter(
18763
19492
  (c) => c !== void 0
18764
19493
  );
18765
- const span = existingSpan ?? startSpan({
18766
- name: "anthropic.messages.create",
18767
- parent: parentSpan,
18768
- spanAttributes: {
18769
- type: "llm" /* LLM */
18770
- },
18771
- startTime
18772
- });
19494
+ const span = existingSpan ?? startSpan(
19495
+ withSpanInstrumentationName(
19496
+ {
19497
+ name: "anthropic.messages.create",
19498
+ parent: parentSpan,
19499
+ spanAttributes: {
19500
+ type: "llm" /* LLM */
19501
+ },
19502
+ startTime
19503
+ },
19504
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
19505
+ )
19506
+ );
18773
19507
  span.log({
18774
19508
  input,
18775
19509
  metadata: model ? { model } : void 0,
@@ -18872,25 +19606,30 @@ function createToolTracingHooks(resolveParentSpan, activeToolSpans, mcpServers,
18872
19606
  return {};
18873
19607
  }
18874
19608
  const parsed = parseToolName(input.tool_name);
18875
- const toolSpan = startSpan({
18876
- event: {
18877
- input: input.tool_input,
18878
- metadata: {
18879
- "claude_agent_sdk.cwd": input.cwd,
18880
- "claude_agent_sdk.raw_tool_name": parsed.rawToolName,
18881
- "claude_agent_sdk.session_id": input.session_id,
18882
- "gen_ai.tool.call.id": toolUseID,
18883
- "gen_ai.tool.name": parsed.toolName,
18884
- ...parsed.mcpServer && { "mcp.server": parsed.mcpServer },
18885
- ...getMcpServerMetadata(parsed.mcpServer, mcpServers)
18886
- }
18887
- },
18888
- name: parsed.displayName,
18889
- parent: await resolveParentSpan(toolUseID, {
18890
- agentId: input.agent_id
18891
- }),
18892
- spanAttributes: { type: "tool" /* TOOL */ }
18893
- });
19609
+ const toolSpan = startSpan(
19610
+ withSpanInstrumentationName(
19611
+ {
19612
+ event: {
19613
+ input: input.tool_input,
19614
+ metadata: {
19615
+ "claude_agent_sdk.cwd": input.cwd,
19616
+ "claude_agent_sdk.raw_tool_name": parsed.rawToolName,
19617
+ "claude_agent_sdk.session_id": input.session_id,
19618
+ "gen_ai.tool.call.id": toolUseID,
19619
+ "gen_ai.tool.name": parsed.toolName,
19620
+ ...parsed.mcpServer && { "mcp.server": parsed.mcpServer },
19621
+ ...getMcpServerMetadata(parsed.mcpServer, mcpServers)
19622
+ }
19623
+ },
19624
+ name: parsed.displayName,
19625
+ parent: await resolveParentSpan(toolUseID, {
19626
+ agentId: input.agent_id
19627
+ }),
19628
+ spanAttributes: { type: "tool" /* TOOL */ }
19629
+ },
19630
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
19631
+ )
19632
+ );
18894
19633
  activeToolSpans.set(toolUseID, toolSpan);
18895
19634
  return {};
18896
19635
  };
@@ -19256,14 +19995,19 @@ async function ensureSubAgentSpan(subAgentDetailsByToolUseId, rootSpan, activeTo
19256
19995
  const spanName = formatSubAgentSpanName(details);
19257
19996
  const parentToolSpan = activeToolSpans.get(parentToolUseId);
19258
19997
  const parentSpan = parentToolSpan ? await parentToolSpan.export() : await rootSpan.export();
19259
- const subAgentSpan = startSpan({
19260
- event: {
19261
- metadata: subAgentDetailsToMetadata(details)
19262
- },
19263
- name: spanName,
19264
- parent: parentSpan,
19265
- spanAttributes: { type: "task" /* TASK */ }
19266
- });
19998
+ const subAgentSpan = startSpan(
19999
+ withSpanInstrumentationName(
20000
+ {
20001
+ event: {
20002
+ metadata: subAgentDetailsToMetadata(details)
20003
+ },
20004
+ name: spanName,
20005
+ parent: parentSpan,
20006
+ spanAttributes: { type: "task" /* TASK */ }
20007
+ },
20008
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
20009
+ )
20010
+ );
19267
20011
  subAgentSpans.set(parentToolUseId, subAgentSpan);
19268
20012
  return subAgentSpan;
19269
20013
  }
@@ -19284,14 +20028,19 @@ async function ensureActiveLlmSpanForParentToolUse(rootSpan, activeLlmSpansByPar
19284
20028
  );
19285
20029
  llmParentSpan = await subAgentSpan.export();
19286
20030
  }
19287
- const llmSpan = startSpan({
19288
- name: "anthropic.messages.create",
19289
- parent: llmParentSpan,
19290
- spanAttributes: {
19291
- type: "llm" /* LLM */
19292
- },
19293
- startTime
19294
- });
20031
+ const llmSpan = startSpan(
20032
+ withSpanInstrumentationName(
20033
+ {
20034
+ name: "anthropic.messages.create",
20035
+ parent: llmParentSpan,
20036
+ spanAttributes: {
20037
+ type: "llm" /* LLM */
20038
+ },
20039
+ startTime
20040
+ },
20041
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
20042
+ )
20043
+ );
19295
20044
  activeLlmSpansByParentToolUse.set(parentKey, llmSpan);
19296
20045
  return llmSpan;
19297
20046
  }
@@ -19560,12 +20309,17 @@ var ClaudeAgentSDKPlugin = class extends BasePlugin {
19560
20309
  }
19561
20310
  })();
19562
20311
  }
19563
- const span = startSpan({
19564
- name: "Claude Agent",
19565
- spanAttributes: {
19566
- type: "task" /* TASK */
19567
- }
19568
- });
20312
+ const span = startSpan(
20313
+ withSpanInstrumentationName(
20314
+ {
20315
+ name: "Claude Agent",
20316
+ spanAttributes: {
20317
+ type: "task" /* TASK */
20318
+ }
20319
+ },
20320
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
20321
+ )
20322
+ );
19569
20323
  const startTime = getCurrentUnixTimestamp();
19570
20324
  try {
19571
20325
  span.log({
@@ -19730,24 +20484,28 @@ var ClaudeAgentSDKPlugin = class extends BasePlugin {
19730
20484
  };
19731
20485
 
19732
20486
  // src/instrumentation/plugins/cursor-sdk-channels.ts
19733
- var cursorSDKChannels = defineChannels("@cursor/sdk", {
19734
- create: channel({
19735
- channelName: "Agent.create",
19736
- kind: "async"
19737
- }),
19738
- resume: channel({
19739
- channelName: "Agent.resume",
19740
- kind: "async"
19741
- }),
19742
- prompt: channel({
19743
- channelName: "Agent.prompt",
19744
- kind: "async"
19745
- }),
19746
- send: channel({
19747
- channelName: "agent.send",
19748
- kind: "async"
19749
- })
19750
- });
20487
+ var cursorSDKChannels = defineChannels(
20488
+ "@cursor/sdk",
20489
+ {
20490
+ create: channel({
20491
+ channelName: "Agent.create",
20492
+ kind: "async"
20493
+ }),
20494
+ resume: channel({
20495
+ channelName: "Agent.resume",
20496
+ kind: "async"
20497
+ }),
20498
+ prompt: channel({
20499
+ channelName: "Agent.prompt",
20500
+ kind: "async"
20501
+ }),
20502
+ send: channel({
20503
+ channelName: "agent.send",
20504
+ kind: "async"
20505
+ })
20506
+ },
20507
+ { instrumentationName: INSTRUMENTATION_NAMES.CURSOR_SDK }
20508
+ );
19751
20509
 
19752
20510
  // src/instrumentation/plugins/cursor-sdk-plugin.ts
19753
20511
  var PATCHED_AGENT = /* @__PURE__ */ Symbol.for("braintrust.cursor-sdk.auto-patched-agent");
@@ -19799,10 +20557,15 @@ var CursorSDKPlugin = class extends BasePlugin {
19799
20557
  provider: "cursor",
19800
20558
  ...event.moduleVersion ? { "cursor_sdk.version": event.moduleVersion } : {}
19801
20559
  };
19802
- const span = startSpan({
19803
- name: "Cursor Agent",
19804
- spanAttributes: { type: "task" /* TASK */ }
19805
- });
20560
+ const span = startSpan(
20561
+ withSpanInstrumentationName(
20562
+ {
20563
+ name: "Cursor Agent",
20564
+ spanAttributes: { type: "task" /* TASK */ }
20565
+ },
20566
+ INSTRUMENTATION_NAMES.CURSOR_SDK
20567
+ )
20568
+ );
19806
20569
  const startTime = getCurrentUnixTimestamp();
19807
20570
  safeLog2(span, {
19808
20571
  input: sanitizeUserMessage(message),
@@ -19864,10 +20627,15 @@ var CursorSDKPlugin = class extends BasePlugin {
19864
20627
  provider: "cursor",
19865
20628
  ...event.moduleVersion ? { "cursor_sdk.version": event.moduleVersion } : {}
19866
20629
  };
19867
- const span = startSpan({
19868
- name: "Cursor Agent",
19869
- spanAttributes: { type: "task" /* TASK */ }
19870
- });
20630
+ const span = startSpan(
20631
+ withSpanInstrumentationName(
20632
+ {
20633
+ name: "Cursor Agent",
20634
+ spanAttributes: { type: "task" /* TASK */ }
20635
+ },
20636
+ INSTRUMENTATION_NAMES.CURSOR_SDK
20637
+ )
20638
+ );
19871
20639
  const startTime = getCurrentUnixTimestamp();
19872
20640
  safeLog2(span, {
19873
20641
  input: sanitizeUserMessage(message),
@@ -20314,29 +21082,39 @@ async function startToolSpan(state, args) {
20314
21082
  if (args.truncated?.result !== void 0) {
20315
21083
  metadata["cursor_sdk.tool.result_truncated"] = args.truncated.result;
20316
21084
  }
20317
- const span = startSpan({
20318
- event: {
20319
- input: args.args,
20320
- metadata
20321
- },
20322
- name: `tool: ${name}`,
20323
- parent: await state.span.export(),
20324
- spanAttributes: { type: "tool" /* TOOL */ }
20325
- });
21085
+ const span = startSpan(
21086
+ withSpanInstrumentationName(
21087
+ {
21088
+ event: {
21089
+ input: args.args,
21090
+ metadata
21091
+ },
21092
+ name: `tool: ${name}`,
21093
+ parent: await state.span.export(),
21094
+ spanAttributes: { type: "tool" /* TOOL */ }
21095
+ },
21096
+ INSTRUMENTATION_NAMES.CURSOR_SDK
21097
+ )
21098
+ );
20326
21099
  let subAgentSpan;
20327
21100
  if (isSubAgentToolName(name)) {
20328
- subAgentSpan = startSpan({
20329
- event: {
20330
- input: args.args,
20331
- metadata: {
20332
- "cursor_sdk.subagent.tool_call_id": args.callId,
20333
- "gen_ai.tool.name": name
20334
- }
20335
- },
20336
- name: formatSubAgentSpanName2(args.toolCall, args.args),
20337
- parent: await span.export(),
20338
- spanAttributes: { type: "task" /* TASK */ }
20339
- });
21101
+ subAgentSpan = startSpan(
21102
+ withSpanInstrumentationName(
21103
+ {
21104
+ event: {
21105
+ input: args.args,
21106
+ metadata: {
21107
+ "cursor_sdk.subagent.tool_call_id": args.callId,
21108
+ "gen_ai.tool.name": name
21109
+ }
21110
+ },
21111
+ name: formatSubAgentSpanName2(args.toolCall, args.args),
21112
+ parent: await span.export(),
21113
+ spanAttributes: { type: "task" /* TASK */ }
21114
+ },
21115
+ INSTRUMENTATION_NAMES.CURSOR_SDK
21116
+ )
21117
+ );
20340
21118
  }
20341
21119
  return { span, subAgentSpan };
20342
21120
  }
@@ -20595,24 +21373,28 @@ function cleanMetrics2(metrics) {
20595
21373
  }
20596
21374
 
20597
21375
  // src/instrumentation/plugins/openai-agents-channels.ts
20598
- var openAIAgentsCoreChannels = defineChannels("@openai/agents-core", {
20599
- onTraceStart: channel({
20600
- channelName: "tracing.processor.onTraceStart",
20601
- kind: "async"
20602
- }),
20603
- onTraceEnd: channel({
20604
- channelName: "tracing.processor.onTraceEnd",
20605
- kind: "async"
20606
- }),
20607
- onSpanStart: channel({
20608
- channelName: "tracing.processor.onSpanStart",
20609
- kind: "async"
20610
- }),
20611
- onSpanEnd: channel({
20612
- channelName: "tracing.processor.onSpanEnd",
20613
- kind: "async"
20614
- })
20615
- });
21376
+ var openAIAgentsCoreChannels = defineChannels(
21377
+ "@openai/agents-core",
21378
+ {
21379
+ onTraceStart: channel({
21380
+ channelName: "tracing.processor.onTraceStart",
21381
+ kind: "async"
21382
+ }),
21383
+ onTraceEnd: channel({
21384
+ channelName: "tracing.processor.onTraceEnd",
21385
+ kind: "async"
21386
+ }),
21387
+ onSpanStart: channel({
21388
+ channelName: "tracing.processor.onSpanStart",
21389
+ kind: "async"
21390
+ }),
21391
+ onSpanEnd: channel({
21392
+ channelName: "tracing.processor.onSpanEnd",
21393
+ kind: "async"
21394
+ })
21395
+ },
21396
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENAI_AGENTS }
21397
+ );
20616
21398
 
20617
21399
  // src/instrumentation/plugins/openai-agents-trace-processor.ts
20618
21400
  function isSpanData(spanData, type) {
@@ -20728,16 +21510,19 @@ var OpenAIAgentsTraceProcessor = class _OpenAIAgentsTraceProcessor {
20728
21510
  this.evictOldestTrace();
20729
21511
  }
20730
21512
  const current = currentSpan();
20731
- const span = current && current !== NOOP_SPAN ? current.startSpan({
20732
- name: trace.name,
20733
- type: "task" /* TASK */
20734
- }) : this.logger ? this.logger.startSpan({
20735
- name: trace.name,
20736
- type: "task" /* TASK */
20737
- }) : startSpan({
20738
- name: trace.name,
20739
- type: "task" /* TASK */
20740
- });
21513
+ const spanArgs = withSpanInstrumentationName(
21514
+ {
21515
+ name: trace.name,
21516
+ type: "task" /* TASK */
21517
+ },
21518
+ INSTRUMENTATION_NAMES.OPENAI_AGENTS
21519
+ );
21520
+ const span = current && current !== NOOP_SPAN ? current.startSpan(spanArgs) : this.logger ? this.logger.startSpan(spanArgs) : startSpan(
21521
+ withSpanInstrumentationName(
21522
+ spanArgs,
21523
+ INSTRUMENTATION_NAMES.OPENAI_AGENTS
21524
+ )
21525
+ );
20741
21526
  span.log({
20742
21527
  input: "Agent workflow started",
20743
21528
  metadata: {
@@ -20788,10 +21573,15 @@ var OpenAIAgentsTraceProcessor = class _OpenAIAgentsTraceProcessor {
20788
21573
  if (!parentSpan) {
20789
21574
  return Promise.resolve();
20790
21575
  }
20791
- const childSpan = parentSpan.startSpan({
20792
- name: spanNameFromAgents(span),
20793
- type: spanTypeFromAgents(span)
20794
- });
21576
+ const childSpan = parentSpan.startSpan(
21577
+ withSpanInstrumentationName(
21578
+ {
21579
+ name: spanNameFromAgents(span),
21580
+ type: spanTypeFromAgents(span)
21581
+ },
21582
+ INSTRUMENTATION_NAMES.OPENAI_AGENTS
21583
+ )
21584
+ );
20795
21585
  traceData.childSpans.set(span.spanId, childSpan);
20796
21586
  return Promise.resolve();
20797
21587
  }
@@ -21056,24 +21846,28 @@ var OpenAIAgentsPlugin = class extends BasePlugin {
21056
21846
  };
21057
21847
 
21058
21848
  // src/instrumentation/plugins/google-genai-channels.ts
21059
- var googleGenAIChannels = defineChannels("@google/genai", {
21060
- generateContent: channel({
21061
- channelName: "models.generateContent",
21062
- kind: "async"
21063
- }),
21064
- generateContentStream: channel({
21065
- channelName: "models.generateContentStream",
21066
- kind: "async"
21067
- }),
21068
- embedContent: channel({
21069
- channelName: "models.embedContent",
21070
- kind: "async"
21071
- }),
21072
- interactionsCreate: channel({
21073
- channelName: "interactions.create",
21074
- kind: "async"
21075
- })
21076
- });
21849
+ var googleGenAIChannels = defineChannels(
21850
+ "@google/genai",
21851
+ {
21852
+ generateContent: channel({
21853
+ channelName: "models.generateContent",
21854
+ kind: "async"
21855
+ }),
21856
+ generateContentStream: channel({
21857
+ channelName: "models.generateContentStream",
21858
+ kind: "async"
21859
+ }),
21860
+ embedContent: channel({
21861
+ channelName: "models.embedContent",
21862
+ kind: "async"
21863
+ }),
21864
+ interactionsCreate: channel({
21865
+ channelName: "interactions.create",
21866
+ kind: "async"
21867
+ })
21868
+ },
21869
+ { instrumentationName: INSTRUMENTATION_NAMES.GOOGLE_GENAI }
21870
+ );
21077
21871
 
21078
21872
  // src/instrumentation/plugins/google-genai-plugin.ts
21079
21873
  var GOOGLE_GENAI_INTERNAL_CONTEXT = {
@@ -21111,13 +21905,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
21111
21905
  const params = event.arguments[0];
21112
21906
  const input = serializeGenerateContentInput(params);
21113
21907
  const metadata = extractGenerateContentMetadata(params);
21114
- const span = startSpan({
21115
- name: "generate_content",
21116
- spanAttributes: {
21117
- type: "llm" /* LLM */
21118
- },
21119
- event: createWrapperParityEvent({ input, metadata })
21120
- });
21908
+ const span = startSpan(
21909
+ withSpanInstrumentationName(
21910
+ {
21911
+ name: "generate_content",
21912
+ spanAttributes: {
21913
+ type: "llm" /* LLM */
21914
+ },
21915
+ event: createWrapperParityEvent({ input, metadata })
21916
+ },
21917
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
21918
+ )
21919
+ );
21121
21920
  return {
21122
21921
  span,
21123
21922
  startTime: getCurrentUnixTimestamp()
@@ -21130,13 +21929,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
21130
21929
  const params = event.arguments[0];
21131
21930
  const input = serializeGenerateContentInput(params);
21132
21931
  const metadata = extractGenerateContentMetadata(params);
21133
- const span = startSpan({
21134
- name: "generate_content",
21135
- spanAttributes: {
21136
- type: "llm" /* LLM */
21137
- },
21138
- event: createWrapperParityEvent({ input, metadata })
21139
- });
21932
+ const span = startSpan(
21933
+ withSpanInstrumentationName(
21934
+ {
21935
+ name: "generate_content",
21936
+ spanAttributes: {
21937
+ type: "llm" /* LLM */
21938
+ },
21939
+ event: createWrapperParityEvent({ input, metadata })
21940
+ },
21941
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
21942
+ )
21943
+ );
21140
21944
  return {
21141
21945
  span,
21142
21946
  startTime: getCurrentUnixTimestamp()
@@ -21212,13 +22016,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
21212
22016
  const params = event.arguments[0];
21213
22017
  const input = serializeEmbedContentInput(params);
21214
22018
  const metadata = extractEmbedContentMetadata(params);
21215
- const span = startSpan({
21216
- name: "embed_content",
21217
- spanAttributes: {
21218
- type: "llm" /* LLM */
21219
- },
21220
- event: createWrapperParityEvent({ input, metadata })
21221
- });
22019
+ const span = startSpan(
22020
+ withSpanInstrumentationName(
22021
+ {
22022
+ name: "embed_content",
22023
+ spanAttributes: {
22024
+ type: "llm" /* LLM */
22025
+ },
22026
+ event: createWrapperParityEvent({ input, metadata })
22027
+ },
22028
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
22029
+ )
22030
+ );
21222
22031
  return {
21223
22032
  span,
21224
22033
  startTime: getCurrentUnixTimestamp()
@@ -21231,13 +22040,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
21231
22040
  const params = event.arguments[0];
21232
22041
  const input = serializeEmbedContentInput(params);
21233
22042
  const metadata = extractEmbedContentMetadata(params);
21234
- const span = startSpan({
21235
- name: "embed_content",
21236
- spanAttributes: {
21237
- type: "llm" /* LLM */
21238
- },
21239
- event: createWrapperParityEvent({ input, metadata })
21240
- });
22043
+ const span = startSpan(
22044
+ withSpanInstrumentationName(
22045
+ {
22046
+ name: "embed_content",
22047
+ spanAttributes: {
22048
+ type: "llm" /* LLM */
22049
+ },
22050
+ event: createWrapperParityEvent({ input, metadata })
22051
+ },
22052
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
22053
+ )
22054
+ );
21241
22055
  return {
21242
22056
  span,
21243
22057
  startTime: getCurrentUnixTimestamp()
@@ -21348,16 +22162,21 @@ function patchGoogleGenAIStreamingResult(args) {
21348
22162
  const requestStartTime = startTime ?? getCurrentUnixTimestamp();
21349
22163
  const ensureSpan = () => {
21350
22164
  if (!span) {
21351
- span = startSpan({
21352
- name: "generate_content_stream",
21353
- spanAttributes: {
21354
- type: "llm" /* LLM */
21355
- },
21356
- event: {
21357
- input,
21358
- metadata
21359
- }
21360
- });
22165
+ span = startSpan(
22166
+ withSpanInstrumentationName(
22167
+ {
22168
+ name: "generate_content_stream",
22169
+ spanAttributes: {
22170
+ type: "llm" /* LLM */
22171
+ },
22172
+ event: {
22173
+ input,
22174
+ metadata
22175
+ }
22176
+ },
22177
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
22178
+ )
22179
+ );
21361
22180
  }
21362
22181
  return span;
21363
22182
  };
@@ -22125,28 +22944,32 @@ function tryToDict(obj) {
22125
22944
  }
22126
22945
 
22127
22946
  // src/instrumentation/plugins/huggingface-channels.ts
22128
- var huggingFaceChannels = defineChannels("@huggingface/inference", {
22129
- chatCompletion: channel({
22130
- channelName: "chatCompletion",
22131
- kind: "async"
22132
- }),
22133
- chatCompletionStream: channel({
22134
- channelName: "chatCompletionStream",
22135
- kind: "sync-stream"
22136
- }),
22137
- textGeneration: channel({
22138
- channelName: "textGeneration",
22139
- kind: "async"
22140
- }),
22141
- textGenerationStream: channel({
22142
- channelName: "textGenerationStream",
22143
- kind: "sync-stream"
22144
- }),
22145
- featureExtraction: channel({
22146
- channelName: "featureExtraction",
22147
- kind: "async"
22148
- })
22149
- });
22947
+ var huggingFaceChannels = defineChannels(
22948
+ "@huggingface/inference",
22949
+ {
22950
+ chatCompletion: channel({
22951
+ channelName: "chatCompletion",
22952
+ kind: "async"
22953
+ }),
22954
+ chatCompletionStream: channel({
22955
+ channelName: "chatCompletionStream",
22956
+ kind: "sync-stream"
22957
+ }),
22958
+ textGeneration: channel({
22959
+ channelName: "textGeneration",
22960
+ kind: "async"
22961
+ }),
22962
+ textGenerationStream: channel({
22963
+ channelName: "textGenerationStream",
22964
+ kind: "sync-stream"
22965
+ }),
22966
+ featureExtraction: channel({
22967
+ channelName: "featureExtraction",
22968
+ kind: "async"
22969
+ })
22970
+ },
22971
+ { instrumentationName: INSTRUMENTATION_NAMES.HUGGINGFACE }
22972
+ );
22150
22973
 
22151
22974
  // src/instrumentation/plugins/huggingface-plugin.ts
22152
22975
  var REQUEST_METADATA_ALLOWLIST = /* @__PURE__ */ new Set([
@@ -22573,20 +23396,24 @@ function extractTextGenerationStreamMetadata(chunks) {
22573
23396
  }
22574
23397
 
22575
23398
  // src/instrumentation/plugins/openrouter-agent-channels.ts
22576
- var openRouterAgentChannels = defineChannels("@openrouter/agent", {
22577
- callModel: channel({
22578
- channelName: "callModel",
22579
- kind: "sync-stream"
22580
- }),
22581
- callModelTurn: channel({
22582
- channelName: "callModel.turn",
22583
- kind: "async"
22584
- }),
22585
- toolExecute: channel({
22586
- channelName: "tool.execute",
22587
- kind: "async"
22588
- })
22589
- });
23399
+ var openRouterAgentChannels = defineChannels(
23400
+ "@openrouter/agent",
23401
+ {
23402
+ callModel: channel({
23403
+ channelName: "callModel",
23404
+ kind: "sync-stream"
23405
+ }),
23406
+ callModelTurn: channel({
23407
+ channelName: "callModel.turn",
23408
+ kind: "async"
23409
+ }),
23410
+ toolExecute: channel({
23411
+ channelName: "tool.execute",
23412
+ kind: "async"
23413
+ })
23414
+ },
23415
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENROUTER_AGENT }
23416
+ );
22590
23417
 
22591
23418
  // src/instrumentation/plugins/openrouter-agent-plugin.ts
22592
23419
  var OpenRouterAgentPlugin = class extends BasePlugin {
@@ -23356,38 +24183,40 @@ function normalizeError(error) {
23356
24183
  }
23357
24184
 
23358
24185
  // src/instrumentation/plugins/openrouter-channels.ts
23359
- var openRouterChannels = defineChannels("@openrouter/sdk", {
23360
- chatSend: channel({
23361
- channelName: "chat.send",
23362
- kind: "async"
23363
- }),
23364
- embeddingsGenerate: channel({
23365
- channelName: "embeddings.generate",
23366
- kind: "async"
23367
- }),
23368
- rerankRerank: channel(
23369
- {
24186
+ var openRouterChannels = defineChannels(
24187
+ "@openrouter/sdk",
24188
+ {
24189
+ chatSend: channel({
24190
+ channelName: "chat.send",
24191
+ kind: "async"
24192
+ }),
24193
+ embeddingsGenerate: channel({
24194
+ channelName: "embeddings.generate",
24195
+ kind: "async"
24196
+ }),
24197
+ rerankRerank: channel({
23370
24198
  channelName: "rerank.rerank",
23371
24199
  kind: "async"
23372
- }
23373
- ),
23374
- betaResponsesSend: channel({
23375
- channelName: "beta.responses.send",
23376
- kind: "async"
23377
- }),
23378
- callModel: channel({
23379
- channelName: "callModel",
23380
- kind: "sync-stream"
23381
- }),
23382
- callModelTurn: channel({
23383
- channelName: "callModel.turn",
23384
- kind: "async"
23385
- }),
23386
- toolExecute: channel({
23387
- channelName: "tool.execute",
23388
- kind: "async"
23389
- })
23390
- });
24200
+ }),
24201
+ betaResponsesSend: channel({
24202
+ channelName: "beta.responses.send",
24203
+ kind: "async"
24204
+ }),
24205
+ callModel: channel({
24206
+ channelName: "callModel",
24207
+ kind: "sync-stream"
24208
+ }),
24209
+ callModelTurn: channel({
24210
+ channelName: "callModel.turn",
24211
+ kind: "async"
24212
+ }),
24213
+ toolExecute: channel({
24214
+ channelName: "tool.execute",
24215
+ kind: "async"
24216
+ })
24217
+ },
24218
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENROUTER }
24219
+ );
23391
24220
 
23392
24221
  // src/instrumentation/plugins/openrouter-plugin.ts
23393
24222
  var OpenRouterPlugin = class extends BasePlugin {
@@ -24427,52 +25256,56 @@ function normalizeError2(error) {
24427
25256
  }
24428
25257
 
24429
25258
  // src/instrumentation/plugins/mistral-channels.ts
24430
- var mistralChannels = defineChannels("@mistralai/mistralai", {
24431
- chatComplete: channel({
24432
- channelName: "chat.complete",
24433
- kind: "async"
24434
- }),
24435
- chatStream: channel({
24436
- channelName: "chat.stream",
24437
- kind: "async"
24438
- }),
24439
- embeddingsCreate: channel({
24440
- channelName: "embeddings.create",
24441
- kind: "async"
24442
- }),
24443
- classifiersModerate: channel({
24444
- channelName: "classifiers.moderate",
24445
- kind: "async"
24446
- }),
24447
- classifiersModerateChat: channel({
24448
- channelName: "classifiers.moderateChat",
24449
- kind: "async"
24450
- }),
24451
- classifiersClassify: channel({
24452
- channelName: "classifiers.classify",
24453
- kind: "async"
24454
- }),
24455
- classifiersClassifyChat: channel({
24456
- channelName: "classifiers.classifyChat",
24457
- kind: "async"
24458
- }),
24459
- fimComplete: channel({
24460
- channelName: "fim.complete",
24461
- kind: "async"
24462
- }),
24463
- fimStream: channel({
24464
- channelName: "fim.stream",
24465
- kind: "async"
24466
- }),
24467
- agentsComplete: channel({
24468
- channelName: "agents.complete",
24469
- kind: "async"
24470
- }),
24471
- agentsStream: channel({
24472
- channelName: "agents.stream",
24473
- kind: "async"
24474
- })
24475
- });
25259
+ var mistralChannels = defineChannels(
25260
+ "@mistralai/mistralai",
25261
+ {
25262
+ chatComplete: channel({
25263
+ channelName: "chat.complete",
25264
+ kind: "async"
25265
+ }),
25266
+ chatStream: channel({
25267
+ channelName: "chat.stream",
25268
+ kind: "async"
25269
+ }),
25270
+ embeddingsCreate: channel({
25271
+ channelName: "embeddings.create",
25272
+ kind: "async"
25273
+ }),
25274
+ classifiersModerate: channel({
25275
+ channelName: "classifiers.moderate",
25276
+ kind: "async"
25277
+ }),
25278
+ classifiersModerateChat: channel({
25279
+ channelName: "classifiers.moderateChat",
25280
+ kind: "async"
25281
+ }),
25282
+ classifiersClassify: channel({
25283
+ channelName: "classifiers.classify",
25284
+ kind: "async"
25285
+ }),
25286
+ classifiersClassifyChat: channel({
25287
+ channelName: "classifiers.classifyChat",
25288
+ kind: "async"
25289
+ }),
25290
+ fimComplete: channel({
25291
+ channelName: "fim.complete",
25292
+ kind: "async"
25293
+ }),
25294
+ fimStream: channel({
25295
+ channelName: "fim.stream",
25296
+ kind: "async"
25297
+ }),
25298
+ agentsComplete: channel({
25299
+ channelName: "agents.complete",
25300
+ kind: "async"
25301
+ }),
25302
+ agentsStream: channel({
25303
+ channelName: "agents.stream",
25304
+ kind: "async"
25305
+ })
25306
+ },
25307
+ { instrumentationName: INSTRUMENTATION_NAMES.MISTRAL }
25308
+ );
24476
25309
 
24477
25310
  // src/instrumentation/plugins/mistral-plugin.ts
24478
25311
  var MistralPlugin = class extends BasePlugin {
@@ -25092,20 +25925,24 @@ function aggregateMistralStreamChunks(chunks) {
25092
25925
  }
25093
25926
 
25094
25927
  // src/instrumentation/plugins/google-adk-channels.ts
25095
- var googleADKChannels = defineChannels("@google/adk", {
25096
- runnerRunAsync: channel({
25097
- channelName: "runner.runAsync",
25098
- kind: "sync-stream"
25099
- }),
25100
- agentRunAsync: channel({
25101
- channelName: "agent.runAsync",
25102
- kind: "sync-stream"
25103
- }),
25104
- toolRunAsync: channel({
25105
- channelName: "tool.runAsync",
25106
- kind: "async"
25107
- })
25108
- });
25928
+ var googleADKChannels = defineChannels(
25929
+ "@google/adk",
25930
+ {
25931
+ runnerRunAsync: channel({
25932
+ channelName: "runner.runAsync",
25933
+ kind: "sync-stream"
25934
+ }),
25935
+ agentRunAsync: channel({
25936
+ channelName: "agent.runAsync",
25937
+ kind: "sync-stream"
25938
+ }),
25939
+ toolRunAsync: channel({
25940
+ channelName: "tool.runAsync",
25941
+ kind: "async"
25942
+ })
25943
+ },
25944
+ { instrumentationName: INSTRUMENTATION_NAMES.GOOGLE_ADK }
25945
+ );
25109
25946
 
25110
25947
  // src/instrumentation/plugins/google-adk-plugin.ts
25111
25948
  var GoogleADKPlugin = class extends BasePlugin {
@@ -25130,12 +25967,17 @@ var GoogleADKPlugin = class extends BasePlugin {
25130
25967
  const createState = (event) => {
25131
25968
  const params = event.arguments[0] ?? {};
25132
25969
  const contextKey = extractRunnerContextKey(params);
25133
- const span = startSpan({
25134
- name: "Google ADK Runner",
25135
- spanAttributes: {
25136
- type: "task" /* TASK */
25137
- }
25138
- });
25970
+ const span = startSpan(
25971
+ withSpanInstrumentationName(
25972
+ {
25973
+ name: "Google ADK Runner",
25974
+ spanAttributes: {
25975
+ type: "task" /* TASK */
25976
+ }
25977
+ },
25978
+ INSTRUMENTATION_NAMES.GOOGLE_ADK
25979
+ )
25980
+ );
25139
25981
  const startTime = getCurrentUnixTimestamp();
25140
25982
  try {
25141
25983
  const metadata = extractRunnerMetadata(params);
@@ -25221,18 +26063,23 @@ var GoogleADKPlugin = class extends BasePlugin {
25221
26063
  this.activeRunnerSpans
25222
26064
  );
25223
26065
  const contextKey = extractInvocationContextKey(parentContext);
25224
- const span = startSpan({
25225
- name: agentName ? `Agent: ${agentName}` : "Google ADK Agent",
25226
- spanAttributes: {
25227
- type: "task" /* TASK */
25228
- },
25229
- ...runnerParentSpan ? {
25230
- parentSpanIds: {
25231
- spanId: runnerParentSpan.spanId,
25232
- rootSpanId: runnerParentSpan.rootSpanId
25233
- }
25234
- } : {}
25235
- });
26066
+ const span = startSpan(
26067
+ withSpanInstrumentationName(
26068
+ {
26069
+ name: agentName ? `Agent: ${agentName}` : "Google ADK Agent",
26070
+ spanAttributes: {
26071
+ type: "task" /* TASK */
26072
+ },
26073
+ ...runnerParentSpan ? {
26074
+ parentSpanIds: {
26075
+ spanId: runnerParentSpan.spanId,
26076
+ rootSpanId: runnerParentSpan.rootSpanId
26077
+ }
26078
+ } : {}
26079
+ },
26080
+ INSTRUMENTATION_NAMES.GOOGLE_ADK
26081
+ )
26082
+ );
25236
26083
  const startTime = getCurrentUnixTimestamp();
25237
26084
  try {
25238
26085
  const metadata = {
@@ -25325,22 +26172,27 @@ var GoogleADKPlugin = class extends BasePlugin {
25325
26172
  this.activeAgentSpans,
25326
26173
  this.activeRunnerSpans
25327
26174
  );
25328
- const createSpan = () => startSpan({
25329
- name: toolName ? `tool: ${toolName}` : "Google ADK Tool",
25330
- spanAttributes: {
25331
- type: "tool" /* TOOL */
25332
- },
25333
- event: {
25334
- input: req.args,
25335
- metadata: {
25336
- provider: "google-adk",
25337
- ...toolName && { "google_adk.tool_name": toolName },
25338
- ...extractToolCallId(req) && {
25339
- "google_adk.tool_call_id": extractToolCallId(req)
26175
+ const createSpan = () => startSpan(
26176
+ withSpanInstrumentationName(
26177
+ {
26178
+ name: toolName ? `tool: ${toolName}` : "Google ADK Tool",
26179
+ spanAttributes: {
26180
+ type: "tool" /* TOOL */
26181
+ },
26182
+ event: {
26183
+ input: req.args,
26184
+ metadata: {
26185
+ provider: "google-adk",
26186
+ ...toolName && { "google_adk.tool_name": toolName },
26187
+ ...extractToolCallId(req) && {
26188
+ "google_adk.tool_call_id": extractToolCallId(req)
26189
+ }
26190
+ }
25340
26191
  }
25341
- }
25342
- }
25343
- });
26192
+ },
26193
+ INSTRUMENTATION_NAMES.GOOGLE_ADK
26194
+ )
26195
+ );
25344
26196
  const span = parentSpan ? withCurrent(parentSpan, () => createSpan()) : createSpan();
25345
26197
  const startTime = getCurrentUnixTimestamp();
25346
26198
  states.set(event, { span, startTime });
@@ -25739,24 +26591,28 @@ function cleanMetrics4(metrics) {
25739
26591
  }
25740
26592
 
25741
26593
  // src/instrumentation/plugins/cohere-channels.ts
25742
- var cohereChannels = defineChannels("cohere-ai", {
25743
- chat: channel({
25744
- channelName: "chat",
25745
- kind: "async"
25746
- }),
25747
- chatStream: channel({
25748
- channelName: "chatStream",
25749
- kind: "async"
25750
- }),
25751
- embed: channel({
25752
- channelName: "embed",
25753
- kind: "async"
25754
- }),
25755
- rerank: channel({
25756
- channelName: "rerank",
25757
- kind: "async"
25758
- })
25759
- });
26594
+ var cohereChannels = defineChannels(
26595
+ "cohere-ai",
26596
+ {
26597
+ chat: channel({
26598
+ channelName: "chat",
26599
+ kind: "async"
26600
+ }),
26601
+ chatStream: channel({
26602
+ channelName: "chatStream",
26603
+ kind: "async"
26604
+ }),
26605
+ embed: channel({
26606
+ channelName: "embed",
26607
+ kind: "async"
26608
+ }),
26609
+ rerank: channel({
26610
+ channelName: "rerank",
26611
+ kind: "async"
26612
+ })
26613
+ },
26614
+ { instrumentationName: INSTRUMENTATION_NAMES.COHERE }
26615
+ );
25760
26616
 
25761
26617
  // src/instrumentation/plugins/cohere-plugin.ts
25762
26618
  var CoherePlugin = class extends BasePlugin {
@@ -26425,18 +27281,20 @@ function aggregateCohereChatStreamChunks(chunks) {
26425
27281
  }
26426
27282
 
26427
27283
  // src/instrumentation/plugins/groq-channels.ts
26428
- var groqChannels = defineChannels("groq-sdk", {
26429
- chatCompletionsCreate: channel({
26430
- channelName: "chat.completions.create",
26431
- kind: "async"
26432
- }),
26433
- embeddingsCreate: channel(
26434
- {
27284
+ var groqChannels = defineChannels(
27285
+ "groq-sdk",
27286
+ {
27287
+ chatCompletionsCreate: channel({
27288
+ channelName: "chat.completions.create",
27289
+ kind: "async"
27290
+ }),
27291
+ embeddingsCreate: channel({
26435
27292
  channelName: "embeddings.create",
26436
27293
  kind: "async"
26437
- }
26438
- )
26439
- });
27294
+ })
27295
+ },
27296
+ { instrumentationName: INSTRUMENTATION_NAMES.GROQ }
27297
+ );
26440
27298
 
26441
27299
  // src/instrumentation/plugins/groq-plugin.ts
26442
27300
  var GroqPlugin = class extends BasePlugin {
@@ -26539,15 +27397,27 @@ var clientSendChannel = channel({
26539
27397
  channelName: "client.send",
26540
27398
  kind: "async"
26541
27399
  });
26542
- var bedrockRuntimeChannels = defineChannels("aws-bedrock-runtime", {
26543
- clientSend: clientSendChannel
26544
- });
26545
- var smithyCoreChannels = defineChannels("@smithy/core", {
26546
- clientSend: clientSendChannel
26547
- });
26548
- var smithyClientChannels = defineChannels("@smithy/smithy-client", {
26549
- clientSend: clientSendChannel
26550
- });
27400
+ var bedrockRuntimeChannels = defineChannels(
27401
+ "aws-bedrock-runtime",
27402
+ {
27403
+ clientSend: clientSendChannel
27404
+ },
27405
+ { instrumentationName: INSTRUMENTATION_NAMES.BEDROCK_RUNTIME }
27406
+ );
27407
+ var smithyCoreChannels = defineChannels(
27408
+ "@smithy/core",
27409
+ {
27410
+ clientSend: clientSendChannel
27411
+ },
27412
+ { instrumentationName: INSTRUMENTATION_NAMES.BEDROCK_RUNTIME }
27413
+ );
27414
+ var smithyClientChannels = defineChannels(
27415
+ "@smithy/smithy-client",
27416
+ {
27417
+ clientSend: clientSendChannel
27418
+ },
27419
+ { instrumentationName: INSTRUMENTATION_NAMES.BEDROCK_RUNTIME }
27420
+ );
26551
27421
 
26552
27422
  // src/instrumentation/plugins/bedrock-runtime-common.ts
26553
27423
  var BEDROCK_RUNTIME_COMMAND_OPERATIONS = {
@@ -27181,38 +28051,46 @@ function extractTextFromJsonLike(value) {
27181
28051
  }
27182
28052
 
27183
28053
  // src/instrumentation/plugins/genkit-channels.ts
27184
- var genkitChannels = defineChannels("@genkit-ai/ai", {
27185
- generate: channel({
27186
- channelName: "generate",
27187
- kind: "async"
27188
- }),
27189
- generateStream: channel({
27190
- channelName: "generateStream",
27191
- kind: "sync-stream"
27192
- }),
27193
- embed: channel({
27194
- channelName: "embed",
27195
- kind: "async"
27196
- }),
27197
- embedMany: channel({
27198
- channelName: "embedMany",
27199
- kind: "async"
27200
- }),
27201
- actionRun: channel({
27202
- channelName: "action.run",
27203
- kind: "async"
27204
- }),
27205
- actionStream: channel({
27206
- channelName: "action.stream",
27207
- kind: "sync-stream"
27208
- })
27209
- });
27210
- var genkitCoreChannels = defineChannels("@genkit-ai/core", {
27211
- actionSpan: channel({
27212
- channelName: "action.span",
27213
- kind: "async"
27214
- })
27215
- });
28054
+ var genkitChannels = defineChannels(
28055
+ "@genkit-ai/ai",
28056
+ {
28057
+ generate: channel({
28058
+ channelName: "generate",
28059
+ kind: "async"
28060
+ }),
28061
+ generateStream: channel({
28062
+ channelName: "generateStream",
28063
+ kind: "sync-stream"
28064
+ }),
28065
+ embed: channel({
28066
+ channelName: "embed",
28067
+ kind: "async"
28068
+ }),
28069
+ embedMany: channel({
28070
+ channelName: "embedMany",
28071
+ kind: "async"
28072
+ }),
28073
+ actionRun: channel({
28074
+ channelName: "action.run",
28075
+ kind: "async"
28076
+ }),
28077
+ actionStream: channel({
28078
+ channelName: "action.stream",
28079
+ kind: "sync-stream"
28080
+ })
28081
+ },
28082
+ { instrumentationName: INSTRUMENTATION_NAMES.GENKIT }
28083
+ );
28084
+ var genkitCoreChannels = defineChannels(
28085
+ "@genkit-ai/core",
28086
+ {
28087
+ actionSpan: channel({
28088
+ channelName: "action.span",
28089
+ kind: "async"
28090
+ })
28091
+ },
28092
+ { instrumentationName: INSTRUMENTATION_NAMES.GENKIT }
28093
+ );
27216
28094
 
27217
28095
  // src/instrumentation/plugins/genkit-plugin.ts
27218
28096
  var GenkitPlugin = class extends BasePlugin {
@@ -27397,12 +28275,17 @@ function startActionSpanState(args) {
27397
28275
  if (!shouldTraceAction(args.metadata, args.runStepName)) {
27398
28276
  return void 0;
27399
28277
  }
27400
- const span = startSpan({
27401
- name: actionSpanName(args.metadata, args.runStepName),
27402
- spanAttributes: {
27403
- type: actionSpanType(args.metadata)
27404
- }
27405
- });
28278
+ const span = startSpan(
28279
+ withSpanInstrumentationName(
28280
+ {
28281
+ name: actionSpanName(args.metadata, args.runStepName),
28282
+ spanAttributes: {
28283
+ type: actionSpanType(args.metadata)
28284
+ }
28285
+ },
28286
+ INSTRUMENTATION_NAMES.GENKIT
28287
+ )
28288
+ );
27406
28289
  const startTime = getCurrentUnixTimestamp();
27407
28290
  span.log({
27408
28291
  input: args.input,
@@ -27763,20 +28646,24 @@ function stringValue(value) {
27763
28646
  }
27764
28647
 
27765
28648
  // src/instrumentation/plugins/github-copilot-channels.ts
27766
- var gitHubCopilotChannels = defineChannels("@github/copilot-sdk", {
27767
- createSession: channel({
27768
- channelName: "client.createSession",
27769
- kind: "async"
27770
- }),
27771
- resumeSession: channel({
27772
- channelName: "client.resumeSession",
27773
- kind: "async"
27774
- }),
27775
- sendAndWait: channel({
27776
- channelName: "session.sendAndWait",
27777
- kind: "async"
27778
- })
27779
- });
28649
+ var gitHubCopilotChannels = defineChannels(
28650
+ "@github/copilot-sdk",
28651
+ {
28652
+ createSession: channel({
28653
+ channelName: "client.createSession",
28654
+ kind: "async"
28655
+ }),
28656
+ resumeSession: channel({
28657
+ channelName: "client.resumeSession",
28658
+ kind: "async"
28659
+ }),
28660
+ sendAndWait: channel({
28661
+ channelName: "session.sendAndWait",
28662
+ kind: "async"
28663
+ })
28664
+ },
28665
+ { instrumentationName: INSTRUMENTATION_NAMES.GITHUB_COPILOT }
28666
+ );
27780
28667
 
27781
28668
  // src/instrumentation/plugins/github-copilot-plugin.ts
27782
28669
  var ROOT_AGENT_KEY = "__root__";
@@ -27867,11 +28754,16 @@ async function handleTurnStart(state, agentId) {
27867
28754
  return;
27868
28755
  }
27869
28756
  const parentId = await getParentIdForAgent(state, agentId);
27870
- const span = startSpan({
27871
- name: "Copilot Turn",
27872
- parent: parentId,
27873
- spanAttributes: { type: "task" /* TASK */ }
27874
- });
28757
+ const span = startSpan(
28758
+ withSpanInstrumentationName(
28759
+ {
28760
+ name: "Copilot Turn",
28761
+ parent: parentId,
28762
+ spanAttributes: { type: "task" /* TASK */ }
28763
+ },
28764
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
28765
+ )
28766
+ );
27875
28767
  const pendingUserMessage = state.pendingUserMessages.get(key);
27876
28768
  if (pendingUserMessage) {
27877
28769
  span.log({ input: pendingUserMessage });
@@ -27902,11 +28794,16 @@ async function handleUsage(state, agentId, usage) {
27902
28794
  const parentId = turn ? await turn.id : await state.session.id;
27903
28795
  const content = state.currentMessageContent.get(key);
27904
28796
  const { metrics, metadata } = extractMetricsFromUsage(usage);
27905
- const llmSpan = startSpan({
27906
- name: "github.copilot.llm",
27907
- parent: parentId,
27908
- spanAttributes: { type: "llm" /* LLM */ }
27909
- });
28797
+ const llmSpan = startSpan(
28798
+ withSpanInstrumentationName(
28799
+ {
28800
+ name: "github.copilot.llm",
28801
+ parent: parentId,
28802
+ spanAttributes: { type: "llm" /* LLM */ }
28803
+ },
28804
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
28805
+ )
28806
+ );
27910
28807
  llmSpan.log({
27911
28808
  output: content ?? void 0,
27912
28809
  metadata,
@@ -27932,11 +28829,16 @@ async function handleToolStart(state, agentId, toolCallId, toolName, args, mcpSe
27932
28829
  }
27933
28830
  const parentId = await getToolParentId(state, agentId);
27934
28831
  const displayName = mcpServerName ? `tool: ${mcpServerName}/${toolName}` : `tool: ${toolName}`;
27935
- const span = startSpan({
27936
- name: displayName,
27937
- parent: parentId,
27938
- spanAttributes: { type: "tool" /* TOOL */ }
27939
- });
28832
+ const span = startSpan(
28833
+ withSpanInstrumentationName(
28834
+ {
28835
+ name: displayName,
28836
+ parent: parentId,
28837
+ spanAttributes: { type: "tool" /* TOOL */ }
28838
+ },
28839
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
28840
+ )
28841
+ );
27940
28842
  const metadata = {
27941
28843
  "gen_ai.tool.name": toolName,
27942
28844
  "gen_ai.tool.call.id": toolCallId
@@ -27972,11 +28874,16 @@ async function handleSubagentStarted(state, agentId, toolCallId, agentDisplayNam
27972
28874
  }
27973
28875
  const tool = state.activeTools.get(toolCallId);
27974
28876
  const parentId = tool ? await tool.id : await state.session.id;
27975
- const span = startSpan({
27976
- name: `Agent: ${agentDisplayName}`,
27977
- parent: parentId,
27978
- spanAttributes: { type: "task" /* TASK */ }
27979
- });
28877
+ const span = startSpan(
28878
+ withSpanInstrumentationName(
28879
+ {
28880
+ name: `Agent: ${agentDisplayName}`,
28881
+ parent: parentId,
28882
+ spanAttributes: { type: "task" /* TASK */ }
28883
+ },
28884
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
28885
+ )
28886
+ );
27980
28887
  span.log({
27981
28888
  metadata: {
27982
28889
  "github_copilot.agent_name": agentDisplayName,
@@ -28202,10 +29109,15 @@ function makeSessionHandlers(sessionStates, configArgIndex, includeProviderMetad
28202
29109
  if (!config || typeof config !== "object") {
28203
29110
  return;
28204
29111
  }
28205
- const sessionSpan = startSpan({
28206
- name: "Copilot Session",
28207
- spanAttributes: { type: "task" /* TASK */ }
28208
- });
29112
+ const sessionSpan = startSpan(
29113
+ withSpanInstrumentationName(
29114
+ {
29115
+ name: "Copilot Session",
29116
+ spanAttributes: { type: "task" /* TASK */ }
29117
+ },
29118
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
29119
+ )
29120
+ );
28209
29121
  const metadata = {};
28210
29122
  if (config.model) {
28211
29123
  metadata["github_copilot.model"] = config.model;
@@ -28293,12 +29205,16 @@ var GitHubCopilotPlugin = class extends BasePlugin {
28293
29205
  };
28294
29206
 
28295
29207
  // src/instrumentation/plugins/flue-channels.ts
28296
- var flueChannels = defineChannels("@flue/runtime", {
28297
- createContext: channel({
28298
- channelName: "createFlueContext",
28299
- kind: "sync-stream"
28300
- })
28301
- });
29208
+ var flueChannels = defineChannels(
29209
+ "@flue/runtime",
29210
+ {
29211
+ createContext: channel({
29212
+ channelName: "createFlueContext",
29213
+ kind: "sync-stream"
29214
+ })
29215
+ },
29216
+ { instrumentationName: INSTRUMENTATION_NAMES.FLUE }
29217
+ );
28302
29218
 
28303
29219
  // src/instrumentation/plugins/flue-plugin.ts
28304
29220
  var FLUE_AUTO_STATE = /* @__PURE__ */ Symbol.for("braintrust.flue.auto-state");
@@ -28641,15 +29557,20 @@ var FlueObserveBridge = class {
28641
29557
  safeLog3(existing.span, { input, metadata });
28642
29558
  return;
28643
29559
  }
28644
- const span = startSpan({
28645
- name: `workflow:${workflowName}`,
28646
- spanAttributes: { type: "task" /* TASK */ },
28647
- startTime: eventTime(event.startedAt ?? event.timestamp),
28648
- event: {
28649
- input,
28650
- metadata
28651
- }
28652
- });
29560
+ const span = startSpan(
29561
+ withSpanInstrumentationName(
29562
+ {
29563
+ name: `workflow:${workflowName}`,
29564
+ spanAttributes: { type: "task" /* TASK */ },
29565
+ startTime: eventTime(event.startedAt ?? event.timestamp),
29566
+ event: {
29567
+ input,
29568
+ metadata
29569
+ }
29570
+ },
29571
+ INSTRUMENTATION_NAMES.FLUE
29572
+ )
29573
+ );
28653
29574
  this.runsById.set(event.runId, { metadata, span });
28654
29575
  }
28655
29576
  handleRunResume(event, ctx) {
@@ -28669,12 +29590,17 @@ var FlueObserveBridge = class {
28669
29590
  safeLog3(existing.span, { metadata });
28670
29591
  return;
28671
29592
  }
28672
- const span = startSpan({
28673
- name: `workflow:${workflowName}`,
28674
- spanAttributes: { type: "task" /* TASK */ },
28675
- startTime: eventTime(event.startedAt ?? event.timestamp),
28676
- event: { metadata }
28677
- });
29593
+ const span = startSpan(
29594
+ withSpanInstrumentationName(
29595
+ {
29596
+ name: `workflow:${workflowName}`,
29597
+ spanAttributes: { type: "task" /* TASK */ },
29598
+ startTime: eventTime(event.startedAt ?? event.timestamp),
29599
+ event: { metadata }
29600
+ },
29601
+ INSTRUMENTATION_NAMES.FLUE
29602
+ )
29603
+ );
28678
29604
  this.runsById.set(event.runId, { metadata, span });
28679
29605
  }
28680
29606
  handleRunEnd(event) {
@@ -29313,7 +30239,14 @@ function stateMatchesRun(state, runId) {
29313
30239
  return state.metadata["flue.run_id"] === runId;
29314
30240
  }
29315
30241
  function startFlueSpan(parent, args) {
29316
- return parent ? withCurrent(parent, () => startSpan(args)) : startSpan(args);
30242
+ return parent ? withCurrent(
30243
+ parent,
30244
+ () => startSpan(
30245
+ withSpanInstrumentationName(args, INSTRUMENTATION_NAMES.FLUE)
30246
+ )
30247
+ ) : startSpan(
30248
+ withSpanInstrumentationName(args, INSTRUMENTATION_NAMES.FLUE)
30249
+ );
29317
30250
  }
29318
30251
  function runWithCurrentSpanStore(span, next) {
29319
30252
  const state = _internalGetGlobalState();
@@ -29403,9 +30336,13 @@ var BraintrustLangChainCallbackHandler = class {
29403
30336
  ...this.options.debug ? { runId, parentRunId } : {}
29404
30337
  }
29405
30338
  };
29406
- let span = parentSpan.startSpan(args);
30339
+ const spanArgs = withSpanInstrumentationName(
30340
+ args,
30341
+ INSTRUMENTATION_NAMES.LANGCHAIN
30342
+ );
30343
+ let span = parentSpan.startSpan(spanArgs);
29407
30344
  if (!Object.is(this.options.logger, NOOP_SPAN) && Object.is(span, NOOP_SPAN)) {
29408
- span = initLogger().startSpan(args);
30345
+ span = initLogger().startSpan(spanArgs);
29409
30346
  }
29410
30347
  this.spans.set(runId, span);
29411
30348
  }
@@ -29702,16 +30639,20 @@ function isRecord(value) {
29702
30639
  }
29703
30640
 
29704
30641
  // src/instrumentation/plugins/langchain-channels.ts
29705
- var langChainChannels = defineChannels("@langchain/core", {
29706
- configure: channel({
29707
- channelName: "CallbackManager.configure",
29708
- kind: "sync-stream"
29709
- }),
29710
- configureSync: channel({
29711
- channelName: "CallbackManager._configureSync",
29712
- kind: "sync-stream"
29713
- })
29714
- });
30642
+ var langChainChannels = defineChannels(
30643
+ "@langchain/core",
30644
+ {
30645
+ configure: channel({
30646
+ channelName: "CallbackManager.configure",
30647
+ kind: "sync-stream"
30648
+ }),
30649
+ configureSync: channel({
30650
+ channelName: "CallbackManager._configureSync",
30651
+ kind: "sync-stream"
30652
+ })
30653
+ },
30654
+ { instrumentationName: INSTRUMENTATION_NAMES.LANGCHAIN }
30655
+ );
29715
30656
 
29716
30657
  // src/instrumentation/plugins/langchain-plugin.ts
29717
30658
  var LangChainPlugin = class extends BasePlugin {
@@ -29799,20 +30740,24 @@ function isBraintrustHandler(handler) {
29799
30740
  }
29800
30741
 
29801
30742
  // src/instrumentation/plugins/langsmith-channels.ts
29802
- var langSmithChannels = defineChannels("langsmith", {
29803
- createRun: channel({
29804
- channelName: "Client.createRun",
29805
- kind: "async"
29806
- }),
29807
- updateRun: channel({
29808
- channelName: "Client.updateRun",
29809
- kind: "async"
29810
- }),
29811
- batchIngestRuns: channel({
29812
- channelName: "Client.batchIngestRuns",
29813
- kind: "async"
29814
- })
29815
- });
30743
+ var langSmithChannels = defineChannels(
30744
+ "langsmith",
30745
+ {
30746
+ createRun: channel({
30747
+ channelName: "Client.createRun",
30748
+ kind: "async"
30749
+ }),
30750
+ updateRun: channel({
30751
+ channelName: "Client.updateRun",
30752
+ kind: "async"
30753
+ }),
30754
+ batchIngestRuns: channel({
30755
+ channelName: "Client.batchIngestRuns",
30756
+ kind: "async"
30757
+ })
30758
+ },
30759
+ { instrumentationName: INSTRUMENTATION_NAMES.LANGSMITH }
30760
+ );
29816
30761
 
29817
30762
  // src/instrumentation/plugins/langsmith-plugin.ts
29818
30763
  var MAX_COMPLETED_RUNS = 1e4;
@@ -29976,19 +30921,24 @@ var LangSmithPlugin = class extends BasePlugin {
29976
30921
  const traceId = stringValue2(ownValue(run, "trace_id")) ?? id;
29977
30922
  const parentId = stringValue2(ownValue(run, "parent_run_id")) ?? stringValue2(ownValue(ownValue(run, "parent_run"), "id"));
29978
30923
  const startTime = timestampSeconds(ownValue(run, "start_time"));
29979
- return startSpan({
29980
- name: stringValue2(ownValue(run, "name")) ?? "LangSmith run",
29981
- spanId: id,
29982
- parentSpanIds: {
29983
- parentSpanIds: parentId ? [parentId] : [],
29984
- rootSpanId: traceId
29985
- },
29986
- spanAttributes: {
29987
- type: mapRunType(ownValue(run, "run_type"))
29988
- },
29989
- ...startTime === void 0 ? {} : { startTime },
29990
- event: { id }
29991
- });
30924
+ return startSpan(
30925
+ withSpanInstrumentationName(
30926
+ {
30927
+ name: stringValue2(ownValue(run, "name")) ?? "LangSmith run",
30928
+ spanId: id,
30929
+ parentSpanIds: {
30930
+ parentSpanIds: parentId ? [parentId] : [],
30931
+ rootSpanId: traceId
30932
+ },
30933
+ spanAttributes: {
30934
+ type: mapRunType(ownValue(run, "run_type"))
30935
+ },
30936
+ ...startTime === void 0 ? {} : { startTime },
30937
+ event: { id }
30938
+ },
30939
+ INSTRUMENTATION_NAMES.LANGSMITH
30940
+ )
30941
+ );
29992
30942
  }
29993
30943
  logRun(span, run, previous, includeOutput) {
29994
30944
  const inputs = preferOwnValue(run, previous, "inputs");
@@ -30246,7 +31196,8 @@ var piCodingAgentChannels = defineChannels(
30246
31196
  channelName: "AgentSession.prompt",
30247
31197
  kind: "async"
30248
31198
  })
30249
- }
31199
+ },
31200
+ { instrumentationName: INSTRUMENTATION_NAMES.PI_CODING_AGENT }
30250
31201
  );
30251
31202
 
30252
31203
  // src/instrumentation/plugins/pi-coding-agent-plugin.ts
@@ -30330,14 +31281,19 @@ function startPiPromptRun(event, onFinalize) {
30330
31281
  ...session.model?.id || agent.state?.model?.id ? { model: session.model?.id ?? agent.state?.model?.id } : {},
30331
31282
  ...event.moduleVersion ? { "pi_coding_agent.version": event.moduleVersion } : {}
30332
31283
  };
30333
- const span = startSpan({
30334
- event: {
30335
- input: extractPromptInput(event.arguments[0], event.arguments[1]),
30336
- metadata
30337
- },
30338
- name: "AgentSession.prompt",
30339
- spanAttributes: { type: "task" /* TASK */ }
30340
- });
31284
+ const span = startSpan(
31285
+ withSpanInstrumentationName(
31286
+ {
31287
+ event: {
31288
+ input: extractPromptInput(event.arguments[0], event.arguments[1]),
31289
+ metadata
31290
+ },
31291
+ name: "AgentSession.prompt",
31292
+ spanAttributes: { type: "task" /* TASK */ }
31293
+ },
31294
+ INSTRUMENTATION_NAMES.PI_CODING_AGENT
31295
+ )
31296
+ );
30341
31297
  const streamPatchState = installPiStreamPatch(agent);
30342
31298
  const options = event.arguments[1];
30343
31299
  const promptText = event.arguments[0];
@@ -30507,15 +31463,20 @@ async function startPiLlmSpan(state, model, context, options) {
30507
31463
  ...extractToolMetadata(context.tools),
30508
31464
  "pi_coding_agent.operation": "agent.streamFn"
30509
31465
  };
30510
- const span = startSpan({
30511
- event: {
30512
- input: processInputAttachments(normalizePiContextInput(context)),
30513
- metadata
30514
- },
30515
- name: getLlmSpanName(model),
30516
- parent: await state.span.export(),
30517
- spanAttributes: { type: "llm" /* LLM */ }
30518
- });
31466
+ const span = startSpan(
31467
+ withSpanInstrumentationName(
31468
+ {
31469
+ event: {
31470
+ input: processInputAttachments(normalizePiContextInput(context)),
31471
+ metadata
31472
+ },
31473
+ name: getLlmSpanName(model),
31474
+ parent: await state.span.export(),
31475
+ spanAttributes: { type: "llm" /* LLM */ }
31476
+ },
31477
+ INSTRUMENTATION_NAMES.PI_CODING_AGENT
31478
+ )
31479
+ );
30519
31480
  const llmState = {
30520
31481
  finalized: false,
30521
31482
  metadata,
@@ -30683,15 +31644,20 @@ async function startPiToolSpan(state, event) {
30683
31644
  "pi_coding_agent.tool.name": event.toolName
30684
31645
  };
30685
31646
  try {
30686
- const span = startSpan({
30687
- event: {
30688
- input: event.args,
30689
- metadata
30690
- },
30691
- name: event.toolName || "tool",
30692
- parent: await state.span.export(),
30693
- spanAttributes: { type: "tool" /* TOOL */ }
30694
- });
31647
+ const span = startSpan(
31648
+ withSpanInstrumentationName(
31649
+ {
31650
+ event: {
31651
+ input: event.args,
31652
+ metadata
31653
+ },
31654
+ name: event.toolName || "tool",
31655
+ parent: await state.span.export(),
31656
+ spanAttributes: { type: "tool" /* TOOL */ }
31657
+ },
31658
+ INSTRUMENTATION_NAMES.PI_CODING_AGENT
31659
+ )
31660
+ );
30695
31661
  state.activeToolSpans.set(event.toolCallId, {
30696
31662
  restoreAutoInstrumentation,
30697
31663
  span
@@ -31123,20 +32089,24 @@ function logInstrumentationError4(context, error) {
31123
32089
  }
31124
32090
 
31125
32091
  // src/instrumentation/plugins/strands-agent-sdk-channels.ts
31126
- var strandsAgentSDKChannels = defineChannels("@strands-agents/sdk", {
31127
- agentStream: channel({
31128
- channelName: "Agent.stream",
31129
- kind: "sync-stream"
31130
- }),
31131
- graphStream: channel({
31132
- channelName: "Graph.stream",
31133
- kind: "sync-stream"
31134
- }),
31135
- swarmStream: channel({
31136
- channelName: "Swarm.stream",
31137
- kind: "sync-stream"
31138
- })
31139
- });
32092
+ var strandsAgentSDKChannels = defineChannels(
32093
+ "@strands-agents/sdk",
32094
+ {
32095
+ agentStream: channel({
32096
+ channelName: "Agent.stream",
32097
+ kind: "sync-stream"
32098
+ }),
32099
+ graphStream: channel({
32100
+ channelName: "Graph.stream",
32101
+ kind: "sync-stream"
32102
+ }),
32103
+ swarmStream: channel({
32104
+ channelName: "Swarm.stream",
32105
+ kind: "sync-stream"
32106
+ })
32107
+ },
32108
+ { instrumentationName: INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK }
32109
+ );
31140
32110
 
31141
32111
  // src/instrumentation/plugins/strands-agent-sdk-plugin.ts
31142
32112
  var MAX_STRANDS_STRING_ATTACHMENT_CACHE_ENTRIES = 32;
@@ -31291,22 +32261,32 @@ function startAgentStream(event, activeChildParents) {
31291
32261
  );
31292
32262
  const span = parentSpan ? withCurrent(
31293
32263
  parentSpan,
31294
- () => startSpan({
31295
- event: {
31296
- input,
31297
- metadata
32264
+ () => startSpan(
32265
+ withSpanInstrumentationName(
32266
+ {
32267
+ event: {
32268
+ input,
32269
+ metadata
32270
+ },
32271
+ name: formatAgentSpanName(agent),
32272
+ spanAttributes: { type: "task" /* TASK */ }
32273
+ },
32274
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
32275
+ )
32276
+ )
32277
+ ) : startSpan(
32278
+ withSpanInstrumentationName(
32279
+ {
32280
+ event: {
32281
+ input,
32282
+ metadata
32283
+ },
32284
+ name: formatAgentSpanName(agent),
32285
+ spanAttributes: { type: "task" /* TASK */ }
31298
32286
  },
31299
- name: formatAgentSpanName(agent),
31300
- spanAttributes: { type: "task" /* TASK */ }
31301
- })
31302
- ) : startSpan({
31303
- event: {
31304
- input,
31305
- metadata
31306
- },
31307
- name: formatAgentSpanName(agent),
31308
- spanAttributes: { type: "task" /* TASK */ }
31309
- });
32287
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
32288
+ )
32289
+ );
31310
32290
  return {
31311
32291
  activeTools: /* @__PURE__ */ new Map(),
31312
32292
  attachmentCache,
@@ -31328,22 +32308,32 @@ function startMultiAgentStream(event, operation, activeChildParents) {
31328
32308
  const input = processStrandsInputAttachments(event.arguments[0]);
31329
32309
  const span = parentSpan ? withCurrent(
31330
32310
  parentSpan,
31331
- () => startSpan({
31332
- event: {
31333
- input,
31334
- metadata
32311
+ () => startSpan(
32312
+ withSpanInstrumentationName(
32313
+ {
32314
+ event: {
32315
+ input,
32316
+ metadata
32317
+ },
32318
+ name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
32319
+ spanAttributes: { type: "task" /* TASK */ }
32320
+ },
32321
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
32322
+ )
32323
+ )
32324
+ ) : startSpan(
32325
+ withSpanInstrumentationName(
32326
+ {
32327
+ event: {
32328
+ input,
32329
+ metadata
32330
+ },
32331
+ name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
32332
+ spanAttributes: { type: "task" /* TASK */ }
31335
32333
  },
31336
- name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
31337
- spanAttributes: { type: "task" /* TASK */ }
31338
- })
31339
- ) : startSpan({
31340
- event: {
31341
- input,
31342
- metadata
31343
- },
31344
- name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
31345
- spanAttributes: { type: "task" /* TASK */ }
31346
- });
32334
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
32335
+ )
32336
+ );
31347
32337
  return {
31348
32338
  activeNodes: /* @__PURE__ */ new Map(),
31349
32339
  finalized: false,
@@ -31445,17 +32435,22 @@ function startModelSpan(state, event) {
31445
32435
  };
31446
32436
  const span = withCurrent(
31447
32437
  state.span,
31448
- () => startSpan({
31449
- event: {
31450
- input: Array.isArray(event.agent?.messages) ? processStrandsInputAttachments(
31451
- event.agent.messages,
31452
- state.attachmentCache
31453
- ) : void 0,
31454
- metadata
31455
- },
31456
- name: formatModelSpanName(model),
31457
- spanAttributes: { type: "llm" /* LLM */ }
31458
- })
32438
+ () => startSpan(
32439
+ withSpanInstrumentationName(
32440
+ {
32441
+ event: {
32442
+ input: Array.isArray(event.agent?.messages) ? processStrandsInputAttachments(
32443
+ event.agent.messages,
32444
+ state.attachmentCache
32445
+ ) : void 0,
32446
+ metadata
32447
+ },
32448
+ name: formatModelSpanName(model),
32449
+ spanAttributes: { type: "llm" /* LLM */ }
32450
+ },
32451
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
32452
+ )
32453
+ )
31459
32454
  );
31460
32455
  state.activeModel = {
31461
32456
  metadata,
@@ -31507,20 +32502,25 @@ function startToolSpan2(state, event) {
31507
32502
  const name = extractToolName3(toolUse, event.tool);
31508
32503
  const span = withCurrent(
31509
32504
  state.span,
31510
- () => startSpan({
31511
- event: {
31512
- input: toolUse?.input,
31513
- metadata: {
31514
- "gen_ai.tool.call.id": toolUse?.toolUseId,
31515
- "gen_ai.tool.name": name,
31516
- "strands.operation": "tool.call",
31517
- "strands.tool.name": name,
31518
- provider: "strands"
31519
- }
31520
- },
31521
- name: `tool: ${name}`,
31522
- spanAttributes: { type: "tool" /* TOOL */ }
31523
- })
32505
+ () => startSpan(
32506
+ withSpanInstrumentationName(
32507
+ {
32508
+ event: {
32509
+ input: toolUse?.input,
32510
+ metadata: {
32511
+ "gen_ai.tool.call.id": toolUse?.toolUseId,
32512
+ "gen_ai.tool.name": name,
32513
+ "strands.operation": "tool.call",
32514
+ "strands.tool.name": name,
32515
+ provider: "strands"
32516
+ }
32517
+ },
32518
+ name: `tool: ${name}`,
32519
+ spanAttributes: { type: "tool" /* TOOL */ }
32520
+ },
32521
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
32522
+ )
32523
+ )
31524
32524
  );
31525
32525
  state.activeTools.set(key, {
31526
32526
  span,
@@ -31591,11 +32591,16 @@ function startNodeSpan(state, event, activeChildParents) {
31591
32591
  };
31592
32592
  const span = withCurrent(
31593
32593
  state.span,
31594
- () => startSpan({
31595
- event: { metadata },
31596
- name: `node: ${nodeId}`,
31597
- spanAttributes: { type: "task" /* TASK */ }
31598
- })
32594
+ () => startSpan(
32595
+ withSpanInstrumentationName(
32596
+ {
32597
+ event: { metadata },
32598
+ name: `node: ${nodeId}`,
32599
+ spanAttributes: { type: "task" /* TASK */ }
32600
+ },
32601
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
32602
+ )
32603
+ )
31599
32604
  );
31600
32605
  const nodeState = {
31601
32606
  ...child ? { child } : {},
@@ -33323,6 +34328,12 @@ var wrapAgentClass = (AgentClass, options = {}) => {
33323
34328
  const original = Reflect.get(instanceTarget, prop, instanceTarget);
33324
34329
  if (harnessAgent && typeof original === "function") {
33325
34330
  switch (prop) {
34331
+ case "createSession":
34332
+ return wrapHarnessAgentCreateSession(
34333
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
34334
+ original,
34335
+ harnessAgent
34336
+ );
33326
34337
  case "generate":
33327
34338
  return wrapHarnessAgentGenerate(
33328
34339
  original,
@@ -33372,6 +34383,19 @@ var wrapAgentClass = (AgentClass, options = {}) => {
33372
34383
  }
33373
34384
  });
33374
34385
  };
34386
+ var wrapHarnessAgentCreateSession = (createSession, instance) => {
34387
+ const wrapper = function(params) {
34388
+ return harnessAgentChannels.createSession.tracePromise(
34389
+ () => params === void 0 ? createSession.call(instance) : createSession.call(instance, params),
34390
+ createAISDKChannelContext(params ?? {}, { self: instance })
34391
+ );
34392
+ };
34393
+ Object.defineProperty(wrapper, "name", {
34394
+ value: "HarnessAgent.createSession",
34395
+ writable: false
34396
+ });
34397
+ return wrapper;
34398
+ };
33375
34399
  var wrapHarnessAgentGenerate = (generate, instance, channel2, name, options) => makeGenerateTextWrapper(
33376
34400
  channel2,
33377
34401
  name,
@@ -33641,12 +34665,17 @@ var BraintrustLanguageModelWrapper = class {
33641
34665
  // For the first cut, do not support custom span_info arguments. We can
33642
34666
  // propagate those via async local storage
33643
34667
  async doGenerate(options) {
33644
- const span = startSpan({
33645
- name: "Chat Completion",
33646
- spanAttributes: {
33647
- type: "llm"
33648
- }
33649
- });
34668
+ const span = startSpan(
34669
+ withSpanInstrumentationName(
34670
+ {
34671
+ name: "Chat Completion",
34672
+ spanAttributes: {
34673
+ type: "llm"
34674
+ }
34675
+ },
34676
+ INSTRUMENTATION_NAMES.AI_SDK
34677
+ )
34678
+ );
33650
34679
  const { prompt, mode, ...rest } = options;
33651
34680
  const startTime = getCurrentUnixTimestamp();
33652
34681
  try {
@@ -33677,12 +34706,17 @@ var BraintrustLanguageModelWrapper = class {
33677
34706
  async doStream(options) {
33678
34707
  const { prompt, mode, ...rest } = options;
33679
34708
  const startTime = getCurrentUnixTimestamp();
33680
- const span = startSpan({
33681
- name: "Chat Completion",
33682
- spanAttributes: {
33683
- type: "llm"
33684
- }
33685
- });
34709
+ const span = startSpan(
34710
+ withSpanInstrumentationName(
34711
+ {
34712
+ name: "Chat Completion",
34713
+ spanAttributes: {
34714
+ type: "llm"
34715
+ }
34716
+ },
34717
+ INSTRUMENTATION_NAMES.AI_SDK
34718
+ )
34719
+ );
33686
34720
  span.log({
33687
34721
  input: postProcessPrompt(prompt),
33688
34722
  metadata: {
@@ -34037,7 +35071,9 @@ function BraintrustMiddleware(config = {}) {
34037
35071
  }
34038
35072
  }
34039
35073
  };
34040
- const span = startSpan(spanArgs);
35074
+ const span = startSpan(
35075
+ withSpanInstrumentationName(spanArgs, INSTRUMENTATION_NAMES.AI_SDK)
35076
+ );
34041
35077
  try {
34042
35078
  const result = await doGenerate();
34043
35079
  const metadata = {};
@@ -34099,7 +35135,9 @@ function BraintrustMiddleware(config = {}) {
34099
35135
  }
34100
35136
  }
34101
35137
  };
34102
- const span = startSpan(spanArgs);
35138
+ const span = startSpan(
35139
+ withSpanInstrumentationName(spanArgs, INSTRUMENTATION_NAMES.AI_SDK)
35140
+ );
34103
35141
  try {
34104
35142
  const { stream, ...rest } = await doStream();
34105
35143
  const textChunks = [];
@@ -34306,7 +35344,12 @@ var EveBridge = class {
34306
35344
  };
34307
35345
  const span = withCurrent(
34308
35346
  NOOP_SPAN,
34309
- () => _internalStartSpanWithInitialMerge({ ...args, startTime })
35347
+ () => _internalStartSpanWithInitialMerge(
35348
+ withSpanInstrumentationName(
35349
+ { ...args, startTime },
35350
+ INSTRUMENTATION_NAMES.EVE
35351
+ )
35352
+ )
34310
35353
  );
34311
35354
  if (typeof rowId !== "string") {
34312
35355
  return span;
@@ -36080,17 +37123,20 @@ var BraintrustObservabilityExporter = class {
36080
37123
  }
36081
37124
  onStart(exported) {
36082
37125
  if (this.spans.has(exported.id)) return;
36083
- const args = {
36084
- name: exported.name,
36085
- spanAttributes: { type: spanTypeFor(exported.type) },
36086
- startTime: epochSeconds(exported.startTime),
36087
- // Use the Mastra span id as the Braintrust row id so that
36088
- // `logFeedback({ id: <mastra span id> })` (and Mastra's score events)
36089
- // attach to the right row. Without this, `SpanImpl` auto-generates a
36090
- // row id (`this._id = eventId ?? idGenerator.getSpanId()`) that no
36091
- // external caller could know.
36092
- event: { id: exported.id }
36093
- };
37126
+ const args = withSpanInstrumentationName(
37127
+ {
37128
+ name: exported.name,
37129
+ spanAttributes: { type: spanTypeFor(exported.type) },
37130
+ startTime: epochSeconds(exported.startTime),
37131
+ // Use the Mastra span id as the Braintrust row id so that
37132
+ // `logFeedback({ id: <mastra span id> })` (and Mastra's score events)
37133
+ // attach to the right row. Without this, `SpanImpl` auto-generates a
37134
+ // row id (`this._id = eventId ?? idGenerator.getSpanId()`) that no
37135
+ // external caller could know.
37136
+ event: { id: exported.id }
37137
+ },
37138
+ INSTRUMENTATION_NAMES.MASTRA
37139
+ );
36094
37140
  const parentRecord = exported.parentSpanId ? this.spans.get(exported.parentSpanId) : void 0;
36095
37141
  if (!this.capturedParent) {
36096
37142
  const probe = currentSpan();
@@ -41476,26 +42522,30 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
41476
42522
  }
41477
42523
  }
41478
42524
  })();
42525
+ let timeoutId;
42526
+ let abortHandler;
42527
+ const cleanupCancellation = () => {
42528
+ if (timeoutId !== void 0) {
42529
+ clearTimeout(timeoutId);
42530
+ timeoutId = void 0;
42531
+ }
42532
+ if (abortHandler && evaluator.signal) {
42533
+ evaluator.signal.removeEventListener("abort", abortHandler);
42534
+ abortHandler = void 0;
42535
+ }
42536
+ };
41479
42537
  const cancel = async () => {
41480
42538
  await new Promise((_, reject2) => {
41481
42539
  if (cancelled) {
41482
42540
  reject2(new InternalAbortError("Evaluator already cancelled"));
41483
42541
  return;
41484
42542
  }
41485
- let timeoutId;
41486
- let abortHandler;
41487
42543
  const rejectOnce = (error) => {
41488
42544
  if (cancelled) {
41489
42545
  return;
41490
42546
  }
41491
42547
  cancelled = true;
41492
- if (timeoutId) {
41493
- clearTimeout(timeoutId);
41494
- timeoutId = void 0;
41495
- }
41496
- if (abortHandler && evaluator.signal) {
41497
- evaluator.signal.removeEventListener("abort", abortHandler);
41498
- }
42548
+ cleanupCancellation();
41499
42549
  reject2(error);
41500
42550
  };
41501
42551
  if (evaluator.timeout) {
@@ -41535,6 +42585,7 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
41535
42585
  }
41536
42586
  throw e;
41537
42587
  } finally {
42588
+ cleanupCancellation();
41538
42589
  if (!collectResults) {
41539
42590
  collectedResults.length = 0;
41540
42591
  }