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
package/dist/browser.js CHANGED
@@ -5022,7 +5022,51 @@ var SpanCache = class {
5022
5022
  };
5023
5023
 
5024
5024
  // src/span-origin.ts
5025
- var SDK_VERSION = true ? "3.24.0" : "0.0.0";
5025
+ var INSTRUMENTATION_NAMES = {
5026
+ AI_SDK: "ai-sdk",
5027
+ ANTHROPIC: "anthropic",
5028
+ BEDROCK_RUNTIME: "bedrock-runtime",
5029
+ BRAINTRUST_JS_LOGGER: "braintrust-js-logger",
5030
+ CLAUDE_AGENT_SDK: "claude-agent-sdk",
5031
+ COHERE: "cohere",
5032
+ CURSOR_SDK: "cursor-sdk",
5033
+ EVE: "eve",
5034
+ FLUE: "flue",
5035
+ GENKIT: "genkit",
5036
+ GITHUB_COPILOT: "github-copilot",
5037
+ GOOGLE_ADK: "google-adk",
5038
+ GOOGLE_GENAI: "google-genai",
5039
+ GROQ: "groq",
5040
+ HUGGINGFACE: "huggingface",
5041
+ LANGCHAIN: "langchain",
5042
+ LANGSMITH: "langsmith",
5043
+ MASTRA: "mastra",
5044
+ MISTRAL: "mistral",
5045
+ OPENAI: "openai",
5046
+ OPENAI_AGENTS: "openai-agents",
5047
+ OPENAI_CODEX: "openai-codex",
5048
+ OPENROUTER: "openrouter",
5049
+ OPENROUTER_AGENT: "openrouter-agent",
5050
+ PI_CODING_AGENT: "pi-coding-agent",
5051
+ STRANDS_AGENT_SDK: "strands-agent-sdk"
5052
+ };
5053
+ var INTERNAL_SPAN_INSTRUMENTATION_NAME = /* @__PURE__ */ Symbol.for(
5054
+ "braintrust.spanInstrumentationName"
5055
+ );
5056
+ var SDK_VERSION = true ? "3.25.0" : "0.0.0";
5057
+ function withSpanInstrumentationName(args, instrumentationName) {
5058
+ return {
5059
+ ...args,
5060
+ [INTERNAL_SPAN_INSTRUMENTATION_NAME]: instrumentationName
5061
+ };
5062
+ }
5063
+ function getSpanInstrumentationName(args) {
5064
+ if (typeof args !== "object" || args === null) {
5065
+ return void 0;
5066
+ }
5067
+ const value = args[INTERNAL_SPAN_INSTRUMENTATION_NAME];
5068
+ return isSpanInstrumentationName(value) ? value : void 0;
5069
+ }
5026
5070
  function detectSpanOriginEnvironment(explicit) {
5027
5071
  if (explicit) return explicit;
5028
5072
  const envType = isomorph_default.getEnv("BRAINTRUST_ENVIRONMENT_TYPE");
@@ -5094,6 +5138,9 @@ function mergeSpanOriginContext(context, instrumentationName, environment) {
5094
5138
  };
5095
5139
  return next;
5096
5140
  }
5141
+ function isSpanInstrumentationName(value) {
5142
+ return Object.values(INSTRUMENTATION_NAMES).some((name) => name === value);
5143
+ }
5097
5144
  function firstPresent(entries) {
5098
5145
  return entries.find(([key]) => Boolean(isomorph_default.getEnv(key)))?.[1];
5099
5146
  }
@@ -5388,6 +5435,7 @@ var BraintrustState = class _BraintrustState {
5388
5435
  });
5389
5436
  this.spanCache = new SpanCache({ disabled: loginParams.disableSpanCache });
5390
5437
  this.spanOriginEnvironment = detectSpanOriginEnvironment();
5438
+ this._internalSetTraceContextSigningSecret(loginParams.apiKey);
5391
5439
  }
5392
5440
  loginParams;
5393
5441
  id;
@@ -5425,6 +5473,18 @@ var BraintrustState = class _BraintrustState {
5425
5473
  _contextManager = null;
5426
5474
  _otelFlushCallback = null;
5427
5475
  spanOriginEnvironment;
5476
+ traceContextSigningSecret;
5477
+ /** @internal */
5478
+ _internalSetTraceContextSigningSecret(secret) {
5479
+ const normalizedSecret = secret?.trim();
5480
+ if (normalizedSecret) {
5481
+ this.traceContextSigningSecret = normalizedSecret;
5482
+ }
5483
+ }
5484
+ /** @internal */
5485
+ _internalGetTraceContextSigningSecret() {
5486
+ return (this.traceContextSigningSecret ?? this.loginToken ?? isomorph_default.getEnv("BRAINTRUST_API_KEY"))?.trim();
5487
+ }
5428
5488
  resetLoginInfo() {
5429
5489
  this.appUrl = null;
5430
5490
  this.appPublicUrl = null;
@@ -5485,6 +5545,7 @@ var BraintrustState = class _BraintrustState {
5485
5545
  this.gitMetadataSettings = other.gitMetadataSettings;
5486
5546
  this.debugLogLevel = other.debugLogLevel;
5487
5547
  this.debugLogLevelConfigured = other.debugLogLevelConfigured;
5548
+ this.traceContextSigningSecret = other.traceContextSigningSecret;
5488
5549
  setGlobalDebugLogLevel(
5489
5550
  this.debugLogLevelConfigured ? this.debugLogLevel ?? false : void 0
5490
5551
  );
@@ -5572,6 +5633,7 @@ var BraintrustState = class _BraintrustState {
5572
5633
  return this.debugLogLevelConfigured;
5573
5634
  }
5574
5635
  async login(loginParams) {
5636
+ this._internalSetTraceContextSigningSecret(loginParams.apiKey);
5575
5637
  this.setDebugLogLevel(loginParams.debugLogLevel);
5576
5638
  if (this.apiUrl && !loginParams.forceLogin) {
5577
5639
  return;
@@ -7551,6 +7613,7 @@ function init(projectOrOptions, optionalOptions) {
7551
7613
  throw new Error("Cannot open and update an experiment at the same time");
7552
7614
  }
7553
7615
  const state = stateArg ?? _globalState;
7616
+ state._internalSetTraceContextSigningSecret(apiKey);
7554
7617
  state.enforceQueueSizeLimit(false);
7555
7618
  if (open) {
7556
7619
  if (isEmpty2(experiment)) {
@@ -8059,6 +8122,7 @@ function initLogger(options = {}) {
8059
8122
  project_id: projectId
8060
8123
  };
8061
8124
  const state = stateArg ?? _globalState;
8125
+ state._internalSetTraceContextSigningSecret(apiKey);
8062
8126
  state.setDebugLogLevel(debugLogLevel);
8063
8127
  state.spanOriginEnvironment = detectSpanOriginEnvironment(environment);
8064
8128
  state.enforceQueueSizeLimit(true);
@@ -9122,7 +9186,9 @@ function deepCopyEvent(event) {
9122
9186
  const ATTACHMENT_MARKER_KEY = "_bt_internal_saved_attachment_marker";
9123
9187
  const attachmentMarker = ++deepCopyEventMarkerCounter;
9124
9188
  const serialized = JSON.stringify(event, (_k, v) => {
9125
- if (v instanceof SpanImpl || v instanceof NoopSpan) {
9189
+ if (v instanceof Error) {
9190
+ return v.message;
9191
+ } else if (v instanceof SpanImpl || v instanceof NoopSpan) {
9126
9192
  return `<span>`;
9127
9193
  } else if (v instanceof Experiment2) {
9128
9194
  return `<experiment>`;
@@ -9790,6 +9856,7 @@ var SpanImpl = class _SpanImpl {
9790
9856
  constructor(args) {
9791
9857
  this._state = args.state;
9792
9858
  this._propagatedState = args.propagatedState;
9859
+ const instrumentationName = getSpanInstrumentationName(args) ?? INSTRUMENTATION_NAMES.BRAINTRUST_JS_LOGGER;
9793
9860
  const spanAttributes = args.spanAttributes ?? {};
9794
9861
  const rawEvent = args.event ?? {};
9795
9862
  const type = args.type ?? (args.parentSpanIds ? void 0 : args.defaultRootType);
@@ -9821,7 +9888,7 @@ var SpanImpl = class _SpanImpl {
9821
9888
  },
9822
9889
  context: mergeSpanOriginContext(
9823
9890
  { ...callerLocation },
9824
- "braintrust-js-logger",
9891
+ instrumentationName,
9825
9892
  this._state.spanOriginEnvironment
9826
9893
  ),
9827
9894
  span_attributes: {
@@ -11805,15 +11872,25 @@ function hasChoices(value) {
11805
11872
  function normalizeMetadata(metadata) {
11806
11873
  return isObject(metadata) ? metadata : void 0;
11807
11874
  }
11808
- function startSpanForEvent(config, event, channelName) {
11875
+ function startSpanForEvent(config, event, channelName, instrumentationName) {
11809
11876
  const { name, spanAttributes, spanInfoMetadata } = buildStartSpanArgs(
11810
11877
  config,
11811
11878
  event
11812
11879
  );
11813
- const span = startSpan({
11814
- name,
11815
- spanAttributes
11816
- });
11880
+ const spanArgs = withSpanInstrumentationName(
11881
+ {
11882
+ name,
11883
+ spanAttributes
11884
+ },
11885
+ instrumentationName
11886
+ );
11887
+ let span;
11888
+ try {
11889
+ span = config.startSpan?.(spanArgs) ?? startSpan(spanArgs);
11890
+ } catch (error) {
11891
+ debugLogger.error(`Error starting span for ${channelName}:`, error);
11892
+ span = startSpan(spanArgs);
11893
+ }
11817
11894
  const startTime = getCurrentUnixTimestamp();
11818
11895
  try {
11819
11896
  const { input, metadata } = config.extractInput(
@@ -11844,7 +11921,7 @@ function shouldTraceEvent(config, event, channelName) {
11844
11921
  return true;
11845
11922
  }
11846
11923
  }
11847
- function ensureSpanStateForEvent(states, config, event, channelName) {
11924
+ function ensureSpanStateForEvent(states, config, event, channelName, instrumentationName) {
11848
11925
  const key = event;
11849
11926
  const existing = states.get(key);
11850
11927
  if (existing) {
@@ -11853,11 +11930,16 @@ function ensureSpanStateForEvent(states, config, event, channelName) {
11853
11930
  if (!shouldTraceEvent(config, event, channelName)) {
11854
11931
  return void 0;
11855
11932
  }
11856
- const created = startSpanForEvent(config, event, channelName);
11933
+ const created = startSpanForEvent(
11934
+ config,
11935
+ event,
11936
+ channelName,
11937
+ instrumentationName
11938
+ );
11857
11939
  states.set(key, created);
11858
11940
  return created;
11859
11941
  }
11860
- function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelName) {
11942
+ function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelName, instrumentationName) {
11861
11943
  const state = _internalGetGlobalState();
11862
11944
  const startChannel = tracingChannel2.start;
11863
11945
  const contextManager = state?.contextManager;
@@ -11875,7 +11957,8 @@ function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelNam
11875
11957
  states,
11876
11958
  config,
11877
11959
  event,
11878
- channelName
11960
+ channelName,
11961
+ instrumentationName
11879
11962
  );
11880
11963
  return spanState ? contextManager.wrapSpanForStore(spanState.span) : currentSpanStore.getStore();
11881
11964
  }
@@ -11884,15 +11967,21 @@ function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelNam
11884
11967
  startChannel.unbindStore(currentSpanStore);
11885
11968
  };
11886
11969
  }
11887
- function logErrorAndEnd(states, event) {
11970
+ function logErrorAndEnd(states, event, channelName) {
11888
11971
  const spanData = states.get(event);
11889
11972
  if (!spanData) {
11890
11973
  return;
11891
11974
  }
11892
- spanData.span.log({
11893
- error: event.error.message
11894
- });
11895
- spanData.span.end();
11975
+ try {
11976
+ spanData.span.log({ error: event.error });
11977
+ } catch (error) {
11978
+ debugLogger.error(`Error logging failure for ${channelName}:`, error);
11979
+ }
11980
+ try {
11981
+ spanData.span.end();
11982
+ } catch (error) {
11983
+ debugLogger.error(`Error ending span for ${channelName}:`, error);
11984
+ }
11896
11985
  states.delete(event);
11897
11986
  }
11898
11987
  function runStreamingCompletionHook(args) {
@@ -11942,7 +12031,8 @@ function traceAsyncChannel(channel2, config) {
11942
12031
  tracingChannel2,
11943
12032
  states,
11944
12033
  config,
11945
- channelName
12034
+ channelName,
12035
+ channel2.instrumentationName
11946
12036
  );
11947
12037
  const handlers = {
11948
12038
  start: (event) => {
@@ -11953,7 +12043,8 @@ function traceAsyncChannel(channel2, config) {
11953
12043
  states,
11954
12044
  config,
11955
12045
  event,
11956
- channelName
12046
+ channelName,
12047
+ channel2.instrumentationName
11957
12048
  );
11958
12049
  },
11959
12050
  asyncEnd: (event) => {
@@ -11990,7 +12081,7 @@ function traceAsyncChannel(channel2, config) {
11990
12081
  }
11991
12082
  },
11992
12083
  error: (event) => {
11993
- logErrorAndEnd(states, event);
12084
+ logErrorAndEnd(states, event, channelName);
11994
12085
  }
11995
12086
  };
11996
12087
  tracingChannel2.subscribe(handlers);
@@ -12007,7 +12098,8 @@ function traceStreamingChannel(channel2, config) {
12007
12098
  tracingChannel2,
12008
12099
  states,
12009
12100
  config,
12010
- channelName
12101
+ channelName,
12102
+ channel2.instrumentationName
12011
12103
  );
12012
12104
  const handlers = {
12013
12105
  start: (event) => {
@@ -12018,7 +12110,8 @@ function traceStreamingChannel(channel2, config) {
12018
12110
  states,
12019
12111
  config,
12020
12112
  event,
12021
- channelName
12113
+ channelName,
12114
+ channel2.instrumentationName
12022
12115
  );
12023
12116
  },
12024
12117
  asyncEnd: (event) => {
@@ -12037,6 +12130,7 @@ function traceStreamingChannel(channel2, config) {
12037
12130
  }
12038
12131
  },
12039
12132
  onComplete: (chunks) => {
12133
+ let completion2;
12040
12134
  try {
12041
12135
  let output;
12042
12136
  let metrics;
@@ -12067,18 +12161,11 @@ function traceStreamingChannel(channel2, config) {
12067
12161
  } else if (metrics.time_to_first_token === void 0 && chunks.length > 0) {
12068
12162
  metrics.time_to_first_token = getCurrentUnixTimestamp() - startTime;
12069
12163
  }
12070
- runStreamingCompletionHook({
12071
- channelName,
12072
- chunks,
12073
- config,
12074
- endEvent: asyncEndEvent,
12164
+ completion2 = {
12075
12165
  ...metadata !== void 0 ? { metadata } : {},
12076
12166
  metrics,
12077
- output,
12078
- result: asyncEndEvent.result,
12079
- span,
12080
- startTime
12081
- });
12167
+ output
12168
+ };
12082
12169
  span.log({
12083
12170
  output,
12084
12171
  ...metadata !== void 0 ? { metadata } : {},
@@ -12090,11 +12177,49 @@ function traceStreamingChannel(channel2, config) {
12090
12177
  error
12091
12178
  );
12092
12179
  } finally {
12093
- span.end();
12180
+ try {
12181
+ span.end();
12182
+ } catch (error) {
12183
+ debugLogger.error(
12184
+ `Error ending span for ${channelName}:`,
12185
+ error
12186
+ );
12187
+ }
12094
12188
  states.delete(event);
12095
12189
  }
12190
+ if (completion2) {
12191
+ runStreamingCompletionHook({
12192
+ channelName,
12193
+ chunks,
12194
+ config,
12195
+ endEvent: asyncEndEvent,
12196
+ ...completion2.metadata !== void 0 ? { metadata: completion2.metadata } : {},
12197
+ metrics: completion2.metrics,
12198
+ output: completion2.output,
12199
+ result: asyncEndEvent.result,
12200
+ span,
12201
+ startTime
12202
+ });
12203
+ }
12096
12204
  },
12097
12205
  onError: (error) => {
12206
+ try {
12207
+ span.log({ error });
12208
+ } catch (loggingError) {
12209
+ debugLogger.error(
12210
+ `Error logging failure for ${channelName}:`,
12211
+ loggingError
12212
+ );
12213
+ }
12214
+ try {
12215
+ span.end();
12216
+ } catch (endingError) {
12217
+ debugLogger.error(
12218
+ `Error ending span for ${channelName}:`,
12219
+ endingError
12220
+ );
12221
+ }
12222
+ states.delete(event);
12098
12223
  runStreamingErrorHook({
12099
12224
  channelName,
12100
12225
  config,
@@ -12103,11 +12228,6 @@ function traceStreamingChannel(channel2, config) {
12103
12228
  span,
12104
12229
  startTime
12105
12230
  });
12106
- span.log({
12107
- error: error.message
12108
- });
12109
- span.end();
12110
- states.delete(event);
12111
12231
  }
12112
12232
  });
12113
12233
  return;
@@ -12122,6 +12242,7 @@ function traceStreamingChannel(channel2, config) {
12122
12242
  states.delete(event);
12123
12243
  return;
12124
12244
  }
12245
+ let completion;
12125
12246
  try {
12126
12247
  const output = config.extractOutput(
12127
12248
  asyncEndEvent.result,
@@ -12136,17 +12257,11 @@ function traceStreamingChannel(channel2, config) {
12136
12257
  asyncEndEvent.result,
12137
12258
  asyncEndEvent
12138
12259
  );
12139
- runStreamingCompletionHook({
12140
- channelName,
12141
- config,
12142
- endEvent: asyncEndEvent,
12260
+ completion = {
12143
12261
  ...normalizeMetadata(metadata) !== void 0 ? { metadata: normalizeMetadata(metadata) } : {},
12144
12262
  metrics,
12145
- output,
12146
- result: asyncEndEvent.result,
12147
- span,
12148
- startTime
12149
- });
12263
+ output
12264
+ };
12150
12265
  span.log({
12151
12266
  output,
12152
12267
  ...normalizeMetadata(metadata) !== void 0 ? { metadata: normalizeMetadata(metadata) } : {},
@@ -12155,12 +12270,30 @@ function traceStreamingChannel(channel2, config) {
12155
12270
  } catch (error) {
12156
12271
  debugLogger.error(`Error extracting output for ${channelName}:`, error);
12157
12272
  } finally {
12158
- span.end();
12273
+ try {
12274
+ span.end();
12275
+ } catch (error) {
12276
+ debugLogger.error(`Error ending span for ${channelName}:`, error);
12277
+ }
12159
12278
  states.delete(event);
12160
12279
  }
12280
+ if (completion) {
12281
+ runStreamingCompletionHook({
12282
+ channelName,
12283
+ config,
12284
+ endEvent: asyncEndEvent,
12285
+ ...completion.metadata !== void 0 ? { metadata: completion.metadata } : {},
12286
+ metrics: completion.metrics,
12287
+ output: completion.output,
12288
+ result: asyncEndEvent.result,
12289
+ span,
12290
+ startTime
12291
+ });
12292
+ }
12161
12293
  },
12162
12294
  error: (event) => {
12163
12295
  const spanData = states.get(event);
12296
+ logErrorAndEnd(states, event, channelName);
12164
12297
  if (spanData) {
12165
12298
  runStreamingErrorHook({
12166
12299
  channelName,
@@ -12171,7 +12304,6 @@ function traceStreamingChannel(channel2, config) {
12171
12304
  startTime: spanData.startTime
12172
12305
  });
12173
12306
  }
12174
- logErrorAndEnd(states, event);
12175
12307
  }
12176
12308
  };
12177
12309
  tracingChannel2.subscribe(handlers);
@@ -12188,7 +12320,8 @@ function traceSyncStreamChannel(channel2, config) {
12188
12320
  tracingChannel2,
12189
12321
  states,
12190
12322
  config,
12191
- channelName
12323
+ channelName,
12324
+ channel2.instrumentationName
12192
12325
  );
12193
12326
  const handlers = {
12194
12327
  start: (event) => {
@@ -12199,7 +12332,8 @@ function traceSyncStreamChannel(channel2, config) {
12199
12332
  states,
12200
12333
  config,
12201
12334
  event,
12202
- channelName
12335
+ channelName,
12336
+ channel2.instrumentationName
12203
12337
  );
12204
12338
  },
12205
12339
  end: (event) => {
@@ -12293,7 +12427,7 @@ function traceSyncStreamChannel(channel2, config) {
12293
12427
  handleResolvedResult(endEvent.result);
12294
12428
  },
12295
12429
  error: (event) => {
12296
- logErrorAndEnd(states, event);
12430
+ logErrorAndEnd(states, event, channelName);
12297
12431
  }
12298
12432
  };
12299
12433
  tracingChannel2.subscribe(handlers);
@@ -12472,7 +12606,8 @@ function processInputAttachments(input) {
12472
12606
  function channel(spec) {
12473
12607
  return spec;
12474
12608
  }
12475
- function defineChannels(pkg, channels) {
12609
+ function defineChannels(pkg, channels, options) {
12610
+ const { instrumentationName } = options;
12476
12611
  return Object.fromEntries(
12477
12612
  Object.entries(channels).map(([key, spec]) => {
12478
12613
  const fullChannelName = `orchestrion:${pkg}:${spec.channelName}`;
@@ -12485,6 +12620,7 @@ function defineChannels(pkg, channels) {
12485
12620
  key,
12486
12621
  {
12487
12622
  ...asyncSpec,
12623
+ instrumentationName,
12488
12624
  tracingChannel: tracingChannel3,
12489
12625
  tracePromise: (fn, context) => tracingChannel3().tracePromise(
12490
12626
  fn,
@@ -12502,6 +12638,7 @@ function defineChannels(pkg, channels) {
12502
12638
  key,
12503
12639
  {
12504
12640
  ...syncSpec,
12641
+ instrumentationName,
12505
12642
  tracingChannel: tracingChannel2,
12506
12643
  traceSync: (fn, context) => tracingChannel2().traceSync(
12507
12644
  fn,
@@ -12515,44 +12652,48 @@ function defineChannels(pkg, channels) {
12515
12652
  }
12516
12653
 
12517
12654
  // src/instrumentation/plugins/openai-channels.ts
12518
- var openAIChannels = defineChannels("openai", {
12519
- chatCompletionsCreate: channel({
12520
- channelName: "chat.completions.create",
12521
- kind: "async"
12522
- }),
12523
- embeddingsCreate: channel({
12524
- channelName: "embeddings.create",
12525
- kind: "async"
12526
- }),
12527
- betaChatCompletionsParse: channel({
12528
- channelName: "beta.chat.completions.parse",
12529
- kind: "async"
12530
- }),
12531
- betaChatCompletionsStream: channel({
12532
- channelName: "beta.chat.completions.stream",
12533
- kind: "sync-stream"
12534
- }),
12535
- moderationsCreate: channel({
12536
- channelName: "moderations.create",
12537
- kind: "async"
12538
- }),
12539
- responsesCreate: channel({
12540
- channelName: "responses.create",
12541
- kind: "async"
12542
- }),
12543
- responsesStream: channel({
12544
- channelName: "responses.stream",
12545
- kind: "sync-stream"
12546
- }),
12547
- responsesParse: channel({
12548
- channelName: "responses.parse",
12549
- kind: "async"
12550
- }),
12551
- responsesCompact: channel({
12552
- channelName: "responses.compact",
12553
- kind: "async"
12554
- })
12555
- });
12655
+ var openAIChannels = defineChannels(
12656
+ "openai",
12657
+ {
12658
+ chatCompletionsCreate: channel({
12659
+ channelName: "chat.completions.create",
12660
+ kind: "async"
12661
+ }),
12662
+ embeddingsCreate: channel({
12663
+ channelName: "embeddings.create",
12664
+ kind: "async"
12665
+ }),
12666
+ betaChatCompletionsParse: channel({
12667
+ channelName: "beta.chat.completions.parse",
12668
+ kind: "async"
12669
+ }),
12670
+ betaChatCompletionsStream: channel({
12671
+ channelName: "beta.chat.completions.stream",
12672
+ kind: "sync-stream"
12673
+ }),
12674
+ moderationsCreate: channel({
12675
+ channelName: "moderations.create",
12676
+ kind: "async"
12677
+ }),
12678
+ responsesCreate: channel({
12679
+ channelName: "responses.create",
12680
+ kind: "async"
12681
+ }),
12682
+ responsesStream: channel({
12683
+ channelName: "responses.stream",
12684
+ kind: "sync-stream"
12685
+ }),
12686
+ responsesParse: channel({
12687
+ channelName: "responses.parse",
12688
+ kind: "async"
12689
+ }),
12690
+ responsesCompact: channel({
12691
+ channelName: "responses.compact",
12692
+ kind: "async"
12693
+ })
12694
+ },
12695
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENAI }
12696
+ );
12556
12697
 
12557
12698
  // src/openai-utils.ts
12558
12699
  var BRAINTRUST_CACHED_STREAM_METRIC = "__braintrust_cached_metric";
@@ -13067,16 +13208,20 @@ function aggregateResponseStreamEvents(chunks, _streamResult, endEvent) {
13067
13208
  }
13068
13209
 
13069
13210
  // src/instrumentation/plugins/openai-codex-channels.ts
13070
- var openAICodexChannels = defineChannels("@openai/codex-sdk", {
13071
- run: channel({
13072
- channelName: "Thread.run",
13073
- kind: "async"
13074
- }),
13075
- runStreamed: channel({
13076
- channelName: "Thread.runStreamed",
13077
- kind: "async"
13078
- })
13079
- });
13211
+ var openAICodexChannels = defineChannels(
13212
+ "@openai/codex-sdk",
13213
+ {
13214
+ run: channel({
13215
+ channelName: "Thread.run",
13216
+ kind: "async"
13217
+ }),
13218
+ runStreamed: channel({
13219
+ channelName: "Thread.runStreamed",
13220
+ kind: "async"
13221
+ })
13222
+ },
13223
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENAI_CODEX }
13224
+ );
13080
13225
 
13081
13226
  // src/instrumentation/plugins/openai-codex-plugin.ts
13082
13227
  var PATCHED_STREAMED_TURN = /* @__PURE__ */ Symbol.for(
@@ -13164,10 +13309,15 @@ function startCodexRun(event, operation) {
13164
13309
  provider: "openai",
13165
13310
  ...event.moduleVersion ? { "openai_codex.version": event.moduleVersion } : {}
13166
13311
  };
13167
- const span = startSpan({
13168
- name: "OpenAI Codex",
13169
- spanAttributes: { type: "task" /* TASK */ }
13170
- });
13312
+ const span = startSpan(
13313
+ withSpanInstrumentationName(
13314
+ {
13315
+ name: "OpenAI Codex",
13316
+ spanAttributes: { type: "task" /* TASK */ }
13317
+ },
13318
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
13319
+ )
13320
+ );
13171
13321
  const startTime = getCurrentUnixTimestamp();
13172
13322
  safeLog(span, {
13173
13323
  input: sanitizedInput,
@@ -13316,7 +13466,12 @@ async function createCompletedItemSpan(state, item) {
13316
13466
  if (!spanArgs) {
13317
13467
  return;
13318
13468
  }
13319
- const span = startSpan(spanArgs.start);
13469
+ const span = startSpan(
13470
+ withSpanInstrumentationName(
13471
+ spanArgs.start,
13472
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
13473
+ )
13474
+ );
13320
13475
  safeLog(span, spanArgs.end);
13321
13476
  span.end();
13322
13477
  }
@@ -13358,15 +13513,20 @@ async function ensureActiveLlmSpan(state) {
13358
13513
  ...state.metadata["openai_codex.thread_id"] ? { "openai_codex.thread_id": state.metadata["openai_codex.thread_id"] } : {},
13359
13514
  "openai_codex.llm_sequence": sequence
13360
13515
  };
13361
- const span = startSpan({
13362
- event: {
13363
- ...sequence === 1 ? { input: state.input } : {},
13364
- metadata
13365
- },
13366
- name: "OpenAI Codex LLM",
13367
- parent: await state.span.export(),
13368
- spanAttributes: { type: "llm" /* LLM */ }
13369
- });
13516
+ const span = startSpan(
13517
+ withSpanInstrumentationName(
13518
+ {
13519
+ event: {
13520
+ ...sequence === 1 ? { input: state.input } : {},
13521
+ metadata
13522
+ },
13523
+ name: "OpenAI Codex LLM",
13524
+ parent: await state.span.export(),
13525
+ spanAttributes: { type: "llm" /* LLM */ }
13526
+ },
13527
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
13528
+ )
13529
+ );
13370
13530
  state.activeLlmSpan = {
13371
13531
  anonymousMessages: [],
13372
13532
  anonymousReasoning: [],
@@ -13412,7 +13572,15 @@ async function startCodexItemSpan(state, item) {
13412
13572
  if (!spanArgs) {
13413
13573
  return;
13414
13574
  }
13415
- state.activeItemSpans.set(itemId, startSpan(spanArgs.start));
13575
+ state.activeItemSpans.set(
13576
+ itemId,
13577
+ startSpan(
13578
+ withSpanInstrumentationName(
13579
+ spanArgs.start,
13580
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
13581
+ )
13582
+ )
13583
+ );
13416
13584
  }
13417
13585
  function updateCodexItem(state, item) {
13418
13586
  if (item.type === "agent_message" && typeof item.text === "string") {
@@ -13722,20 +13890,24 @@ function extractAnthropicCacheTokens(cacheReadTokens = 0, cacheCreationTokens =
13722
13890
  }
13723
13891
 
13724
13892
  // src/instrumentation/plugins/anthropic-channels.ts
13725
- var anthropicChannels = defineChannels("@anthropic-ai/sdk", {
13726
- messagesCreate: channel({
13727
- channelName: "messages.create",
13728
- kind: "async"
13729
- }),
13730
- betaMessagesCreate: channel({
13731
- channelName: "beta.messages.create",
13732
- kind: "async"
13733
- }),
13734
- betaMessagesToolRunner: channel({
13735
- channelName: "beta.messages.toolRunner",
13736
- kind: "sync-stream"
13737
- })
13738
- });
13893
+ var anthropicChannels = defineChannels(
13894
+ "@anthropic-ai/sdk",
13895
+ {
13896
+ messagesCreate: channel({
13897
+ channelName: "messages.create",
13898
+ kind: "async"
13899
+ }),
13900
+ betaMessagesCreate: channel({
13901
+ channelName: "beta.messages.create",
13902
+ kind: "async"
13903
+ }),
13904
+ betaMessagesToolRunner: channel({
13905
+ channelName: "beta.messages.toolRunner",
13906
+ kind: "sync-stream"
13907
+ })
13908
+ },
13909
+ { instrumentationName: INSTRUMENTATION_NAMES.ANTHROPIC }
13910
+ );
13739
13911
 
13740
13912
  // src/instrumentation/plugins/anthropic-plugin.ts
13741
13913
  var ANTHROPIC_TOOL_RUNNER_TOOL_WRAPPED = /* @__PURE__ */ Symbol.for(
@@ -13808,12 +13980,17 @@ var AnthropicPlugin = class extends BasePlugin {
13808
13980
  return;
13809
13981
  }
13810
13982
  const params = event.arguments[0] ?? {};
13811
- const span = startSpan({
13812
- name: "anthropic.beta.messages.toolRunner",
13813
- spanAttributes: {
13814
- type: "task" /* TASK */
13815
- }
13816
- });
13983
+ const span = startSpan(
13984
+ withSpanInstrumentationName(
13985
+ {
13986
+ name: "anthropic.beta.messages.toolRunner",
13987
+ spanAttributes: {
13988
+ type: "task" /* TASK */
13989
+ }
13990
+ },
13991
+ INSTRUMENTATION_NAMES.ANTHROPIC
13992
+ )
13993
+ );
13817
13994
  span.log({
13818
13995
  input: processAttachmentsInInput(
13819
13996
  coalesceInput(params.messages ?? [], params.system)
@@ -13954,19 +14131,22 @@ function wrapAnthropicToolRunnerTool(tool, index, state) {
13954
14131
  return finalizeError(error);
13955
14132
  }
13956
14133
  },
13957
- {
13958
- event: {
13959
- input: getAnthropicToolRunnerInput(args),
13960
- metadata: {
13961
- "gen_ai.tool.name": toolName,
13962
- provider: "anthropic"
14134
+ withSpanInstrumentationName(
14135
+ {
14136
+ event: {
14137
+ input: getAnthropicToolRunnerInput(args),
14138
+ metadata: {
14139
+ "gen_ai.tool.name": toolName,
14140
+ provider: "anthropic"
14141
+ }
14142
+ },
14143
+ name: `tool: ${toolName}`,
14144
+ spanAttributes: {
14145
+ type: "tool" /* TOOL */
13963
14146
  }
13964
14147
  },
13965
- name: `tool: ${toolName}`,
13966
- spanAttributes: {
13967
- type: "tool" /* TOOL */
13968
- }
13969
- }
14148
+ INSTRUMENTATION_NAMES.ANTHROPIC
14149
+ )
13970
14150
  );
13971
14151
  },
13972
14152
  writable: runDescriptor?.writable ?? true
@@ -14561,6 +14741,267 @@ function currentWorkflowAgentWrapperSpan() {
14561
14741
  return void 0;
14562
14742
  }
14563
14743
 
14744
+ // src/wrappers/ai-sdk/harness-agent-context.ts
14745
+ var BRAINTRUST_TURN_CONTEXT_KEY = "__braintrust_trace_context";
14746
+ var sessionTurnParents = /* @__PURE__ */ new WeakMap();
14747
+ var wrapperTurnParents = /* @__PURE__ */ new WeakMap();
14748
+ var patchedLifecycleMethods = /* @__PURE__ */ new WeakMap();
14749
+ var harnessTurnParentStore;
14750
+ function serializedTurnContext(value) {
14751
+ if (!isObject(value)) {
14752
+ return void 0;
14753
+ }
14754
+ const context = value[BRAINTRUST_TURN_CONTEXT_KEY];
14755
+ if (!isObject(context) || typeof context.parent !== "string" || typeof context.sessionId !== "string" || typeof context.signature !== "string") {
14756
+ return void 0;
14757
+ }
14758
+ const expectedSignature = signTurnContext({
14759
+ parent: context.parent,
14760
+ sessionId: context.sessionId
14761
+ });
14762
+ if (!expectedSignature || !isomorph_default.timingSafeEqual?.(context.signature, expectedSignature)) {
14763
+ return void 0;
14764
+ }
14765
+ const parent = SpanComponentsV4.fromStr(context.parent);
14766
+ if (!parent.data.row_id || !parent.data.root_span_id || !parent.data.span_id) {
14767
+ return void 0;
14768
+ }
14769
+ return {
14770
+ parent: context.parent,
14771
+ sessionId: context.sessionId
14772
+ };
14773
+ }
14774
+ function signTurnContext(context) {
14775
+ const secret = _internalGetGlobalState()._internalGetTraceContextSigningSecret();
14776
+ return secret ? isomorph_default.hmacSha256?.(
14777
+ secret,
14778
+ JSON.stringify([BRAINTRUST_TURN_CONTEXT_KEY, context])
14779
+ ) : void 0;
14780
+ }
14781
+ function continuationParentFromCreateSessionParams(params) {
14782
+ if (!isObject(params)) {
14783
+ return void 0;
14784
+ }
14785
+ const continuation = params.continueFrom ?? (isObject(params.resumeFrom) ? params.resumeFrom.continueFrom : void 0);
14786
+ const context = serializedTurnContext(continuation);
14787
+ if (!context) {
14788
+ return void 0;
14789
+ }
14790
+ if (params.sessionId !== context.sessionId) {
14791
+ return void 0;
14792
+ }
14793
+ return context.parent;
14794
+ }
14795
+ function exportSpanSynchronously(span) {
14796
+ const parentInfo = span.getParentInfo();
14797
+ if (!parentInfo) {
14798
+ return void 0;
14799
+ }
14800
+ const objectId = parentInfo.objectId.getSync().value;
14801
+ if (!objectId && !parentInfo.computeObjectMetadataArgs) {
14802
+ return void 0;
14803
+ }
14804
+ return new SpanComponentsV4({
14805
+ object_type: parentInfo.objectType,
14806
+ ...objectId ? { object_id: objectId } : {
14807
+ compute_object_metadata_args: parentInfo.computeObjectMetadataArgs ?? {}
14808
+ },
14809
+ row_id: span.id,
14810
+ root_span_id: span.rootSpanId,
14811
+ span_id: span.spanId
14812
+ }).toStr();
14813
+ }
14814
+ function exportedParent(parent) {
14815
+ return typeof parent === "string" ? parent : exportSpanSynchronously(parent);
14816
+ }
14817
+ function addSerializedContext(args) {
14818
+ if (!isObject(args.continuation) || args.sessionId === void 0) {
14819
+ return;
14820
+ }
14821
+ const parent = exportedParent(args.parent);
14822
+ if (!parent) {
14823
+ return;
14824
+ }
14825
+ const context = {
14826
+ parent,
14827
+ sessionId: args.sessionId
14828
+ };
14829
+ const signature = signTurnContext(context);
14830
+ if (!signature) {
14831
+ return;
14832
+ }
14833
+ Object.defineProperty(args.continuation, BRAINTRUST_TURN_CONTEXT_KEY, {
14834
+ configurable: true,
14835
+ enumerable: true,
14836
+ value: {
14837
+ ...context,
14838
+ signature
14839
+ },
14840
+ writable: true
14841
+ });
14842
+ }
14843
+ function lifecycleMethodDescriptor(session, method) {
14844
+ let owner = session;
14845
+ while (owner) {
14846
+ const descriptor = Object.getOwnPropertyDescriptor(owner, method);
14847
+ if (descriptor) {
14848
+ return { descriptor, owner };
14849
+ }
14850
+ owner = Object.getPrototypeOf(owner);
14851
+ }
14852
+ return void 0;
14853
+ }
14854
+ function patchLifecycleMethod(session, method) {
14855
+ let resolvedDescriptor;
14856
+ try {
14857
+ resolvedDescriptor = lifecycleMethodDescriptor(session, method);
14858
+ } catch {
14859
+ return;
14860
+ }
14861
+ if (!resolvedDescriptor || !("value" in resolvedDescriptor.descriptor) || typeof resolvedDescriptor.descriptor.value !== "function") {
14862
+ return;
14863
+ }
14864
+ const { descriptor, owner } = resolvedDescriptor;
14865
+ const patched = patchedLifecycleMethods.get(owner);
14866
+ if (patched?.has(method)) {
14867
+ return;
14868
+ }
14869
+ const original = descriptor.value;
14870
+ const replacement = function(...args) {
14871
+ const result = Reflect.apply(original, this, args);
14872
+ const addContext = (state) => {
14873
+ try {
14874
+ const parent = sessionTurnParents.get(this);
14875
+ if (!parent) {
14876
+ return;
14877
+ }
14878
+ const continuation = method === "suspendTurn" ? state : isObject(state) ? state.continueFrom : void 0;
14879
+ addSerializedContext({
14880
+ continuation,
14881
+ parent,
14882
+ sessionId: typeof this.sessionId === "string" ? this.sessionId : void 0
14883
+ });
14884
+ } catch {
14885
+ }
14886
+ };
14887
+ try {
14888
+ if (isObject(result) && typeof result.then === "function") {
14889
+ void Promise.resolve(result).then(addContext, () => {
14890
+ });
14891
+ } else {
14892
+ addContext(result);
14893
+ }
14894
+ } catch {
14895
+ }
14896
+ return result;
14897
+ };
14898
+ try {
14899
+ Object.defineProperty(owner, method, {
14900
+ ...descriptor,
14901
+ value: replacement
14902
+ });
14903
+ const ownerMethods = patched ?? /* @__PURE__ */ new Set();
14904
+ ownerMethods.add(method);
14905
+ if (!patched) {
14906
+ patchedLifecycleMethods.set(owner, ownerMethods);
14907
+ }
14908
+ } catch {
14909
+ }
14910
+ }
14911
+ function patchLifecycleMethods(session) {
14912
+ patchLifecycleMethod(session, "suspendTurn");
14913
+ patchLifecycleMethod(session, "detach");
14914
+ patchLifecycleMethod(session, "stop");
14915
+ }
14916
+ function registerHarnessTurnSpan(args) {
14917
+ if (!isObject(args.session)) {
14918
+ return;
14919
+ }
14920
+ const session = args.session;
14921
+ sessionTurnParents.set(session, args.span);
14922
+ wrapperTurnParents.set(args.span, args.span);
14923
+ patchLifecycleMethods(session);
14924
+ }
14925
+ function harnessContinuationParent(session) {
14926
+ return isObject(session) ? sessionTurnParents.get(session) : void 0;
14927
+ }
14928
+ function captureHarnessCreateSessionParent(params) {
14929
+ try {
14930
+ return continuationParentFromCreateSessionParams(params);
14931
+ } catch {
14932
+ return void 0;
14933
+ }
14934
+ }
14935
+ function registerHarnessSessionParent(session, parent) {
14936
+ if (!parent || !isObject(session)) {
14937
+ return;
14938
+ }
14939
+ const harnessSession = session;
14940
+ sessionTurnParents.set(harnessSession, parent);
14941
+ patchLifecycleMethods(harnessSession);
14942
+ }
14943
+ function currentHarnessTurnParent() {
14944
+ return harnessTurnParentStore?.getStore() ?? wrapperTurnParents.get(currentSpan());
14945
+ }
14946
+ function bindHarnessTurnParentToStart(tracingChannel2, parentFromEvent) {
14947
+ const startChannel = tracingChannel2.start;
14948
+ if (!startChannel) {
14949
+ return () => {
14950
+ };
14951
+ }
14952
+ harnessTurnParentStore ??= isomorph_default.newAsyncLocalStorage();
14953
+ const store = harnessTurnParentStore;
14954
+ startChannel.bindStore(
14955
+ store,
14956
+ (event) => parentFromEvent(event) ?? store.getStore()
14957
+ );
14958
+ return () => {
14959
+ startChannel.unbindStore(store);
14960
+ };
14961
+ }
14962
+ function startHarnessTurnChildSpan(parent, args) {
14963
+ const spanArgs = withSpanInstrumentationName(
14964
+ args,
14965
+ INSTRUMENTATION_NAMES.AI_SDK
14966
+ );
14967
+ return typeof parent === "string" ? startSpan({ ...spanArgs, parent }) : parent.startSpan(spanArgs);
14968
+ }
14969
+ function updateHarnessTurn(parent, update = {}) {
14970
+ if (!parent) {
14971
+ return;
14972
+ }
14973
+ const log3 = (event) => {
14974
+ if (typeof parent === "string") {
14975
+ updateSpan({ exported: parent, ...event });
14976
+ } else {
14977
+ parent.log(event);
14978
+ }
14979
+ };
14980
+ try {
14981
+ if (Object.prototype.hasOwnProperty.call(update, "output")) {
14982
+ log3({ output: null });
14983
+ }
14984
+ log3(update);
14985
+ } catch {
14986
+ }
14987
+ }
14988
+ function endHarnessTurn(parent) {
14989
+ const endTime = getCurrentUnixTimestamp();
14990
+ if (!parent) {
14991
+ return endTime;
14992
+ }
14993
+ try {
14994
+ const event = { metrics: { end: endTime } };
14995
+ if (typeof parent === "string") {
14996
+ updateSpan({ exported: parent, ...event });
14997
+ } else {
14998
+ parent.log(event);
14999
+ }
15000
+ } catch {
15001
+ }
15002
+ return endTime;
15003
+ }
15004
+
14564
15005
  // src/wrappers/ai-sdk/telemetry.ts
14565
15006
  function braintrustAISDKTelemetry() {
14566
15007
  const operations = /* @__PURE__ */ new Map();
@@ -14579,14 +15020,17 @@ function braintrustAISDKTelemetry() {
14579
15020
  console.error(`Error in Braintrust AI SDK telemetry ${name}:`, error);
14580
15021
  }
14581
15022
  };
14582
- const startChildSpan = (operationKey, name, type, event) => {
15023
+ const startChildSpan = (operationKey, name, type, event, parentOverride) => {
14583
15024
  const parent = operations.get(operationKey)?.span;
14584
- const spanArgs = {
14585
- name,
14586
- spanAttributes: { type },
14587
- ...event ? { event } : {}
14588
- };
14589
- const span = parent ? parent.startSpan(spanArgs) : startSpan(spanArgs);
15025
+ const spanArgs = withSpanInstrumentationName(
15026
+ {
15027
+ name,
15028
+ spanAttributes: { type },
15029
+ ...event ? { event } : {}
15030
+ },
15031
+ INSTRUMENTATION_NAMES.AI_SDK
15032
+ );
15033
+ const span = parentOverride ? startHarnessTurnChildSpan(parentOverride, spanArgs) : parent ? parent.startSpan(spanArgs) : startSpan(spanArgs);
14590
15034
  const state = operations.get(operationKey);
14591
15035
  if (state && type === "llm" /* LLM */) {
14592
15036
  state.hadModelChild = true;
@@ -14866,14 +15310,30 @@ function braintrustAISDKTelemetry() {
14866
15310
  const workflowAgent = operationName === "WorkflowAgent.stream";
14867
15311
  const wrapperSpan = workflowAgent ? currentWorkflowAgentWrapperSpan() : void 0;
14868
15312
  const ownsSpan = !wrapperSpan;
14869
- const span = ownsSpan ? startSpan({
14870
- name: operationName,
14871
- spanAttributes: { type: "function" /* FUNCTION */ }
14872
- }) : wrapperSpan;
15313
+ const harnessTurnParent = currentHarnessTurnParent();
15314
+ const span = ownsSpan ? harnessTurnParent ? startHarnessTurnChildSpan(
15315
+ harnessTurnParent,
15316
+ withSpanInstrumentationName(
15317
+ {
15318
+ name: operationName,
15319
+ spanAttributes: { type: "function" /* FUNCTION */ }
15320
+ },
15321
+ INSTRUMENTATION_NAMES.AI_SDK
15322
+ )
15323
+ ) : startSpan(
15324
+ withSpanInstrumentationName(
15325
+ {
15326
+ name: operationName,
15327
+ spanAttributes: { type: "function" /* FUNCTION */ }
15328
+ },
15329
+ INSTRUMENTATION_NAMES.AI_SDK
15330
+ )
15331
+ ) : wrapperSpan;
14873
15332
  const operationKey = createOperationKey(event, operationName);
14874
15333
  registerOperation({
14875
15334
  callId: event.callId,
14876
15335
  hadModelChild: false,
15336
+ harnessTurnParent,
14877
15337
  loggedInput: false,
14878
15338
  operationName,
14879
15339
  operationKey,
@@ -15114,7 +15574,8 @@ function braintrustAISDKTelemetry() {
15114
15574
  toolCallId,
15115
15575
  ...typeof event.toolCall.toolName === "string" ? { toolName: event.toolCall.toolName } : {}
15116
15576
  }
15117
- }
15577
+ },
15578
+ state?.harnessTurnParent
15118
15579
  );
15119
15580
  toolSpans.set(toolCallId, { operationKey, span });
15120
15581
  });
@@ -15350,92 +15811,102 @@ function finishOutput(result, operationName) {
15350
15811
  }
15351
15812
 
15352
15813
  // src/instrumentation/plugins/ai-sdk-channels.ts
15353
- var aiSDKChannels = defineChannels("ai", {
15354
- generateText: channel({
15355
- channelName: "generateText",
15356
- kind: "async"
15357
- }),
15358
- streamText: channel({
15359
- channelName: "streamText",
15360
- kind: "async"
15361
- }),
15362
- streamTextSync: channel({
15363
- channelName: "streamText.sync",
15364
- kind: "sync-stream"
15365
- }),
15366
- generateObject: channel({
15367
- channelName: "generateObject",
15368
- kind: "async"
15369
- }),
15370
- streamObject: channel({
15371
- channelName: "streamObject",
15372
- kind: "async"
15373
- }),
15374
- streamObjectSync: channel({
15375
- channelName: "streamObject.sync",
15376
- kind: "sync-stream"
15377
- }),
15378
- embed: channel(
15379
- {
15814
+ var aiSDKChannels = defineChannels(
15815
+ "ai",
15816
+ {
15817
+ generateText: channel({
15818
+ channelName: "generateText",
15819
+ kind: "async"
15820
+ }),
15821
+ streamText: channel({
15822
+ channelName: "streamText",
15823
+ kind: "async"
15824
+ }),
15825
+ streamTextSync: channel({
15826
+ channelName: "streamText.sync",
15827
+ kind: "sync-stream"
15828
+ }),
15829
+ generateObject: channel({
15830
+ channelName: "generateObject",
15831
+ kind: "async"
15832
+ }),
15833
+ streamObject: channel({
15834
+ channelName: "streamObject",
15835
+ kind: "async"
15836
+ }),
15837
+ streamObjectSync: channel({
15838
+ channelName: "streamObject.sync",
15839
+ kind: "sync-stream"
15840
+ }),
15841
+ embed: channel({
15380
15842
  channelName: "embed",
15381
15843
  kind: "async"
15382
- }
15383
- ),
15384
- embedMany: channel({
15385
- channelName: "embedMany",
15386
- kind: "async"
15387
- }),
15388
- rerank: channel({
15389
- channelName: "rerank",
15390
- kind: "async"
15391
- }),
15392
- agentGenerate: channel({
15393
- channelName: "Agent.generate",
15394
- kind: "async"
15395
- }),
15396
- agentStream: channel({
15397
- channelName: "Agent.stream",
15398
- kind: "async"
15399
- }),
15400
- agentStreamSync: channel({
15401
- channelName: "Agent.stream.sync",
15402
- kind: "sync-stream"
15403
- }),
15404
- toolLoopAgentGenerate: channel({
15405
- channelName: "ToolLoopAgent.generate",
15406
- kind: "async"
15407
- }),
15408
- toolLoopAgentStream: channel({
15409
- channelName: "ToolLoopAgent.stream",
15410
- kind: "async"
15411
- }),
15412
- workflowAgentStream: channel({
15413
- channelName: "WorkflowAgent.stream",
15414
- kind: "async"
15415
- }),
15416
- v7CreateTelemetryDispatcher: channel({
15417
- channelName: "createTelemetryDispatcher",
15418
- kind: "sync-stream"
15419
- })
15420
- });
15421
- var harnessAgentChannels = defineChannels("@ai-sdk/harness", {
15422
- generate: channel({
15423
- channelName: "HarnessAgent.generate",
15424
- kind: "async"
15425
- }),
15426
- stream: channel({
15427
- channelName: "HarnessAgent.stream",
15428
- kind: "async"
15429
- }),
15430
- continueGenerate: channel({
15431
- channelName: "HarnessAgent.continueGenerate",
15432
- kind: "async"
15433
- }),
15434
- continueStream: channel({
15435
- channelName: "HarnessAgent.continueStream",
15436
- kind: "async"
15437
- })
15438
- });
15844
+ }),
15845
+ embedMany: channel({
15846
+ channelName: "embedMany",
15847
+ kind: "async"
15848
+ }),
15849
+ rerank: channel({
15850
+ channelName: "rerank",
15851
+ kind: "async"
15852
+ }),
15853
+ agentGenerate: channel({
15854
+ channelName: "Agent.generate",
15855
+ kind: "async"
15856
+ }),
15857
+ agentStream: channel({
15858
+ channelName: "Agent.stream",
15859
+ kind: "async"
15860
+ }),
15861
+ agentStreamSync: channel({
15862
+ channelName: "Agent.stream.sync",
15863
+ kind: "sync-stream"
15864
+ }),
15865
+ toolLoopAgentGenerate: channel({
15866
+ channelName: "ToolLoopAgent.generate",
15867
+ kind: "async"
15868
+ }),
15869
+ toolLoopAgentStream: channel({
15870
+ channelName: "ToolLoopAgent.stream",
15871
+ kind: "async"
15872
+ }),
15873
+ workflowAgentStream: channel({
15874
+ channelName: "WorkflowAgent.stream",
15875
+ kind: "async"
15876
+ }),
15877
+ v7CreateTelemetryDispatcher: channel({
15878
+ channelName: "createTelemetryDispatcher",
15879
+ kind: "sync-stream"
15880
+ })
15881
+ },
15882
+ { instrumentationName: INSTRUMENTATION_NAMES.AI_SDK }
15883
+ );
15884
+ var harnessAgentChannels = defineChannels(
15885
+ "@ai-sdk/harness",
15886
+ {
15887
+ createSession: channel({
15888
+ channelName: "HarnessAgent.createSession",
15889
+ kind: "async"
15890
+ }),
15891
+ generate: channel({
15892
+ channelName: "HarnessAgent.generate",
15893
+ kind: "async"
15894
+ }),
15895
+ stream: channel({
15896
+ channelName: "HarnessAgent.stream",
15897
+ kind: "async"
15898
+ }),
15899
+ continueGenerate: channel({
15900
+ channelName: "HarnessAgent.continueGenerate",
15901
+ kind: "async"
15902
+ }),
15903
+ continueStream: channel({
15904
+ channelName: "HarnessAgent.continueStream",
15905
+ kind: "async"
15906
+ })
15907
+ },
15908
+ { instrumentationName: INSTRUMENTATION_NAMES.AI_SDK }
15909
+ );
15439
15910
 
15440
15911
  // src/instrumentation/plugins/ai-sdk-plugin.ts
15441
15912
  var DEFAULT_DENY_OUTPUT_PATHS = [
@@ -15512,6 +15983,17 @@ var AISDKPlugin = class extends BasePlugin {
15512
15983
  subscribeToAISDK() {
15513
15984
  const denyOutputPaths = this.config.denyOutputPaths || DEFAULT_DENY_OUTPUT_PATHS;
15514
15985
  this.unsubscribers.push(subscribeToAISDKV7TelemetryDispatcher());
15986
+ this.unsubscribers.push(subscribeToHarnessAgentCreateSession());
15987
+ this.unsubscribers.push(
15988
+ subscribeToHarnessContinuation(
15989
+ harnessAgentChannels.continueGenerate,
15990
+ denyOutputPaths
15991
+ ),
15992
+ subscribeToHarnessContinuation(
15993
+ harnessAgentChannels.continueStream,
15994
+ denyOutputPaths
15995
+ )
15996
+ );
15515
15997
  this.unsubscribers.push(
15516
15998
  traceStreamingChannel(aiSDKChannels.generateText, {
15517
15999
  name: "generateText",
@@ -15707,8 +16189,9 @@ var AISDKPlugin = class extends BasePlugin {
15707
16189
  this.unsubscribers.push(
15708
16190
  traceStreamingChannel(harnessAgentChannels.generate, {
15709
16191
  name: "HarnessAgent.generate",
16192
+ startSpan: _internalStartSpanWithInitialMerge,
15710
16193
  type: "task" /* TASK */,
15711
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
16194
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
15712
16195
  extractOutput: (result, endEvent) => processAISDKOutput(
15713
16196
  result,
15714
16197
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -15720,8 +16203,9 @@ var AISDKPlugin = class extends BasePlugin {
15720
16203
  this.unsubscribers.push(
15721
16204
  traceStreamingChannel(harnessAgentChannels.stream, {
15722
16205
  name: "HarnessAgent.stream",
16206
+ startSpan: _internalStartSpanWithInitialMerge,
15723
16207
  type: "task" /* TASK */,
15724
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
16208
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
15725
16209
  extractOutput: (result, endEvent) => processAISDKOutput(
15726
16210
  result,
15727
16211
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -15746,8 +16230,10 @@ var AISDKPlugin = class extends BasePlugin {
15746
16230
  this.unsubscribers.push(
15747
16231
  traceStreamingChannel(harnessAgentChannels.continueGenerate, {
15748
16232
  name: "HarnessAgent.continueGenerate",
16233
+ shouldTrace: (args) => !harnessContinuationParent(harnessSessionFromArguments(args)),
16234
+ startSpan: _internalStartSpanWithInitialMerge,
15749
16235
  type: "task" /* TASK */,
15750
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
16236
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
15751
16237
  extractOutput: (result, endEvent) => processAISDKOutput(
15752
16238
  result,
15753
16239
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -15759,8 +16245,10 @@ var AISDKPlugin = class extends BasePlugin {
15759
16245
  this.unsubscribers.push(
15760
16246
  traceStreamingChannel(harnessAgentChannels.continueStream, {
15761
16247
  name: "HarnessAgent.continueStream",
16248
+ shouldTrace: (args) => !harnessContinuationParent(harnessSessionFromArguments(args)),
16249
+ startSpan: _internalStartSpanWithInitialMerge,
15762
16250
  type: "task" /* TASK */,
15763
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
16251
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
15764
16252
  extractOutput: (result, endEvent) => processAISDKOutput(
15765
16253
  result,
15766
16254
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -15852,6 +16340,8 @@ var AISDKPlugin = class extends BasePlugin {
15852
16340
  defaultDenyOutputPaths: denyOutputPaths,
15853
16341
  endEvent,
15854
16342
  onComplete: () => unregisterWorkflowAgentWrapperSpan(span),
16343
+ onCancel: () => unregisterWorkflowAgentWrapperSpan(span),
16344
+ onError: () => unregisterWorkflowAgentWrapperSpan(span),
15855
16345
  result,
15856
16346
  span,
15857
16347
  startTime
@@ -15860,6 +16350,153 @@ var AISDKPlugin = class extends BasePlugin {
15860
16350
  );
15861
16351
  }
15862
16352
  };
16353
+ function subscribeToHarnessAgentCreateSession() {
16354
+ const channel2 = harnessAgentChannels.createSession.tracingChannel();
16355
+ const parents = /* @__PURE__ */ new WeakMap();
16356
+ const handlers = {
16357
+ start: (event) => {
16358
+ const parent = captureHarnessCreateSessionParent(event.arguments?.[0]);
16359
+ if (parent) {
16360
+ parents.set(event, parent);
16361
+ }
16362
+ },
16363
+ asyncEnd: (event) => {
16364
+ registerHarnessSessionParent(event.result, parents.get(event));
16365
+ parents.delete(event);
16366
+ },
16367
+ error: (event) => {
16368
+ parents.delete(event);
16369
+ }
16370
+ };
16371
+ channel2.subscribe(handlers);
16372
+ return () => channel2.unsubscribe(handlers);
16373
+ }
16374
+ function harnessContinuationParentFromEvent(event) {
16375
+ try {
16376
+ return harnessContinuationParent(event.arguments?.[0]?.session);
16377
+ } catch {
16378
+ return void 0;
16379
+ }
16380
+ }
16381
+ function subscribeToHarnessContinuation(continuationChannel, defaultDenyOutputPaths) {
16382
+ const channel2 = continuationChannel.tracingChannel();
16383
+ const parents = /* @__PURE__ */ new WeakMap();
16384
+ const startTimes = /* @__PURE__ */ new WeakMap();
16385
+ const unbindParentStore = bindHarnessTurnParentToStart(
16386
+ channel2,
16387
+ harnessContinuationParentFromEvent
16388
+ );
16389
+ const handlers = {
16390
+ start: (event) => {
16391
+ const parent = harnessContinuationParentFromEvent(event);
16392
+ if (!parent) {
16393
+ return;
16394
+ }
16395
+ parents.set(event, parent);
16396
+ startTimes.set(event, getCurrentUnixTimestamp());
16397
+ try {
16398
+ const params = event.arguments?.[0];
16399
+ if (params) {
16400
+ prepareAISDKHarnessAgentInput(params, event.self);
16401
+ }
16402
+ } catch (error) {
16403
+ debugLogger.error(
16404
+ "Error preparing Harness continuation telemetry:",
16405
+ error
16406
+ );
16407
+ }
16408
+ },
16409
+ asyncEnd: (event) => {
16410
+ const parent = parents.get(event);
16411
+ const startTime = startTimes.get(event) ?? getCurrentUnixTimestamp();
16412
+ parents.delete(event);
16413
+ startTimes.delete(event);
16414
+ if (!parent) {
16415
+ return;
16416
+ }
16417
+ const endEvent = event;
16418
+ const span = {
16419
+ end: () => endHarnessTurn(parent),
16420
+ log: (update) => updateHarnessTurn(
16421
+ parent,
16422
+ Object.prototype.hasOwnProperty.call(update, "error") && !Object.prototype.hasOwnProperty.call(update, "output") ? { ...update, output: null } : update
16423
+ )
16424
+ };
16425
+ try {
16426
+ if (isAsyncIterable(endEvent.result)) {
16427
+ patchStreamIfNeeded(endEvent.result, {
16428
+ onComplete: (chunks) => {
16429
+ try {
16430
+ const { metadata, metrics, output } = aggregateAISDKChunks(
16431
+ chunks,
16432
+ endEvent.result,
16433
+ endEvent
16434
+ );
16435
+ span.log({
16436
+ ...metadata ? { metadata } : {},
16437
+ metrics,
16438
+ output
16439
+ });
16440
+ } catch (error) {
16441
+ debugLogger.error(
16442
+ "Error aggregating Harness continuation stream:",
16443
+ error
16444
+ );
16445
+ } finally {
16446
+ span.end();
16447
+ }
16448
+ },
16449
+ onError: (error) => {
16450
+ span.log({ error: toLoggedError(error), output: null });
16451
+ span.end();
16452
+ }
16453
+ });
16454
+ return;
16455
+ }
16456
+ if (patchAISDKStreamingResult({
16457
+ defaultDenyOutputPaths,
16458
+ endEvent,
16459
+ result: endEvent.result,
16460
+ resolvePromiseUsage: true,
16461
+ span,
16462
+ startTime
16463
+ })) {
16464
+ return;
16465
+ }
16466
+ finalizeAISDKChildTracing(endEvent);
16467
+ span.log({
16468
+ metrics: extractTokenMetrics(endEvent.result),
16469
+ output: processAISDKOutput(
16470
+ endEvent.result,
16471
+ resolveDenyOutputPaths(endEvent, defaultDenyOutputPaths)
16472
+ )
16473
+ });
16474
+ span.end();
16475
+ } catch (error) {
16476
+ debugLogger.error("Error tracing Harness continuation:", error);
16477
+ span.end();
16478
+ }
16479
+ },
16480
+ error: (event) => {
16481
+ const parent = parents.get(event);
16482
+ parents.delete(event);
16483
+ startTimes.delete(event);
16484
+ if (!parent) {
16485
+ return;
16486
+ }
16487
+ updateHarnessTurn(parent, {
16488
+ error: toLoggedError(event.error),
16489
+ output: null
16490
+ });
16491
+ endHarnessTurn(parent);
16492
+ }
16493
+ };
16494
+ channel2.subscribe(handlers);
16495
+ return () => {
16496
+ unbindParentStore();
16497
+ channel2.unsubscribe(handlers);
16498
+ };
16499
+ }
15863
16500
  function subscribeToAISDKV7TelemetryDispatcher() {
15864
16501
  const channel2 = aiSDKChannels.v7CreateTelemetryDispatcher.tracingChannel();
15865
16502
  const telemetry = braintrustAISDKTelemetry();
@@ -16312,7 +16949,13 @@ function prepareAISDKCallInput(params, event, span, defaultDenyOutputPaths, chil
16312
16949
  metadata
16313
16950
  };
16314
16951
  }
16315
- function prepareAISDKHarnessAgentInput(params, self) {
16952
+ function prepareAISDKHarnessAgentInput(params, self, span) {
16953
+ if (span) {
16954
+ registerHarnessTurnSpan({
16955
+ session: params.session,
16956
+ span
16957
+ });
16958
+ }
16316
16959
  if (isObject(self)) {
16317
16960
  try {
16318
16961
  if (isObject(self.settings)) {
@@ -16351,6 +16994,10 @@ function prepareAISDKHarnessAgentInput(params, self) {
16351
16994
  metadata
16352
16995
  };
16353
16996
  }
16997
+ function harnessSessionFromArguments(args) {
16998
+ const params = args[0];
16999
+ return isObject(params) ? params.session : void 0;
17000
+ }
16354
17001
  function prepareAISDKWorkflowAgentStreamInput(params, event, span, defaultDenyOutputPaths) {
16355
17002
  registerWorkflowAgentWrapperSpan(span);
16356
17003
  const { input } = processAISDKWorkflowAgentCallInput(params);
@@ -16798,19 +17445,22 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
16798
17445
  activeEntry.openSpans.delete(span);
16799
17446
  }
16800
17447
  },
16801
- {
16802
- name: "doGenerate",
16803
- spanAttributes: {
16804
- type: "llm" /* LLM */
17448
+ withSpanInstrumentationName(
17449
+ {
17450
+ name: "doGenerate",
17451
+ spanAttributes: {
17452
+ type: "llm" /* LLM */
17453
+ },
17454
+ event: buildAISDKModelStartEvent(
17455
+ callOptions,
17456
+ activeEntry.baseMetadata,
17457
+ {
17458
+ workflowAgent: activeEntry.childTracingOptions.workflowAgent
17459
+ }
17460
+ )
16805
17461
  },
16806
- event: buildAISDKModelStartEvent(
16807
- callOptions,
16808
- activeEntry.baseMetadata,
16809
- {
16810
- workflowAgent: activeEntry.childTracingOptions.workflowAgent
16811
- }
16812
- )
16813
- }
17462
+ INSTRUMENTATION_NAMES.AI_SDK
17463
+ )
16814
17464
  );
16815
17465
  };
16816
17466
  if (originalDoStream) {
@@ -16820,19 +17470,24 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
16820
17470
  return Reflect.apply(originalDoStream, resolvedModel, [callOptions]);
16821
17471
  }
16822
17472
  closeOpenAISDKModelPatchSpans(activeEntry);
16823
- const span = activeEntry.parentSpan.startSpan({
16824
- name: "doStream",
16825
- spanAttributes: {
16826
- type: "llm" /* LLM */
16827
- },
16828
- event: buildAISDKModelStartEvent(
16829
- callOptions,
16830
- activeEntry.baseMetadata,
17473
+ const span = activeEntry.parentSpan.startSpan(
17474
+ withSpanInstrumentationName(
16831
17475
  {
16832
- workflowAgent: activeEntry.childTracingOptions.workflowAgent
16833
- }
17476
+ name: "doStream",
17477
+ spanAttributes: {
17478
+ type: "llm" /* LLM */
17479
+ },
17480
+ event: buildAISDKModelStartEvent(
17481
+ callOptions,
17482
+ activeEntry.baseMetadata,
17483
+ {
17484
+ workflowAgent: activeEntry.childTracingOptions.workflowAgent
17485
+ }
17486
+ )
17487
+ },
17488
+ INSTRUMENTATION_NAMES.AI_SDK
16834
17489
  )
16835
- });
17490
+ );
16836
17491
  activeEntry.openSpans.add(span);
16837
17492
  const streamStartTime = getCurrentUnixTimestamp();
16838
17493
  const result = await withCurrent(
@@ -17004,12 +17659,17 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
17004
17659
  }
17005
17660
  if (isAsyncGenerator(result)) {
17006
17661
  return (async function* () {
17007
- const span = activeEntry.parentSpan.startSpan({
17008
- name: activeEntry.name,
17009
- spanAttributes: {
17010
- type: "tool" /* TOOL */
17011
- }
17012
- });
17662
+ const span = activeEntry.parentSpan.startSpan(
17663
+ withSpanInstrumentationName(
17664
+ {
17665
+ name: activeEntry.name,
17666
+ spanAttributes: {
17667
+ type: "tool" /* TOOL */
17668
+ }
17669
+ },
17670
+ INSTRUMENTATION_NAMES.AI_SDK
17671
+ )
17672
+ );
17013
17673
  span.log({ input: serializeToolExecutionInput(args) });
17014
17674
  try {
17015
17675
  let lastValue;
@@ -17033,12 +17693,15 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
17033
17693
  span.log({ output: awaitedResult });
17034
17694
  return awaitedResult;
17035
17695
  },
17036
- {
17037
- name: activeEntry.name,
17038
- spanAttributes: {
17039
- type: "tool" /* TOOL */
17040
- }
17041
- }
17696
+ withSpanInstrumentationName(
17697
+ {
17698
+ name: activeEntry.name,
17699
+ spanAttributes: {
17700
+ type: "tool" /* TOOL */
17701
+ }
17702
+ },
17703
+ INSTRUMENTATION_NAMES.AI_SDK
17704
+ )
17042
17705
  );
17043
17706
  };
17044
17707
  cleanup.push(() => {
@@ -17197,6 +17860,8 @@ function patchAISDKStreamingResult(args) {
17197
17860
  defaultDenyOutputPaths,
17198
17861
  endEvent,
17199
17862
  onComplete,
17863
+ onCancel,
17864
+ onError,
17200
17865
  result,
17201
17866
  resolvePromiseUsage,
17202
17867
  span,
@@ -17208,14 +17873,43 @@ function patchAISDKStreamingResult(args) {
17208
17873
  const resultRecord = result;
17209
17874
  attachKnownResultPromiseHandlers(resultRecord);
17210
17875
  let finalized = false;
17211
- const finalize = () => {
17876
+ const finalize = (outcome) => {
17212
17877
  if (finalized) {
17213
17878
  return;
17214
17879
  }
17215
17880
  finalized = true;
17216
- finalizeAISDKChildTracing(endEvent);
17217
- span.end();
17218
- onComplete?.();
17881
+ try {
17882
+ finalizeAISDKChildTracing(endEvent);
17883
+ } catch (error) {
17884
+ debugLogger.error("Error finalizing AI SDK child tracing:", error);
17885
+ }
17886
+ try {
17887
+ span.end();
17888
+ } catch (error) {
17889
+ debugLogger.error("Error ending AI SDK streaming span:", error);
17890
+ }
17891
+ if (outcome && "error" in outcome) {
17892
+ try {
17893
+ onError?.(outcome.error);
17894
+ } catch (error) {
17895
+ debugLogger.error("Error in AI SDK streaming error hook:", error);
17896
+ }
17897
+ } else if (outcome) {
17898
+ try {
17899
+ onComplete?.(outcome);
17900
+ } catch (error) {
17901
+ debugLogger.error("Error in AI SDK streaming completion hook:", error);
17902
+ }
17903
+ } else {
17904
+ try {
17905
+ onCancel?.();
17906
+ } catch (error) {
17907
+ debugLogger.error(
17908
+ "Error in AI SDK streaming cancellation hook:",
17909
+ error
17910
+ );
17911
+ }
17912
+ }
17219
17913
  };
17220
17914
  let outputLogged = false;
17221
17915
  const logStreamingOutput = async (firstChunkTime) => {
@@ -17249,15 +17943,29 @@ function patchAISDKStreamingResult(args) {
17249
17943
  resolveDenyOutputPaths(endEvent, defaultDenyOutputPaths)
17250
17944
  );
17251
17945
  const metadata = buildResolvedMetadataPayload(result).metadata;
17252
- span.log({
17253
- output,
17254
- ...metadata ? { metadata } : {},
17255
- metrics
17256
- });
17946
+ try {
17947
+ span.log({
17948
+ output,
17949
+ ...metadata ? { metadata } : {},
17950
+ metrics
17951
+ });
17952
+ } catch (error) {
17953
+ debugLogger.error("Error logging AI SDK streaming output:", error);
17954
+ }
17955
+ finalize({ metrics, output });
17257
17956
  } catch (error) {
17258
- span.log({ error: toLoggedError(error) });
17259
- } finally {
17260
- finalize();
17957
+ const loggedError = toLoggedError(error);
17958
+ try {
17959
+ span.log({ error: loggedError });
17960
+ } catch (loggingError) {
17961
+ debugLogger.error(
17962
+ "Error logging AI SDK streaming failure:",
17963
+ loggingError
17964
+ );
17965
+ }
17966
+ finalize({
17967
+ error: error instanceof Error ? error : new Error(String(loggedError))
17968
+ });
17261
17969
  }
17262
17970
  };
17263
17971
  const createAsyncIterableHooks = () => {
@@ -17274,11 +17982,16 @@ function patchAISDKStreamingResult(args) {
17274
17982
  onError: (error) => {
17275
17983
  if (!outputLogged) {
17276
17984
  outputLogged = true;
17277
- span.log({
17278
- error: error.message
17279
- });
17985
+ try {
17986
+ span.log({ error });
17987
+ } catch (loggingError) {
17988
+ debugLogger.error(
17989
+ "Error logging AI SDK stream failure:",
17990
+ loggingError
17991
+ );
17992
+ }
17280
17993
  }
17281
- finalize();
17994
+ finalize({ error });
17282
17995
  },
17283
17996
  onCancel: finalize
17284
17997
  };
@@ -17364,8 +18077,18 @@ function patchAISDKStreamingResult(args) {
17364
18077
  }
17365
18078
  controller.enqueue(value);
17366
18079
  } catch (error) {
17367
- span.log({ error: toLoggedError(error) });
17368
- finalize();
18080
+ const loggedError = toLoggedError(error);
18081
+ try {
18082
+ span.log({ error: loggedError });
18083
+ } catch (loggingError) {
18084
+ debugLogger.error(
18085
+ "Error logging AI SDK base stream failure:",
18086
+ loggingError
18087
+ );
18088
+ }
18089
+ finalize({
18090
+ error: error instanceof Error ? error : new Error(String(loggedError))
18091
+ });
17369
18092
  controller.error(error);
17370
18093
  }
17371
18094
  },
@@ -18154,7 +18877,8 @@ var claudeAgentSDKChannels = defineChannels(
18154
18877
  channelName: "query",
18155
18878
  kind: "sync-stream"
18156
18879
  })
18157
- }
18880
+ },
18881
+ { instrumentationName: INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK }
18158
18882
  );
18159
18883
 
18160
18884
  // src/instrumentation/plugins/claude-agent-sdk-instrumentation-constants.ts
@@ -18302,22 +19026,27 @@ function wrapLocalClaudeToolHandler(handler, getMetadata) {
18302
19026
  const spanName = metadata.serverName ? `tool: ${metadata.serverName}/${metadata.toolName}` : `tool: ${metadata.toolName}`;
18303
19027
  const runWithResolvedParent = async () => {
18304
19028
  const parent = toolUseId && localToolParentResolver ? await localToolParentResolver(toolUseId).catch(() => void 0) : void 0;
18305
- const span = startSpan({
18306
- event: {
18307
- input: handlerArgs[0],
18308
- metadata: {
18309
- "claude_agent_sdk.raw_tool_name": rawToolName,
18310
- "gen_ai.tool.name": metadata.toolName,
18311
- ...toolUseId && { "gen_ai.tool.call.id": toolUseId },
18312
- ...metadata.serverName && {
18313
- "mcp.server": metadata.serverName
18314
- }
18315
- }
18316
- },
18317
- name: spanName,
18318
- ...parent && { parent },
18319
- spanAttributes: { type: "tool" /* TOOL */ }
18320
- });
19029
+ const span = startSpan(
19030
+ withSpanInstrumentationName(
19031
+ {
19032
+ event: {
19033
+ input: handlerArgs[0],
19034
+ metadata: {
19035
+ "claude_agent_sdk.raw_tool_name": rawToolName,
19036
+ "gen_ai.tool.name": metadata.toolName,
19037
+ ...toolUseId && { "gen_ai.tool.call.id": toolUseId },
19038
+ ...metadata.serverName && {
19039
+ "mcp.server": metadata.serverName
19040
+ }
19041
+ }
19042
+ },
19043
+ name: spanName,
19044
+ ...parent && { parent },
19045
+ spanAttributes: { type: "tool" /* TOOL */ }
19046
+ },
19047
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
19048
+ )
19049
+ );
18321
19050
  const runHandler = () => Reflect.apply(handler, this, handlerArgs);
18322
19051
  const finalizeSuccess = (result) => {
18323
19052
  span.log({ output: result });
@@ -18642,14 +19371,19 @@ async function createLLMSpanForMessages(messages, promptMessages, conversationHi
18642
19371
  ).filter(
18643
19372
  (c) => c !== void 0
18644
19373
  );
18645
- const span = existingSpan ?? startSpan({
18646
- name: "anthropic.messages.create",
18647
- parent: parentSpan,
18648
- spanAttributes: {
18649
- type: "llm" /* LLM */
18650
- },
18651
- startTime
18652
- });
19374
+ const span = existingSpan ?? startSpan(
19375
+ withSpanInstrumentationName(
19376
+ {
19377
+ name: "anthropic.messages.create",
19378
+ parent: parentSpan,
19379
+ spanAttributes: {
19380
+ type: "llm" /* LLM */
19381
+ },
19382
+ startTime
19383
+ },
19384
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
19385
+ )
19386
+ );
18653
19387
  span.log({
18654
19388
  input,
18655
19389
  metadata: model ? { model } : void 0,
@@ -18752,25 +19486,30 @@ function createToolTracingHooks(resolveParentSpan, activeToolSpans, mcpServers,
18752
19486
  return {};
18753
19487
  }
18754
19488
  const parsed = parseToolName(input.tool_name);
18755
- const toolSpan = startSpan({
18756
- event: {
18757
- input: input.tool_input,
18758
- metadata: {
18759
- "claude_agent_sdk.cwd": input.cwd,
18760
- "claude_agent_sdk.raw_tool_name": parsed.rawToolName,
18761
- "claude_agent_sdk.session_id": input.session_id,
18762
- "gen_ai.tool.call.id": toolUseID,
18763
- "gen_ai.tool.name": parsed.toolName,
18764
- ...parsed.mcpServer && { "mcp.server": parsed.mcpServer },
18765
- ...getMcpServerMetadata(parsed.mcpServer, mcpServers)
18766
- }
18767
- },
18768
- name: parsed.displayName,
18769
- parent: await resolveParentSpan(toolUseID, {
18770
- agentId: input.agent_id
18771
- }),
18772
- spanAttributes: { type: "tool" /* TOOL */ }
18773
- });
19489
+ const toolSpan = startSpan(
19490
+ withSpanInstrumentationName(
19491
+ {
19492
+ event: {
19493
+ input: input.tool_input,
19494
+ metadata: {
19495
+ "claude_agent_sdk.cwd": input.cwd,
19496
+ "claude_agent_sdk.raw_tool_name": parsed.rawToolName,
19497
+ "claude_agent_sdk.session_id": input.session_id,
19498
+ "gen_ai.tool.call.id": toolUseID,
19499
+ "gen_ai.tool.name": parsed.toolName,
19500
+ ...parsed.mcpServer && { "mcp.server": parsed.mcpServer },
19501
+ ...getMcpServerMetadata(parsed.mcpServer, mcpServers)
19502
+ }
19503
+ },
19504
+ name: parsed.displayName,
19505
+ parent: await resolveParentSpan(toolUseID, {
19506
+ agentId: input.agent_id
19507
+ }),
19508
+ spanAttributes: { type: "tool" /* TOOL */ }
19509
+ },
19510
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
19511
+ )
19512
+ );
18774
19513
  activeToolSpans.set(toolUseID, toolSpan);
18775
19514
  return {};
18776
19515
  };
@@ -19136,14 +19875,19 @@ async function ensureSubAgentSpan(subAgentDetailsByToolUseId, rootSpan, activeTo
19136
19875
  const spanName = formatSubAgentSpanName(details);
19137
19876
  const parentToolSpan = activeToolSpans.get(parentToolUseId);
19138
19877
  const parentSpan = parentToolSpan ? await parentToolSpan.export() : await rootSpan.export();
19139
- const subAgentSpan = startSpan({
19140
- event: {
19141
- metadata: subAgentDetailsToMetadata(details)
19142
- },
19143
- name: spanName,
19144
- parent: parentSpan,
19145
- spanAttributes: { type: "task" /* TASK */ }
19146
- });
19878
+ const subAgentSpan = startSpan(
19879
+ withSpanInstrumentationName(
19880
+ {
19881
+ event: {
19882
+ metadata: subAgentDetailsToMetadata(details)
19883
+ },
19884
+ name: spanName,
19885
+ parent: parentSpan,
19886
+ spanAttributes: { type: "task" /* TASK */ }
19887
+ },
19888
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
19889
+ )
19890
+ );
19147
19891
  subAgentSpans.set(parentToolUseId, subAgentSpan);
19148
19892
  return subAgentSpan;
19149
19893
  }
@@ -19164,14 +19908,19 @@ async function ensureActiveLlmSpanForParentToolUse(rootSpan, activeLlmSpansByPar
19164
19908
  );
19165
19909
  llmParentSpan = await subAgentSpan.export();
19166
19910
  }
19167
- const llmSpan = startSpan({
19168
- name: "anthropic.messages.create",
19169
- parent: llmParentSpan,
19170
- spanAttributes: {
19171
- type: "llm" /* LLM */
19172
- },
19173
- startTime
19174
- });
19911
+ const llmSpan = startSpan(
19912
+ withSpanInstrumentationName(
19913
+ {
19914
+ name: "anthropic.messages.create",
19915
+ parent: llmParentSpan,
19916
+ spanAttributes: {
19917
+ type: "llm" /* LLM */
19918
+ },
19919
+ startTime
19920
+ },
19921
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
19922
+ )
19923
+ );
19175
19924
  activeLlmSpansByParentToolUse.set(parentKey, llmSpan);
19176
19925
  return llmSpan;
19177
19926
  }
@@ -19440,12 +20189,17 @@ var ClaudeAgentSDKPlugin = class extends BasePlugin {
19440
20189
  }
19441
20190
  })();
19442
20191
  }
19443
- const span = startSpan({
19444
- name: "Claude Agent",
19445
- spanAttributes: {
19446
- type: "task" /* TASK */
19447
- }
19448
- });
20192
+ const span = startSpan(
20193
+ withSpanInstrumentationName(
20194
+ {
20195
+ name: "Claude Agent",
20196
+ spanAttributes: {
20197
+ type: "task" /* TASK */
20198
+ }
20199
+ },
20200
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
20201
+ )
20202
+ );
19449
20203
  const startTime = getCurrentUnixTimestamp();
19450
20204
  try {
19451
20205
  span.log({
@@ -19610,24 +20364,28 @@ var ClaudeAgentSDKPlugin = class extends BasePlugin {
19610
20364
  };
19611
20365
 
19612
20366
  // src/instrumentation/plugins/cursor-sdk-channels.ts
19613
- var cursorSDKChannels = defineChannels("@cursor/sdk", {
19614
- create: channel({
19615
- channelName: "Agent.create",
19616
- kind: "async"
19617
- }),
19618
- resume: channel({
19619
- channelName: "Agent.resume",
19620
- kind: "async"
19621
- }),
19622
- prompt: channel({
19623
- channelName: "Agent.prompt",
19624
- kind: "async"
19625
- }),
19626
- send: channel({
19627
- channelName: "agent.send",
19628
- kind: "async"
19629
- })
19630
- });
20367
+ var cursorSDKChannels = defineChannels(
20368
+ "@cursor/sdk",
20369
+ {
20370
+ create: channel({
20371
+ channelName: "Agent.create",
20372
+ kind: "async"
20373
+ }),
20374
+ resume: channel({
20375
+ channelName: "Agent.resume",
20376
+ kind: "async"
20377
+ }),
20378
+ prompt: channel({
20379
+ channelName: "Agent.prompt",
20380
+ kind: "async"
20381
+ }),
20382
+ send: channel({
20383
+ channelName: "agent.send",
20384
+ kind: "async"
20385
+ })
20386
+ },
20387
+ { instrumentationName: INSTRUMENTATION_NAMES.CURSOR_SDK }
20388
+ );
19631
20389
 
19632
20390
  // src/instrumentation/plugins/cursor-sdk-plugin.ts
19633
20391
  var PATCHED_AGENT = /* @__PURE__ */ Symbol.for("braintrust.cursor-sdk.auto-patched-agent");
@@ -19679,10 +20437,15 @@ var CursorSDKPlugin = class extends BasePlugin {
19679
20437
  provider: "cursor",
19680
20438
  ...event.moduleVersion ? { "cursor_sdk.version": event.moduleVersion } : {}
19681
20439
  };
19682
- const span = startSpan({
19683
- name: "Cursor Agent",
19684
- spanAttributes: { type: "task" /* TASK */ }
19685
- });
20440
+ const span = startSpan(
20441
+ withSpanInstrumentationName(
20442
+ {
20443
+ name: "Cursor Agent",
20444
+ spanAttributes: { type: "task" /* TASK */ }
20445
+ },
20446
+ INSTRUMENTATION_NAMES.CURSOR_SDK
20447
+ )
20448
+ );
19686
20449
  const startTime = getCurrentUnixTimestamp();
19687
20450
  safeLog2(span, {
19688
20451
  input: sanitizeUserMessage(message),
@@ -19744,10 +20507,15 @@ var CursorSDKPlugin = class extends BasePlugin {
19744
20507
  provider: "cursor",
19745
20508
  ...event.moduleVersion ? { "cursor_sdk.version": event.moduleVersion } : {}
19746
20509
  };
19747
- const span = startSpan({
19748
- name: "Cursor Agent",
19749
- spanAttributes: { type: "task" /* TASK */ }
19750
- });
20510
+ const span = startSpan(
20511
+ withSpanInstrumentationName(
20512
+ {
20513
+ name: "Cursor Agent",
20514
+ spanAttributes: { type: "task" /* TASK */ }
20515
+ },
20516
+ INSTRUMENTATION_NAMES.CURSOR_SDK
20517
+ )
20518
+ );
19751
20519
  const startTime = getCurrentUnixTimestamp();
19752
20520
  safeLog2(span, {
19753
20521
  input: sanitizeUserMessage(message),
@@ -20194,29 +20962,39 @@ async function startToolSpan(state, args) {
20194
20962
  if (args.truncated?.result !== void 0) {
20195
20963
  metadata["cursor_sdk.tool.result_truncated"] = args.truncated.result;
20196
20964
  }
20197
- const span = startSpan({
20198
- event: {
20199
- input: args.args,
20200
- metadata
20201
- },
20202
- name: `tool: ${name}`,
20203
- parent: await state.span.export(),
20204
- spanAttributes: { type: "tool" /* TOOL */ }
20205
- });
20965
+ const span = startSpan(
20966
+ withSpanInstrumentationName(
20967
+ {
20968
+ event: {
20969
+ input: args.args,
20970
+ metadata
20971
+ },
20972
+ name: `tool: ${name}`,
20973
+ parent: await state.span.export(),
20974
+ spanAttributes: { type: "tool" /* TOOL */ }
20975
+ },
20976
+ INSTRUMENTATION_NAMES.CURSOR_SDK
20977
+ )
20978
+ );
20206
20979
  let subAgentSpan;
20207
20980
  if (isSubAgentToolName(name)) {
20208
- subAgentSpan = startSpan({
20209
- event: {
20210
- input: args.args,
20211
- metadata: {
20212
- "cursor_sdk.subagent.tool_call_id": args.callId,
20213
- "gen_ai.tool.name": name
20214
- }
20215
- },
20216
- name: formatSubAgentSpanName2(args.toolCall, args.args),
20217
- parent: await span.export(),
20218
- spanAttributes: { type: "task" /* TASK */ }
20219
- });
20981
+ subAgentSpan = startSpan(
20982
+ withSpanInstrumentationName(
20983
+ {
20984
+ event: {
20985
+ input: args.args,
20986
+ metadata: {
20987
+ "cursor_sdk.subagent.tool_call_id": args.callId,
20988
+ "gen_ai.tool.name": name
20989
+ }
20990
+ },
20991
+ name: formatSubAgentSpanName2(args.toolCall, args.args),
20992
+ parent: await span.export(),
20993
+ spanAttributes: { type: "task" /* TASK */ }
20994
+ },
20995
+ INSTRUMENTATION_NAMES.CURSOR_SDK
20996
+ )
20997
+ );
20220
20998
  }
20221
20999
  return { span, subAgentSpan };
20222
21000
  }
@@ -20475,24 +21253,28 @@ function cleanMetrics2(metrics) {
20475
21253
  }
20476
21254
 
20477
21255
  // src/instrumentation/plugins/openai-agents-channels.ts
20478
- var openAIAgentsCoreChannels = defineChannels("@openai/agents-core", {
20479
- onTraceStart: channel({
20480
- channelName: "tracing.processor.onTraceStart",
20481
- kind: "async"
20482
- }),
20483
- onTraceEnd: channel({
20484
- channelName: "tracing.processor.onTraceEnd",
20485
- kind: "async"
20486
- }),
20487
- onSpanStart: channel({
20488
- channelName: "tracing.processor.onSpanStart",
20489
- kind: "async"
20490
- }),
20491
- onSpanEnd: channel({
20492
- channelName: "tracing.processor.onSpanEnd",
20493
- kind: "async"
20494
- })
20495
- });
21256
+ var openAIAgentsCoreChannels = defineChannels(
21257
+ "@openai/agents-core",
21258
+ {
21259
+ onTraceStart: channel({
21260
+ channelName: "tracing.processor.onTraceStart",
21261
+ kind: "async"
21262
+ }),
21263
+ onTraceEnd: channel({
21264
+ channelName: "tracing.processor.onTraceEnd",
21265
+ kind: "async"
21266
+ }),
21267
+ onSpanStart: channel({
21268
+ channelName: "tracing.processor.onSpanStart",
21269
+ kind: "async"
21270
+ }),
21271
+ onSpanEnd: channel({
21272
+ channelName: "tracing.processor.onSpanEnd",
21273
+ kind: "async"
21274
+ })
21275
+ },
21276
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENAI_AGENTS }
21277
+ );
20496
21278
 
20497
21279
  // src/instrumentation/plugins/openai-agents-trace-processor.ts
20498
21280
  function isSpanData(spanData, type) {
@@ -20608,16 +21390,19 @@ var OpenAIAgentsTraceProcessor = class _OpenAIAgentsTraceProcessor {
20608
21390
  this.evictOldestTrace();
20609
21391
  }
20610
21392
  const current = currentSpan();
20611
- const span = current && current !== NOOP_SPAN ? current.startSpan({
20612
- name: trace.name,
20613
- type: "task" /* TASK */
20614
- }) : this.logger ? this.logger.startSpan({
20615
- name: trace.name,
20616
- type: "task" /* TASK */
20617
- }) : startSpan({
20618
- name: trace.name,
20619
- type: "task" /* TASK */
20620
- });
21393
+ const spanArgs = withSpanInstrumentationName(
21394
+ {
21395
+ name: trace.name,
21396
+ type: "task" /* TASK */
21397
+ },
21398
+ INSTRUMENTATION_NAMES.OPENAI_AGENTS
21399
+ );
21400
+ const span = current && current !== NOOP_SPAN ? current.startSpan(spanArgs) : this.logger ? this.logger.startSpan(spanArgs) : startSpan(
21401
+ withSpanInstrumentationName(
21402
+ spanArgs,
21403
+ INSTRUMENTATION_NAMES.OPENAI_AGENTS
21404
+ )
21405
+ );
20621
21406
  span.log({
20622
21407
  input: "Agent workflow started",
20623
21408
  metadata: {
@@ -20668,10 +21453,15 @@ var OpenAIAgentsTraceProcessor = class _OpenAIAgentsTraceProcessor {
20668
21453
  if (!parentSpan) {
20669
21454
  return Promise.resolve();
20670
21455
  }
20671
- const childSpan = parentSpan.startSpan({
20672
- name: spanNameFromAgents(span),
20673
- type: spanTypeFromAgents(span)
20674
- });
21456
+ const childSpan = parentSpan.startSpan(
21457
+ withSpanInstrumentationName(
21458
+ {
21459
+ name: spanNameFromAgents(span),
21460
+ type: spanTypeFromAgents(span)
21461
+ },
21462
+ INSTRUMENTATION_NAMES.OPENAI_AGENTS
21463
+ )
21464
+ );
20675
21465
  traceData.childSpans.set(span.spanId, childSpan);
20676
21466
  return Promise.resolve();
20677
21467
  }
@@ -20936,24 +21726,28 @@ var OpenAIAgentsPlugin = class extends BasePlugin {
20936
21726
  };
20937
21727
 
20938
21728
  // src/instrumentation/plugins/google-genai-channels.ts
20939
- var googleGenAIChannels = defineChannels("@google/genai", {
20940
- generateContent: channel({
20941
- channelName: "models.generateContent",
20942
- kind: "async"
20943
- }),
20944
- generateContentStream: channel({
20945
- channelName: "models.generateContentStream",
20946
- kind: "async"
20947
- }),
20948
- embedContent: channel({
20949
- channelName: "models.embedContent",
20950
- kind: "async"
20951
- }),
20952
- interactionsCreate: channel({
20953
- channelName: "interactions.create",
20954
- kind: "async"
20955
- })
20956
- });
21729
+ var googleGenAIChannels = defineChannels(
21730
+ "@google/genai",
21731
+ {
21732
+ generateContent: channel({
21733
+ channelName: "models.generateContent",
21734
+ kind: "async"
21735
+ }),
21736
+ generateContentStream: channel({
21737
+ channelName: "models.generateContentStream",
21738
+ kind: "async"
21739
+ }),
21740
+ embedContent: channel({
21741
+ channelName: "models.embedContent",
21742
+ kind: "async"
21743
+ }),
21744
+ interactionsCreate: channel({
21745
+ channelName: "interactions.create",
21746
+ kind: "async"
21747
+ })
21748
+ },
21749
+ { instrumentationName: INSTRUMENTATION_NAMES.GOOGLE_GENAI }
21750
+ );
20957
21751
 
20958
21752
  // src/instrumentation/plugins/google-genai-plugin.ts
20959
21753
  var GOOGLE_GENAI_INTERNAL_CONTEXT = {
@@ -20991,13 +21785,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
20991
21785
  const params = event.arguments[0];
20992
21786
  const input = serializeGenerateContentInput(params);
20993
21787
  const metadata = extractGenerateContentMetadata(params);
20994
- const span = startSpan({
20995
- name: "generate_content",
20996
- spanAttributes: {
20997
- type: "llm" /* LLM */
20998
- },
20999
- event: createWrapperParityEvent({ input, metadata })
21000
- });
21788
+ const span = startSpan(
21789
+ withSpanInstrumentationName(
21790
+ {
21791
+ name: "generate_content",
21792
+ spanAttributes: {
21793
+ type: "llm" /* LLM */
21794
+ },
21795
+ event: createWrapperParityEvent({ input, metadata })
21796
+ },
21797
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
21798
+ )
21799
+ );
21001
21800
  return {
21002
21801
  span,
21003
21802
  startTime: getCurrentUnixTimestamp()
@@ -21010,13 +21809,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
21010
21809
  const params = event.arguments[0];
21011
21810
  const input = serializeGenerateContentInput(params);
21012
21811
  const metadata = extractGenerateContentMetadata(params);
21013
- const span = startSpan({
21014
- name: "generate_content",
21015
- spanAttributes: {
21016
- type: "llm" /* LLM */
21017
- },
21018
- event: createWrapperParityEvent({ input, metadata })
21019
- });
21812
+ const span = startSpan(
21813
+ withSpanInstrumentationName(
21814
+ {
21815
+ name: "generate_content",
21816
+ spanAttributes: {
21817
+ type: "llm" /* LLM */
21818
+ },
21819
+ event: createWrapperParityEvent({ input, metadata })
21820
+ },
21821
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
21822
+ )
21823
+ );
21020
21824
  return {
21021
21825
  span,
21022
21826
  startTime: getCurrentUnixTimestamp()
@@ -21092,13 +21896,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
21092
21896
  const params = event.arguments[0];
21093
21897
  const input = serializeEmbedContentInput(params);
21094
21898
  const metadata = extractEmbedContentMetadata(params);
21095
- const span = startSpan({
21096
- name: "embed_content",
21097
- spanAttributes: {
21098
- type: "llm" /* LLM */
21099
- },
21100
- event: createWrapperParityEvent({ input, metadata })
21101
- });
21899
+ const span = startSpan(
21900
+ withSpanInstrumentationName(
21901
+ {
21902
+ name: "embed_content",
21903
+ spanAttributes: {
21904
+ type: "llm" /* LLM */
21905
+ },
21906
+ event: createWrapperParityEvent({ input, metadata })
21907
+ },
21908
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
21909
+ )
21910
+ );
21102
21911
  return {
21103
21912
  span,
21104
21913
  startTime: getCurrentUnixTimestamp()
@@ -21111,13 +21920,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
21111
21920
  const params = event.arguments[0];
21112
21921
  const input = serializeEmbedContentInput(params);
21113
21922
  const metadata = extractEmbedContentMetadata(params);
21114
- const span = startSpan({
21115
- name: "embed_content",
21116
- spanAttributes: {
21117
- type: "llm" /* LLM */
21118
- },
21119
- event: createWrapperParityEvent({ input, metadata })
21120
- });
21923
+ const span = startSpan(
21924
+ withSpanInstrumentationName(
21925
+ {
21926
+ name: "embed_content",
21927
+ spanAttributes: {
21928
+ type: "llm" /* LLM */
21929
+ },
21930
+ event: createWrapperParityEvent({ input, metadata })
21931
+ },
21932
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
21933
+ )
21934
+ );
21121
21935
  return {
21122
21936
  span,
21123
21937
  startTime: getCurrentUnixTimestamp()
@@ -21228,16 +22042,21 @@ function patchGoogleGenAIStreamingResult(args) {
21228
22042
  const requestStartTime = startTime ?? getCurrentUnixTimestamp();
21229
22043
  const ensureSpan = () => {
21230
22044
  if (!span) {
21231
- span = startSpan({
21232
- name: "generate_content_stream",
21233
- spanAttributes: {
21234
- type: "llm" /* LLM */
21235
- },
21236
- event: {
21237
- input,
21238
- metadata
21239
- }
21240
- });
22045
+ span = startSpan(
22046
+ withSpanInstrumentationName(
22047
+ {
22048
+ name: "generate_content_stream",
22049
+ spanAttributes: {
22050
+ type: "llm" /* LLM */
22051
+ },
22052
+ event: {
22053
+ input,
22054
+ metadata
22055
+ }
22056
+ },
22057
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
22058
+ )
22059
+ );
21241
22060
  }
21242
22061
  return span;
21243
22062
  };
@@ -22005,28 +22824,32 @@ function tryToDict(obj) {
22005
22824
  }
22006
22825
 
22007
22826
  // src/instrumentation/plugins/huggingface-channels.ts
22008
- var huggingFaceChannels = defineChannels("@huggingface/inference", {
22009
- chatCompletion: channel({
22010
- channelName: "chatCompletion",
22011
- kind: "async"
22012
- }),
22013
- chatCompletionStream: channel({
22014
- channelName: "chatCompletionStream",
22015
- kind: "sync-stream"
22016
- }),
22017
- textGeneration: channel({
22018
- channelName: "textGeneration",
22019
- kind: "async"
22020
- }),
22021
- textGenerationStream: channel({
22022
- channelName: "textGenerationStream",
22023
- kind: "sync-stream"
22024
- }),
22025
- featureExtraction: channel({
22026
- channelName: "featureExtraction",
22027
- kind: "async"
22028
- })
22029
- });
22827
+ var huggingFaceChannels = defineChannels(
22828
+ "@huggingface/inference",
22829
+ {
22830
+ chatCompletion: channel({
22831
+ channelName: "chatCompletion",
22832
+ kind: "async"
22833
+ }),
22834
+ chatCompletionStream: channel({
22835
+ channelName: "chatCompletionStream",
22836
+ kind: "sync-stream"
22837
+ }),
22838
+ textGeneration: channel({
22839
+ channelName: "textGeneration",
22840
+ kind: "async"
22841
+ }),
22842
+ textGenerationStream: channel({
22843
+ channelName: "textGenerationStream",
22844
+ kind: "sync-stream"
22845
+ }),
22846
+ featureExtraction: channel({
22847
+ channelName: "featureExtraction",
22848
+ kind: "async"
22849
+ })
22850
+ },
22851
+ { instrumentationName: INSTRUMENTATION_NAMES.HUGGINGFACE }
22852
+ );
22030
22853
 
22031
22854
  // src/instrumentation/plugins/huggingface-plugin.ts
22032
22855
  var REQUEST_METADATA_ALLOWLIST = /* @__PURE__ */ new Set([
@@ -22453,20 +23276,24 @@ function extractTextGenerationStreamMetadata(chunks) {
22453
23276
  }
22454
23277
 
22455
23278
  // src/instrumentation/plugins/openrouter-agent-channels.ts
22456
- var openRouterAgentChannels = defineChannels("@openrouter/agent", {
22457
- callModel: channel({
22458
- channelName: "callModel",
22459
- kind: "sync-stream"
22460
- }),
22461
- callModelTurn: channel({
22462
- channelName: "callModel.turn",
22463
- kind: "async"
22464
- }),
22465
- toolExecute: channel({
22466
- channelName: "tool.execute",
22467
- kind: "async"
22468
- })
22469
- });
23279
+ var openRouterAgentChannels = defineChannels(
23280
+ "@openrouter/agent",
23281
+ {
23282
+ callModel: channel({
23283
+ channelName: "callModel",
23284
+ kind: "sync-stream"
23285
+ }),
23286
+ callModelTurn: channel({
23287
+ channelName: "callModel.turn",
23288
+ kind: "async"
23289
+ }),
23290
+ toolExecute: channel({
23291
+ channelName: "tool.execute",
23292
+ kind: "async"
23293
+ })
23294
+ },
23295
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENROUTER_AGENT }
23296
+ );
22470
23297
 
22471
23298
  // src/instrumentation/plugins/openrouter-agent-plugin.ts
22472
23299
  var OpenRouterAgentPlugin = class extends BasePlugin {
@@ -23236,38 +24063,40 @@ function normalizeError(error) {
23236
24063
  }
23237
24064
 
23238
24065
  // src/instrumentation/plugins/openrouter-channels.ts
23239
- var openRouterChannels = defineChannels("@openrouter/sdk", {
23240
- chatSend: channel({
23241
- channelName: "chat.send",
23242
- kind: "async"
23243
- }),
23244
- embeddingsGenerate: channel({
23245
- channelName: "embeddings.generate",
23246
- kind: "async"
23247
- }),
23248
- rerankRerank: channel(
23249
- {
24066
+ var openRouterChannels = defineChannels(
24067
+ "@openrouter/sdk",
24068
+ {
24069
+ chatSend: channel({
24070
+ channelName: "chat.send",
24071
+ kind: "async"
24072
+ }),
24073
+ embeddingsGenerate: channel({
24074
+ channelName: "embeddings.generate",
24075
+ kind: "async"
24076
+ }),
24077
+ rerankRerank: channel({
23250
24078
  channelName: "rerank.rerank",
23251
24079
  kind: "async"
23252
- }
23253
- ),
23254
- betaResponsesSend: channel({
23255
- channelName: "beta.responses.send",
23256
- kind: "async"
23257
- }),
23258
- callModel: channel({
23259
- channelName: "callModel",
23260
- kind: "sync-stream"
23261
- }),
23262
- callModelTurn: channel({
23263
- channelName: "callModel.turn",
23264
- kind: "async"
23265
- }),
23266
- toolExecute: channel({
23267
- channelName: "tool.execute",
23268
- kind: "async"
23269
- })
23270
- });
24080
+ }),
24081
+ betaResponsesSend: channel({
24082
+ channelName: "beta.responses.send",
24083
+ kind: "async"
24084
+ }),
24085
+ callModel: channel({
24086
+ channelName: "callModel",
24087
+ kind: "sync-stream"
24088
+ }),
24089
+ callModelTurn: channel({
24090
+ channelName: "callModel.turn",
24091
+ kind: "async"
24092
+ }),
24093
+ toolExecute: channel({
24094
+ channelName: "tool.execute",
24095
+ kind: "async"
24096
+ })
24097
+ },
24098
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENROUTER }
24099
+ );
23271
24100
 
23272
24101
  // src/instrumentation/plugins/openrouter-plugin.ts
23273
24102
  var OpenRouterPlugin = class extends BasePlugin {
@@ -24307,52 +25136,56 @@ function normalizeError2(error) {
24307
25136
  }
24308
25137
 
24309
25138
  // src/instrumentation/plugins/mistral-channels.ts
24310
- var mistralChannels = defineChannels("@mistralai/mistralai", {
24311
- chatComplete: channel({
24312
- channelName: "chat.complete",
24313
- kind: "async"
24314
- }),
24315
- chatStream: channel({
24316
- channelName: "chat.stream",
24317
- kind: "async"
24318
- }),
24319
- embeddingsCreate: channel({
24320
- channelName: "embeddings.create",
24321
- kind: "async"
24322
- }),
24323
- classifiersModerate: channel({
24324
- channelName: "classifiers.moderate",
24325
- kind: "async"
24326
- }),
24327
- classifiersModerateChat: channel({
24328
- channelName: "classifiers.moderateChat",
24329
- kind: "async"
24330
- }),
24331
- classifiersClassify: channel({
24332
- channelName: "classifiers.classify",
24333
- kind: "async"
24334
- }),
24335
- classifiersClassifyChat: channel({
24336
- channelName: "classifiers.classifyChat",
24337
- kind: "async"
24338
- }),
24339
- fimComplete: channel({
24340
- channelName: "fim.complete",
24341
- kind: "async"
24342
- }),
24343
- fimStream: channel({
24344
- channelName: "fim.stream",
24345
- kind: "async"
24346
- }),
24347
- agentsComplete: channel({
24348
- channelName: "agents.complete",
24349
- kind: "async"
24350
- }),
24351
- agentsStream: channel({
24352
- channelName: "agents.stream",
24353
- kind: "async"
24354
- })
24355
- });
25139
+ var mistralChannels = defineChannels(
25140
+ "@mistralai/mistralai",
25141
+ {
25142
+ chatComplete: channel({
25143
+ channelName: "chat.complete",
25144
+ kind: "async"
25145
+ }),
25146
+ chatStream: channel({
25147
+ channelName: "chat.stream",
25148
+ kind: "async"
25149
+ }),
25150
+ embeddingsCreate: channel({
25151
+ channelName: "embeddings.create",
25152
+ kind: "async"
25153
+ }),
25154
+ classifiersModerate: channel({
25155
+ channelName: "classifiers.moderate",
25156
+ kind: "async"
25157
+ }),
25158
+ classifiersModerateChat: channel({
25159
+ channelName: "classifiers.moderateChat",
25160
+ kind: "async"
25161
+ }),
25162
+ classifiersClassify: channel({
25163
+ channelName: "classifiers.classify",
25164
+ kind: "async"
25165
+ }),
25166
+ classifiersClassifyChat: channel({
25167
+ channelName: "classifiers.classifyChat",
25168
+ kind: "async"
25169
+ }),
25170
+ fimComplete: channel({
25171
+ channelName: "fim.complete",
25172
+ kind: "async"
25173
+ }),
25174
+ fimStream: channel({
25175
+ channelName: "fim.stream",
25176
+ kind: "async"
25177
+ }),
25178
+ agentsComplete: channel({
25179
+ channelName: "agents.complete",
25180
+ kind: "async"
25181
+ }),
25182
+ agentsStream: channel({
25183
+ channelName: "agents.stream",
25184
+ kind: "async"
25185
+ })
25186
+ },
25187
+ { instrumentationName: INSTRUMENTATION_NAMES.MISTRAL }
25188
+ );
24356
25189
 
24357
25190
  // src/instrumentation/plugins/mistral-plugin.ts
24358
25191
  var MistralPlugin = class extends BasePlugin {
@@ -24972,20 +25805,24 @@ function aggregateMistralStreamChunks(chunks) {
24972
25805
  }
24973
25806
 
24974
25807
  // src/instrumentation/plugins/google-adk-channels.ts
24975
- var googleADKChannels = defineChannels("@google/adk", {
24976
- runnerRunAsync: channel({
24977
- channelName: "runner.runAsync",
24978
- kind: "sync-stream"
24979
- }),
24980
- agentRunAsync: channel({
24981
- channelName: "agent.runAsync",
24982
- kind: "sync-stream"
24983
- }),
24984
- toolRunAsync: channel({
24985
- channelName: "tool.runAsync",
24986
- kind: "async"
24987
- })
24988
- });
25808
+ var googleADKChannels = defineChannels(
25809
+ "@google/adk",
25810
+ {
25811
+ runnerRunAsync: channel({
25812
+ channelName: "runner.runAsync",
25813
+ kind: "sync-stream"
25814
+ }),
25815
+ agentRunAsync: channel({
25816
+ channelName: "agent.runAsync",
25817
+ kind: "sync-stream"
25818
+ }),
25819
+ toolRunAsync: channel({
25820
+ channelName: "tool.runAsync",
25821
+ kind: "async"
25822
+ })
25823
+ },
25824
+ { instrumentationName: INSTRUMENTATION_NAMES.GOOGLE_ADK }
25825
+ );
24989
25826
 
24990
25827
  // src/instrumentation/plugins/google-adk-plugin.ts
24991
25828
  var GoogleADKPlugin = class extends BasePlugin {
@@ -25010,12 +25847,17 @@ var GoogleADKPlugin = class extends BasePlugin {
25010
25847
  const createState = (event) => {
25011
25848
  const params = event.arguments[0] ?? {};
25012
25849
  const contextKey = extractRunnerContextKey(params);
25013
- const span = startSpan({
25014
- name: "Google ADK Runner",
25015
- spanAttributes: {
25016
- type: "task" /* TASK */
25017
- }
25018
- });
25850
+ const span = startSpan(
25851
+ withSpanInstrumentationName(
25852
+ {
25853
+ name: "Google ADK Runner",
25854
+ spanAttributes: {
25855
+ type: "task" /* TASK */
25856
+ }
25857
+ },
25858
+ INSTRUMENTATION_NAMES.GOOGLE_ADK
25859
+ )
25860
+ );
25019
25861
  const startTime = getCurrentUnixTimestamp();
25020
25862
  try {
25021
25863
  const metadata = extractRunnerMetadata(params);
@@ -25101,18 +25943,23 @@ var GoogleADKPlugin = class extends BasePlugin {
25101
25943
  this.activeRunnerSpans
25102
25944
  );
25103
25945
  const contextKey = extractInvocationContextKey(parentContext);
25104
- const span = startSpan({
25105
- name: agentName ? `Agent: ${agentName}` : "Google ADK Agent",
25106
- spanAttributes: {
25107
- type: "task" /* TASK */
25108
- },
25109
- ...runnerParentSpan ? {
25110
- parentSpanIds: {
25111
- spanId: runnerParentSpan.spanId,
25112
- rootSpanId: runnerParentSpan.rootSpanId
25113
- }
25114
- } : {}
25115
- });
25946
+ const span = startSpan(
25947
+ withSpanInstrumentationName(
25948
+ {
25949
+ name: agentName ? `Agent: ${agentName}` : "Google ADK Agent",
25950
+ spanAttributes: {
25951
+ type: "task" /* TASK */
25952
+ },
25953
+ ...runnerParentSpan ? {
25954
+ parentSpanIds: {
25955
+ spanId: runnerParentSpan.spanId,
25956
+ rootSpanId: runnerParentSpan.rootSpanId
25957
+ }
25958
+ } : {}
25959
+ },
25960
+ INSTRUMENTATION_NAMES.GOOGLE_ADK
25961
+ )
25962
+ );
25116
25963
  const startTime = getCurrentUnixTimestamp();
25117
25964
  try {
25118
25965
  const metadata = {
@@ -25205,22 +26052,27 @@ var GoogleADKPlugin = class extends BasePlugin {
25205
26052
  this.activeAgentSpans,
25206
26053
  this.activeRunnerSpans
25207
26054
  );
25208
- const createSpan = () => startSpan({
25209
- name: toolName ? `tool: ${toolName}` : "Google ADK Tool",
25210
- spanAttributes: {
25211
- type: "tool" /* TOOL */
25212
- },
25213
- event: {
25214
- input: req.args,
25215
- metadata: {
25216
- provider: "google-adk",
25217
- ...toolName && { "google_adk.tool_name": toolName },
25218
- ...extractToolCallId(req) && {
25219
- "google_adk.tool_call_id": extractToolCallId(req)
26055
+ const createSpan = () => startSpan(
26056
+ withSpanInstrumentationName(
26057
+ {
26058
+ name: toolName ? `tool: ${toolName}` : "Google ADK Tool",
26059
+ spanAttributes: {
26060
+ type: "tool" /* TOOL */
26061
+ },
26062
+ event: {
26063
+ input: req.args,
26064
+ metadata: {
26065
+ provider: "google-adk",
26066
+ ...toolName && { "google_adk.tool_name": toolName },
26067
+ ...extractToolCallId(req) && {
26068
+ "google_adk.tool_call_id": extractToolCallId(req)
26069
+ }
26070
+ }
25220
26071
  }
25221
- }
25222
- }
25223
- });
26072
+ },
26073
+ INSTRUMENTATION_NAMES.GOOGLE_ADK
26074
+ )
26075
+ );
25224
26076
  const span = parentSpan ? withCurrent(parentSpan, () => createSpan()) : createSpan();
25225
26077
  const startTime = getCurrentUnixTimestamp();
25226
26078
  states.set(event, { span, startTime });
@@ -25619,24 +26471,28 @@ function cleanMetrics4(metrics) {
25619
26471
  }
25620
26472
 
25621
26473
  // src/instrumentation/plugins/cohere-channels.ts
25622
- var cohereChannels = defineChannels("cohere-ai", {
25623
- chat: channel({
25624
- channelName: "chat",
25625
- kind: "async"
25626
- }),
25627
- chatStream: channel({
25628
- channelName: "chatStream",
25629
- kind: "async"
25630
- }),
25631
- embed: channel({
25632
- channelName: "embed",
25633
- kind: "async"
25634
- }),
25635
- rerank: channel({
25636
- channelName: "rerank",
25637
- kind: "async"
25638
- })
25639
- });
26474
+ var cohereChannels = defineChannels(
26475
+ "cohere-ai",
26476
+ {
26477
+ chat: channel({
26478
+ channelName: "chat",
26479
+ kind: "async"
26480
+ }),
26481
+ chatStream: channel({
26482
+ channelName: "chatStream",
26483
+ kind: "async"
26484
+ }),
26485
+ embed: channel({
26486
+ channelName: "embed",
26487
+ kind: "async"
26488
+ }),
26489
+ rerank: channel({
26490
+ channelName: "rerank",
26491
+ kind: "async"
26492
+ })
26493
+ },
26494
+ { instrumentationName: INSTRUMENTATION_NAMES.COHERE }
26495
+ );
25640
26496
 
25641
26497
  // src/instrumentation/plugins/cohere-plugin.ts
25642
26498
  var CoherePlugin = class extends BasePlugin {
@@ -26305,18 +27161,20 @@ function aggregateCohereChatStreamChunks(chunks) {
26305
27161
  }
26306
27162
 
26307
27163
  // src/instrumentation/plugins/groq-channels.ts
26308
- var groqChannels = defineChannels("groq-sdk", {
26309
- chatCompletionsCreate: channel({
26310
- channelName: "chat.completions.create",
26311
- kind: "async"
26312
- }),
26313
- embeddingsCreate: channel(
26314
- {
27164
+ var groqChannels = defineChannels(
27165
+ "groq-sdk",
27166
+ {
27167
+ chatCompletionsCreate: channel({
27168
+ channelName: "chat.completions.create",
27169
+ kind: "async"
27170
+ }),
27171
+ embeddingsCreate: channel({
26315
27172
  channelName: "embeddings.create",
26316
27173
  kind: "async"
26317
- }
26318
- )
26319
- });
27174
+ })
27175
+ },
27176
+ { instrumentationName: INSTRUMENTATION_NAMES.GROQ }
27177
+ );
26320
27178
 
26321
27179
  // src/instrumentation/plugins/groq-plugin.ts
26322
27180
  var GroqPlugin = class extends BasePlugin {
@@ -26419,15 +27277,27 @@ var clientSendChannel = channel({
26419
27277
  channelName: "client.send",
26420
27278
  kind: "async"
26421
27279
  });
26422
- var bedrockRuntimeChannels = defineChannels("aws-bedrock-runtime", {
26423
- clientSend: clientSendChannel
26424
- });
26425
- var smithyCoreChannels = defineChannels("@smithy/core", {
26426
- clientSend: clientSendChannel
26427
- });
26428
- var smithyClientChannels = defineChannels("@smithy/smithy-client", {
26429
- clientSend: clientSendChannel
26430
- });
27280
+ var bedrockRuntimeChannels = defineChannels(
27281
+ "aws-bedrock-runtime",
27282
+ {
27283
+ clientSend: clientSendChannel
27284
+ },
27285
+ { instrumentationName: INSTRUMENTATION_NAMES.BEDROCK_RUNTIME }
27286
+ );
27287
+ var smithyCoreChannels = defineChannels(
27288
+ "@smithy/core",
27289
+ {
27290
+ clientSend: clientSendChannel
27291
+ },
27292
+ { instrumentationName: INSTRUMENTATION_NAMES.BEDROCK_RUNTIME }
27293
+ );
27294
+ var smithyClientChannels = defineChannels(
27295
+ "@smithy/smithy-client",
27296
+ {
27297
+ clientSend: clientSendChannel
27298
+ },
27299
+ { instrumentationName: INSTRUMENTATION_NAMES.BEDROCK_RUNTIME }
27300
+ );
26431
27301
 
26432
27302
  // src/instrumentation/plugins/bedrock-runtime-common.ts
26433
27303
  var BEDROCK_RUNTIME_COMMAND_OPERATIONS = {
@@ -27061,38 +27931,46 @@ function extractTextFromJsonLike(value) {
27061
27931
  }
27062
27932
 
27063
27933
  // src/instrumentation/plugins/genkit-channels.ts
27064
- var genkitChannels = defineChannels("@genkit-ai/ai", {
27065
- generate: channel({
27066
- channelName: "generate",
27067
- kind: "async"
27068
- }),
27069
- generateStream: channel({
27070
- channelName: "generateStream",
27071
- kind: "sync-stream"
27072
- }),
27073
- embed: channel({
27074
- channelName: "embed",
27075
- kind: "async"
27076
- }),
27077
- embedMany: channel({
27078
- channelName: "embedMany",
27079
- kind: "async"
27080
- }),
27081
- actionRun: channel({
27082
- channelName: "action.run",
27083
- kind: "async"
27084
- }),
27085
- actionStream: channel({
27086
- channelName: "action.stream",
27087
- kind: "sync-stream"
27088
- })
27089
- });
27090
- var genkitCoreChannels = defineChannels("@genkit-ai/core", {
27091
- actionSpan: channel({
27092
- channelName: "action.span",
27093
- kind: "async"
27094
- })
27095
- });
27934
+ var genkitChannels = defineChannels(
27935
+ "@genkit-ai/ai",
27936
+ {
27937
+ generate: channel({
27938
+ channelName: "generate",
27939
+ kind: "async"
27940
+ }),
27941
+ generateStream: channel({
27942
+ channelName: "generateStream",
27943
+ kind: "sync-stream"
27944
+ }),
27945
+ embed: channel({
27946
+ channelName: "embed",
27947
+ kind: "async"
27948
+ }),
27949
+ embedMany: channel({
27950
+ channelName: "embedMany",
27951
+ kind: "async"
27952
+ }),
27953
+ actionRun: channel({
27954
+ channelName: "action.run",
27955
+ kind: "async"
27956
+ }),
27957
+ actionStream: channel({
27958
+ channelName: "action.stream",
27959
+ kind: "sync-stream"
27960
+ })
27961
+ },
27962
+ { instrumentationName: INSTRUMENTATION_NAMES.GENKIT }
27963
+ );
27964
+ var genkitCoreChannels = defineChannels(
27965
+ "@genkit-ai/core",
27966
+ {
27967
+ actionSpan: channel({
27968
+ channelName: "action.span",
27969
+ kind: "async"
27970
+ })
27971
+ },
27972
+ { instrumentationName: INSTRUMENTATION_NAMES.GENKIT }
27973
+ );
27096
27974
 
27097
27975
  // src/instrumentation/plugins/genkit-plugin.ts
27098
27976
  var GenkitPlugin = class extends BasePlugin {
@@ -27277,12 +28155,17 @@ function startActionSpanState(args) {
27277
28155
  if (!shouldTraceAction(args.metadata, args.runStepName)) {
27278
28156
  return void 0;
27279
28157
  }
27280
- const span = startSpan({
27281
- name: actionSpanName(args.metadata, args.runStepName),
27282
- spanAttributes: {
27283
- type: actionSpanType(args.metadata)
27284
- }
27285
- });
28158
+ const span = startSpan(
28159
+ withSpanInstrumentationName(
28160
+ {
28161
+ name: actionSpanName(args.metadata, args.runStepName),
28162
+ spanAttributes: {
28163
+ type: actionSpanType(args.metadata)
28164
+ }
28165
+ },
28166
+ INSTRUMENTATION_NAMES.GENKIT
28167
+ )
28168
+ );
27286
28169
  const startTime = getCurrentUnixTimestamp();
27287
28170
  span.log({
27288
28171
  input: args.input,
@@ -27643,20 +28526,24 @@ function stringValue(value) {
27643
28526
  }
27644
28527
 
27645
28528
  // src/instrumentation/plugins/github-copilot-channels.ts
27646
- var gitHubCopilotChannels = defineChannels("@github/copilot-sdk", {
27647
- createSession: channel({
27648
- channelName: "client.createSession",
27649
- kind: "async"
27650
- }),
27651
- resumeSession: channel({
27652
- channelName: "client.resumeSession",
27653
- kind: "async"
27654
- }),
27655
- sendAndWait: channel({
27656
- channelName: "session.sendAndWait",
27657
- kind: "async"
27658
- })
27659
- });
28529
+ var gitHubCopilotChannels = defineChannels(
28530
+ "@github/copilot-sdk",
28531
+ {
28532
+ createSession: channel({
28533
+ channelName: "client.createSession",
28534
+ kind: "async"
28535
+ }),
28536
+ resumeSession: channel({
28537
+ channelName: "client.resumeSession",
28538
+ kind: "async"
28539
+ }),
28540
+ sendAndWait: channel({
28541
+ channelName: "session.sendAndWait",
28542
+ kind: "async"
28543
+ })
28544
+ },
28545
+ { instrumentationName: INSTRUMENTATION_NAMES.GITHUB_COPILOT }
28546
+ );
27660
28547
 
27661
28548
  // src/instrumentation/plugins/github-copilot-plugin.ts
27662
28549
  var ROOT_AGENT_KEY = "__root__";
@@ -27747,11 +28634,16 @@ async function handleTurnStart(state, agentId) {
27747
28634
  return;
27748
28635
  }
27749
28636
  const parentId = await getParentIdForAgent(state, agentId);
27750
- const span = startSpan({
27751
- name: "Copilot Turn",
27752
- parent: parentId,
27753
- spanAttributes: { type: "task" /* TASK */ }
27754
- });
28637
+ const span = startSpan(
28638
+ withSpanInstrumentationName(
28639
+ {
28640
+ name: "Copilot Turn",
28641
+ parent: parentId,
28642
+ spanAttributes: { type: "task" /* TASK */ }
28643
+ },
28644
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
28645
+ )
28646
+ );
27755
28647
  const pendingUserMessage = state.pendingUserMessages.get(key);
27756
28648
  if (pendingUserMessage) {
27757
28649
  span.log({ input: pendingUserMessage });
@@ -27782,11 +28674,16 @@ async function handleUsage(state, agentId, usage) {
27782
28674
  const parentId = turn ? await turn.id : await state.session.id;
27783
28675
  const content = state.currentMessageContent.get(key);
27784
28676
  const { metrics, metadata } = extractMetricsFromUsage(usage);
27785
- const llmSpan = startSpan({
27786
- name: "github.copilot.llm",
27787
- parent: parentId,
27788
- spanAttributes: { type: "llm" /* LLM */ }
27789
- });
28677
+ const llmSpan = startSpan(
28678
+ withSpanInstrumentationName(
28679
+ {
28680
+ name: "github.copilot.llm",
28681
+ parent: parentId,
28682
+ spanAttributes: { type: "llm" /* LLM */ }
28683
+ },
28684
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
28685
+ )
28686
+ );
27790
28687
  llmSpan.log({
27791
28688
  output: content ?? void 0,
27792
28689
  metadata,
@@ -27812,11 +28709,16 @@ async function handleToolStart(state, agentId, toolCallId, toolName, args, mcpSe
27812
28709
  }
27813
28710
  const parentId = await getToolParentId(state, agentId);
27814
28711
  const displayName = mcpServerName ? `tool: ${mcpServerName}/${toolName}` : `tool: ${toolName}`;
27815
- const span = startSpan({
27816
- name: displayName,
27817
- parent: parentId,
27818
- spanAttributes: { type: "tool" /* TOOL */ }
27819
- });
28712
+ const span = startSpan(
28713
+ withSpanInstrumentationName(
28714
+ {
28715
+ name: displayName,
28716
+ parent: parentId,
28717
+ spanAttributes: { type: "tool" /* TOOL */ }
28718
+ },
28719
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
28720
+ )
28721
+ );
27820
28722
  const metadata = {
27821
28723
  "gen_ai.tool.name": toolName,
27822
28724
  "gen_ai.tool.call.id": toolCallId
@@ -27852,11 +28754,16 @@ async function handleSubagentStarted(state, agentId, toolCallId, agentDisplayNam
27852
28754
  }
27853
28755
  const tool = state.activeTools.get(toolCallId);
27854
28756
  const parentId = tool ? await tool.id : await state.session.id;
27855
- const span = startSpan({
27856
- name: `Agent: ${agentDisplayName}`,
27857
- parent: parentId,
27858
- spanAttributes: { type: "task" /* TASK */ }
27859
- });
28757
+ const span = startSpan(
28758
+ withSpanInstrumentationName(
28759
+ {
28760
+ name: `Agent: ${agentDisplayName}`,
28761
+ parent: parentId,
28762
+ spanAttributes: { type: "task" /* TASK */ }
28763
+ },
28764
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
28765
+ )
28766
+ );
27860
28767
  span.log({
27861
28768
  metadata: {
27862
28769
  "github_copilot.agent_name": agentDisplayName,
@@ -28082,10 +28989,15 @@ function makeSessionHandlers(sessionStates, configArgIndex, includeProviderMetad
28082
28989
  if (!config || typeof config !== "object") {
28083
28990
  return;
28084
28991
  }
28085
- const sessionSpan = startSpan({
28086
- name: "Copilot Session",
28087
- spanAttributes: { type: "task" /* TASK */ }
28088
- });
28992
+ const sessionSpan = startSpan(
28993
+ withSpanInstrumentationName(
28994
+ {
28995
+ name: "Copilot Session",
28996
+ spanAttributes: { type: "task" /* TASK */ }
28997
+ },
28998
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
28999
+ )
29000
+ );
28089
29001
  const metadata = {};
28090
29002
  if (config.model) {
28091
29003
  metadata["github_copilot.model"] = config.model;
@@ -28173,12 +29085,16 @@ var GitHubCopilotPlugin = class extends BasePlugin {
28173
29085
  };
28174
29086
 
28175
29087
  // src/instrumentation/plugins/flue-channels.ts
28176
- var flueChannels = defineChannels("@flue/runtime", {
28177
- createContext: channel({
28178
- channelName: "createFlueContext",
28179
- kind: "sync-stream"
28180
- })
28181
- });
29088
+ var flueChannels = defineChannels(
29089
+ "@flue/runtime",
29090
+ {
29091
+ createContext: channel({
29092
+ channelName: "createFlueContext",
29093
+ kind: "sync-stream"
29094
+ })
29095
+ },
29096
+ { instrumentationName: INSTRUMENTATION_NAMES.FLUE }
29097
+ );
28182
29098
 
28183
29099
  // src/instrumentation/plugins/flue-plugin.ts
28184
29100
  var FLUE_AUTO_STATE = /* @__PURE__ */ Symbol.for("braintrust.flue.auto-state");
@@ -28521,15 +29437,20 @@ var FlueObserveBridge = class {
28521
29437
  safeLog3(existing.span, { input, metadata });
28522
29438
  return;
28523
29439
  }
28524
- const span = startSpan({
28525
- name: `workflow:${workflowName}`,
28526
- spanAttributes: { type: "task" /* TASK */ },
28527
- startTime: eventTime(event.startedAt ?? event.timestamp),
28528
- event: {
28529
- input,
28530
- metadata
28531
- }
28532
- });
29440
+ const span = startSpan(
29441
+ withSpanInstrumentationName(
29442
+ {
29443
+ name: `workflow:${workflowName}`,
29444
+ spanAttributes: { type: "task" /* TASK */ },
29445
+ startTime: eventTime(event.startedAt ?? event.timestamp),
29446
+ event: {
29447
+ input,
29448
+ metadata
29449
+ }
29450
+ },
29451
+ INSTRUMENTATION_NAMES.FLUE
29452
+ )
29453
+ );
28533
29454
  this.runsById.set(event.runId, { metadata, span });
28534
29455
  }
28535
29456
  handleRunResume(event, ctx) {
@@ -28549,12 +29470,17 @@ var FlueObserveBridge = class {
28549
29470
  safeLog3(existing.span, { metadata });
28550
29471
  return;
28551
29472
  }
28552
- const span = startSpan({
28553
- name: `workflow:${workflowName}`,
28554
- spanAttributes: { type: "task" /* TASK */ },
28555
- startTime: eventTime(event.startedAt ?? event.timestamp),
28556
- event: { metadata }
28557
- });
29473
+ const span = startSpan(
29474
+ withSpanInstrumentationName(
29475
+ {
29476
+ name: `workflow:${workflowName}`,
29477
+ spanAttributes: { type: "task" /* TASK */ },
29478
+ startTime: eventTime(event.startedAt ?? event.timestamp),
29479
+ event: { metadata }
29480
+ },
29481
+ INSTRUMENTATION_NAMES.FLUE
29482
+ )
29483
+ );
28558
29484
  this.runsById.set(event.runId, { metadata, span });
28559
29485
  }
28560
29486
  handleRunEnd(event) {
@@ -29193,7 +30119,14 @@ function stateMatchesRun(state, runId) {
29193
30119
  return state.metadata["flue.run_id"] === runId;
29194
30120
  }
29195
30121
  function startFlueSpan(parent, args) {
29196
- return parent ? withCurrent(parent, () => startSpan(args)) : startSpan(args);
30122
+ return parent ? withCurrent(
30123
+ parent,
30124
+ () => startSpan(
30125
+ withSpanInstrumentationName(args, INSTRUMENTATION_NAMES.FLUE)
30126
+ )
30127
+ ) : startSpan(
30128
+ withSpanInstrumentationName(args, INSTRUMENTATION_NAMES.FLUE)
30129
+ );
29197
30130
  }
29198
30131
  function runWithCurrentSpanStore(span, next) {
29199
30132
  const state = _internalGetGlobalState();
@@ -29283,9 +30216,13 @@ var BraintrustLangChainCallbackHandler = class {
29283
30216
  ...this.options.debug ? { runId, parentRunId } : {}
29284
30217
  }
29285
30218
  };
29286
- let span = parentSpan.startSpan(args);
30219
+ const spanArgs = withSpanInstrumentationName(
30220
+ args,
30221
+ INSTRUMENTATION_NAMES.LANGCHAIN
30222
+ );
30223
+ let span = parentSpan.startSpan(spanArgs);
29287
30224
  if (!Object.is(this.options.logger, NOOP_SPAN) && Object.is(span, NOOP_SPAN)) {
29288
- span = initLogger().startSpan(args);
30225
+ span = initLogger().startSpan(spanArgs);
29289
30226
  }
29290
30227
  this.spans.set(runId, span);
29291
30228
  }
@@ -29582,16 +30519,20 @@ function isRecord(value) {
29582
30519
  }
29583
30520
 
29584
30521
  // src/instrumentation/plugins/langchain-channels.ts
29585
- var langChainChannels = defineChannels("@langchain/core", {
29586
- configure: channel({
29587
- channelName: "CallbackManager.configure",
29588
- kind: "sync-stream"
29589
- }),
29590
- configureSync: channel({
29591
- channelName: "CallbackManager._configureSync",
29592
- kind: "sync-stream"
29593
- })
29594
- });
30522
+ var langChainChannels = defineChannels(
30523
+ "@langchain/core",
30524
+ {
30525
+ configure: channel({
30526
+ channelName: "CallbackManager.configure",
30527
+ kind: "sync-stream"
30528
+ }),
30529
+ configureSync: channel({
30530
+ channelName: "CallbackManager._configureSync",
30531
+ kind: "sync-stream"
30532
+ })
30533
+ },
30534
+ { instrumentationName: INSTRUMENTATION_NAMES.LANGCHAIN }
30535
+ );
29595
30536
 
29596
30537
  // src/instrumentation/plugins/langchain-plugin.ts
29597
30538
  var LangChainPlugin = class extends BasePlugin {
@@ -29679,20 +30620,24 @@ function isBraintrustHandler(handler) {
29679
30620
  }
29680
30621
 
29681
30622
  // src/instrumentation/plugins/langsmith-channels.ts
29682
- var langSmithChannels = defineChannels("langsmith", {
29683
- createRun: channel({
29684
- channelName: "Client.createRun",
29685
- kind: "async"
29686
- }),
29687
- updateRun: channel({
29688
- channelName: "Client.updateRun",
29689
- kind: "async"
29690
- }),
29691
- batchIngestRuns: channel({
29692
- channelName: "Client.batchIngestRuns",
29693
- kind: "async"
29694
- })
29695
- });
30623
+ var langSmithChannels = defineChannels(
30624
+ "langsmith",
30625
+ {
30626
+ createRun: channel({
30627
+ channelName: "Client.createRun",
30628
+ kind: "async"
30629
+ }),
30630
+ updateRun: channel({
30631
+ channelName: "Client.updateRun",
30632
+ kind: "async"
30633
+ }),
30634
+ batchIngestRuns: channel({
30635
+ channelName: "Client.batchIngestRuns",
30636
+ kind: "async"
30637
+ })
30638
+ },
30639
+ { instrumentationName: INSTRUMENTATION_NAMES.LANGSMITH }
30640
+ );
29696
30641
 
29697
30642
  // src/instrumentation/plugins/langsmith-plugin.ts
29698
30643
  var MAX_COMPLETED_RUNS = 1e4;
@@ -29856,19 +30801,24 @@ var LangSmithPlugin = class extends BasePlugin {
29856
30801
  const traceId = stringValue2(ownValue(run, "trace_id")) ?? id;
29857
30802
  const parentId = stringValue2(ownValue(run, "parent_run_id")) ?? stringValue2(ownValue(ownValue(run, "parent_run"), "id"));
29858
30803
  const startTime = timestampSeconds(ownValue(run, "start_time"));
29859
- return startSpan({
29860
- name: stringValue2(ownValue(run, "name")) ?? "LangSmith run",
29861
- spanId: id,
29862
- parentSpanIds: {
29863
- parentSpanIds: parentId ? [parentId] : [],
29864
- rootSpanId: traceId
29865
- },
29866
- spanAttributes: {
29867
- type: mapRunType(ownValue(run, "run_type"))
29868
- },
29869
- ...startTime === void 0 ? {} : { startTime },
29870
- event: { id }
29871
- });
30804
+ return startSpan(
30805
+ withSpanInstrumentationName(
30806
+ {
30807
+ name: stringValue2(ownValue(run, "name")) ?? "LangSmith run",
30808
+ spanId: id,
30809
+ parentSpanIds: {
30810
+ parentSpanIds: parentId ? [parentId] : [],
30811
+ rootSpanId: traceId
30812
+ },
30813
+ spanAttributes: {
30814
+ type: mapRunType(ownValue(run, "run_type"))
30815
+ },
30816
+ ...startTime === void 0 ? {} : { startTime },
30817
+ event: { id }
30818
+ },
30819
+ INSTRUMENTATION_NAMES.LANGSMITH
30820
+ )
30821
+ );
29872
30822
  }
29873
30823
  logRun(span, run, previous, includeOutput) {
29874
30824
  const inputs = preferOwnValue(run, previous, "inputs");
@@ -30126,7 +31076,8 @@ var piCodingAgentChannels = defineChannels(
30126
31076
  channelName: "AgentSession.prompt",
30127
31077
  kind: "async"
30128
31078
  })
30129
- }
31079
+ },
31080
+ { instrumentationName: INSTRUMENTATION_NAMES.PI_CODING_AGENT }
30130
31081
  );
30131
31082
 
30132
31083
  // src/instrumentation/plugins/pi-coding-agent-plugin.ts
@@ -30210,14 +31161,19 @@ function startPiPromptRun(event, onFinalize) {
30210
31161
  ...session.model?.id || agent.state?.model?.id ? { model: session.model?.id ?? agent.state?.model?.id } : {},
30211
31162
  ...event.moduleVersion ? { "pi_coding_agent.version": event.moduleVersion } : {}
30212
31163
  };
30213
- const span = startSpan({
30214
- event: {
30215
- input: extractPromptInput(event.arguments[0], event.arguments[1]),
30216
- metadata
30217
- },
30218
- name: "AgentSession.prompt",
30219
- spanAttributes: { type: "task" /* TASK */ }
30220
- });
31164
+ const span = startSpan(
31165
+ withSpanInstrumentationName(
31166
+ {
31167
+ event: {
31168
+ input: extractPromptInput(event.arguments[0], event.arguments[1]),
31169
+ metadata
31170
+ },
31171
+ name: "AgentSession.prompt",
31172
+ spanAttributes: { type: "task" /* TASK */ }
31173
+ },
31174
+ INSTRUMENTATION_NAMES.PI_CODING_AGENT
31175
+ )
31176
+ );
30221
31177
  const streamPatchState = installPiStreamPatch(agent);
30222
31178
  const options = event.arguments[1];
30223
31179
  const promptText = event.arguments[0];
@@ -30387,15 +31343,20 @@ async function startPiLlmSpan(state, model, context, options) {
30387
31343
  ...extractToolMetadata(context.tools),
30388
31344
  "pi_coding_agent.operation": "agent.streamFn"
30389
31345
  };
30390
- const span = startSpan({
30391
- event: {
30392
- input: processInputAttachments(normalizePiContextInput(context)),
30393
- metadata
30394
- },
30395
- name: getLlmSpanName(model),
30396
- parent: await state.span.export(),
30397
- spanAttributes: { type: "llm" /* LLM */ }
30398
- });
31346
+ const span = startSpan(
31347
+ withSpanInstrumentationName(
31348
+ {
31349
+ event: {
31350
+ input: processInputAttachments(normalizePiContextInput(context)),
31351
+ metadata
31352
+ },
31353
+ name: getLlmSpanName(model),
31354
+ parent: await state.span.export(),
31355
+ spanAttributes: { type: "llm" /* LLM */ }
31356
+ },
31357
+ INSTRUMENTATION_NAMES.PI_CODING_AGENT
31358
+ )
31359
+ );
30399
31360
  const llmState = {
30400
31361
  finalized: false,
30401
31362
  metadata,
@@ -30563,15 +31524,20 @@ async function startPiToolSpan(state, event) {
30563
31524
  "pi_coding_agent.tool.name": event.toolName
30564
31525
  };
30565
31526
  try {
30566
- const span = startSpan({
30567
- event: {
30568
- input: event.args,
30569
- metadata
30570
- },
30571
- name: event.toolName || "tool",
30572
- parent: await state.span.export(),
30573
- spanAttributes: { type: "tool" /* TOOL */ }
30574
- });
31527
+ const span = startSpan(
31528
+ withSpanInstrumentationName(
31529
+ {
31530
+ event: {
31531
+ input: event.args,
31532
+ metadata
31533
+ },
31534
+ name: event.toolName || "tool",
31535
+ parent: await state.span.export(),
31536
+ spanAttributes: { type: "tool" /* TOOL */ }
31537
+ },
31538
+ INSTRUMENTATION_NAMES.PI_CODING_AGENT
31539
+ )
31540
+ );
30575
31541
  state.activeToolSpans.set(event.toolCallId, {
30576
31542
  restoreAutoInstrumentation,
30577
31543
  span
@@ -31003,20 +31969,24 @@ function logInstrumentationError4(context, error) {
31003
31969
  }
31004
31970
 
31005
31971
  // src/instrumentation/plugins/strands-agent-sdk-channels.ts
31006
- var strandsAgentSDKChannels = defineChannels("@strands-agents/sdk", {
31007
- agentStream: channel({
31008
- channelName: "Agent.stream",
31009
- kind: "sync-stream"
31010
- }),
31011
- graphStream: channel({
31012
- channelName: "Graph.stream",
31013
- kind: "sync-stream"
31014
- }),
31015
- swarmStream: channel({
31016
- channelName: "Swarm.stream",
31017
- kind: "sync-stream"
31018
- })
31019
- });
31972
+ var strandsAgentSDKChannels = defineChannels(
31973
+ "@strands-agents/sdk",
31974
+ {
31975
+ agentStream: channel({
31976
+ channelName: "Agent.stream",
31977
+ kind: "sync-stream"
31978
+ }),
31979
+ graphStream: channel({
31980
+ channelName: "Graph.stream",
31981
+ kind: "sync-stream"
31982
+ }),
31983
+ swarmStream: channel({
31984
+ channelName: "Swarm.stream",
31985
+ kind: "sync-stream"
31986
+ })
31987
+ },
31988
+ { instrumentationName: INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK }
31989
+ );
31020
31990
 
31021
31991
  // src/instrumentation/plugins/strands-agent-sdk-plugin.ts
31022
31992
  var MAX_STRANDS_STRING_ATTACHMENT_CACHE_ENTRIES = 32;
@@ -31171,22 +32141,32 @@ function startAgentStream(event, activeChildParents) {
31171
32141
  );
31172
32142
  const span = parentSpan ? withCurrent(
31173
32143
  parentSpan,
31174
- () => startSpan({
31175
- event: {
31176
- input,
31177
- metadata
32144
+ () => startSpan(
32145
+ withSpanInstrumentationName(
32146
+ {
32147
+ event: {
32148
+ input,
32149
+ metadata
32150
+ },
32151
+ name: formatAgentSpanName(agent),
32152
+ spanAttributes: { type: "task" /* TASK */ }
32153
+ },
32154
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
32155
+ )
32156
+ )
32157
+ ) : startSpan(
32158
+ withSpanInstrumentationName(
32159
+ {
32160
+ event: {
32161
+ input,
32162
+ metadata
32163
+ },
32164
+ name: formatAgentSpanName(agent),
32165
+ spanAttributes: { type: "task" /* TASK */ }
31178
32166
  },
31179
- name: formatAgentSpanName(agent),
31180
- spanAttributes: { type: "task" /* TASK */ }
31181
- })
31182
- ) : startSpan({
31183
- event: {
31184
- input,
31185
- metadata
31186
- },
31187
- name: formatAgentSpanName(agent),
31188
- spanAttributes: { type: "task" /* TASK */ }
31189
- });
32167
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
32168
+ )
32169
+ );
31190
32170
  return {
31191
32171
  activeTools: /* @__PURE__ */ new Map(),
31192
32172
  attachmentCache,
@@ -31208,22 +32188,32 @@ function startMultiAgentStream(event, operation, activeChildParents) {
31208
32188
  const input = processStrandsInputAttachments(event.arguments[0]);
31209
32189
  const span = parentSpan ? withCurrent(
31210
32190
  parentSpan,
31211
- () => startSpan({
31212
- event: {
31213
- input,
31214
- metadata
32191
+ () => startSpan(
32192
+ withSpanInstrumentationName(
32193
+ {
32194
+ event: {
32195
+ input,
32196
+ metadata
32197
+ },
32198
+ name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
32199
+ spanAttributes: { type: "task" /* TASK */ }
32200
+ },
32201
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
32202
+ )
32203
+ )
32204
+ ) : startSpan(
32205
+ withSpanInstrumentationName(
32206
+ {
32207
+ event: {
32208
+ input,
32209
+ metadata
32210
+ },
32211
+ name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
32212
+ spanAttributes: { type: "task" /* TASK */ }
31215
32213
  },
31216
- name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
31217
- spanAttributes: { type: "task" /* TASK */ }
31218
- })
31219
- ) : startSpan({
31220
- event: {
31221
- input,
31222
- metadata
31223
- },
31224
- name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
31225
- spanAttributes: { type: "task" /* TASK */ }
31226
- });
32214
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
32215
+ )
32216
+ );
31227
32217
  return {
31228
32218
  activeNodes: /* @__PURE__ */ new Map(),
31229
32219
  finalized: false,
@@ -31325,17 +32315,22 @@ function startModelSpan(state, event) {
31325
32315
  };
31326
32316
  const span = withCurrent(
31327
32317
  state.span,
31328
- () => startSpan({
31329
- event: {
31330
- input: Array.isArray(event.agent?.messages) ? processStrandsInputAttachments(
31331
- event.agent.messages,
31332
- state.attachmentCache
31333
- ) : void 0,
31334
- metadata
31335
- },
31336
- name: formatModelSpanName(model),
31337
- spanAttributes: { type: "llm" /* LLM */ }
31338
- })
32318
+ () => startSpan(
32319
+ withSpanInstrumentationName(
32320
+ {
32321
+ event: {
32322
+ input: Array.isArray(event.agent?.messages) ? processStrandsInputAttachments(
32323
+ event.agent.messages,
32324
+ state.attachmentCache
32325
+ ) : void 0,
32326
+ metadata
32327
+ },
32328
+ name: formatModelSpanName(model),
32329
+ spanAttributes: { type: "llm" /* LLM */ }
32330
+ },
32331
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
32332
+ )
32333
+ )
31339
32334
  );
31340
32335
  state.activeModel = {
31341
32336
  metadata,
@@ -31387,20 +32382,25 @@ function startToolSpan2(state, event) {
31387
32382
  const name = extractToolName3(toolUse, event.tool);
31388
32383
  const span = withCurrent(
31389
32384
  state.span,
31390
- () => startSpan({
31391
- event: {
31392
- input: toolUse?.input,
31393
- metadata: {
31394
- "gen_ai.tool.call.id": toolUse?.toolUseId,
31395
- "gen_ai.tool.name": name,
31396
- "strands.operation": "tool.call",
31397
- "strands.tool.name": name,
31398
- provider: "strands"
31399
- }
31400
- },
31401
- name: `tool: ${name}`,
31402
- spanAttributes: { type: "tool" /* TOOL */ }
31403
- })
32385
+ () => startSpan(
32386
+ withSpanInstrumentationName(
32387
+ {
32388
+ event: {
32389
+ input: toolUse?.input,
32390
+ metadata: {
32391
+ "gen_ai.tool.call.id": toolUse?.toolUseId,
32392
+ "gen_ai.tool.name": name,
32393
+ "strands.operation": "tool.call",
32394
+ "strands.tool.name": name,
32395
+ provider: "strands"
32396
+ }
32397
+ },
32398
+ name: `tool: ${name}`,
32399
+ spanAttributes: { type: "tool" /* TOOL */ }
32400
+ },
32401
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
32402
+ )
32403
+ )
31404
32404
  );
31405
32405
  state.activeTools.set(key, {
31406
32406
  span,
@@ -31471,11 +32471,16 @@ function startNodeSpan(state, event, activeChildParents) {
31471
32471
  };
31472
32472
  const span = withCurrent(
31473
32473
  state.span,
31474
- () => startSpan({
31475
- event: { metadata },
31476
- name: `node: ${nodeId}`,
31477
- spanAttributes: { type: "task" /* TASK */ }
31478
- })
32474
+ () => startSpan(
32475
+ withSpanInstrumentationName(
32476
+ {
32477
+ event: { metadata },
32478
+ name: `node: ${nodeId}`,
32479
+ spanAttributes: { type: "task" /* TASK */ }
32480
+ },
32481
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
32482
+ )
32483
+ )
31479
32484
  );
31480
32485
  const nodeState = {
31481
32486
  ...child ? { child } : {},
@@ -33288,6 +34293,12 @@ var wrapAgentClass = (AgentClass, options = {}) => {
33288
34293
  const original = Reflect.get(instanceTarget, prop, instanceTarget);
33289
34294
  if (harnessAgent && typeof original === "function") {
33290
34295
  switch (prop) {
34296
+ case "createSession":
34297
+ return wrapHarnessAgentCreateSession(
34298
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
34299
+ original,
34300
+ harnessAgent
34301
+ );
33291
34302
  case "generate":
33292
34303
  return wrapHarnessAgentGenerate(
33293
34304
  original,
@@ -33337,6 +34348,19 @@ var wrapAgentClass = (AgentClass, options = {}) => {
33337
34348
  }
33338
34349
  });
33339
34350
  };
34351
+ var wrapHarnessAgentCreateSession = (createSession, instance) => {
34352
+ const wrapper = function(params) {
34353
+ return harnessAgentChannels.createSession.tracePromise(
34354
+ () => params === void 0 ? createSession.call(instance) : createSession.call(instance, params),
34355
+ createAISDKChannelContext(params ?? {}, { self: instance })
34356
+ );
34357
+ };
34358
+ Object.defineProperty(wrapper, "name", {
34359
+ value: "HarnessAgent.createSession",
34360
+ writable: false
34361
+ });
34362
+ return wrapper;
34363
+ };
33340
34364
  var wrapHarnessAgentGenerate = (generate, instance, channel2, name, options) => makeGenerateTextWrapper(
33341
34365
  channel2,
33342
34366
  name,
@@ -33606,12 +34630,17 @@ var BraintrustLanguageModelWrapper = class {
33606
34630
  // For the first cut, do not support custom span_info arguments. We can
33607
34631
  // propagate those via async local storage
33608
34632
  async doGenerate(options) {
33609
- const span = startSpan({
33610
- name: "Chat Completion",
33611
- spanAttributes: {
33612
- type: "llm"
33613
- }
33614
- });
34633
+ const span = startSpan(
34634
+ withSpanInstrumentationName(
34635
+ {
34636
+ name: "Chat Completion",
34637
+ spanAttributes: {
34638
+ type: "llm"
34639
+ }
34640
+ },
34641
+ INSTRUMENTATION_NAMES.AI_SDK
34642
+ )
34643
+ );
33615
34644
  const { prompt, mode, ...rest } = options;
33616
34645
  const startTime = getCurrentUnixTimestamp();
33617
34646
  try {
@@ -33642,12 +34671,17 @@ var BraintrustLanguageModelWrapper = class {
33642
34671
  async doStream(options) {
33643
34672
  const { prompt, mode, ...rest } = options;
33644
34673
  const startTime = getCurrentUnixTimestamp();
33645
- const span = startSpan({
33646
- name: "Chat Completion",
33647
- spanAttributes: {
33648
- type: "llm"
33649
- }
33650
- });
34674
+ const span = startSpan(
34675
+ withSpanInstrumentationName(
34676
+ {
34677
+ name: "Chat Completion",
34678
+ spanAttributes: {
34679
+ type: "llm"
34680
+ }
34681
+ },
34682
+ INSTRUMENTATION_NAMES.AI_SDK
34683
+ )
34684
+ );
33651
34685
  span.log({
33652
34686
  input: postProcessPrompt(prompt),
33653
34687
  metadata: {
@@ -34002,7 +35036,9 @@ function BraintrustMiddleware(config = {}) {
34002
35036
  }
34003
35037
  }
34004
35038
  };
34005
- const span = startSpan(spanArgs);
35039
+ const span = startSpan(
35040
+ withSpanInstrumentationName(spanArgs, INSTRUMENTATION_NAMES.AI_SDK)
35041
+ );
34006
35042
  try {
34007
35043
  const result = await doGenerate();
34008
35044
  const metadata = {};
@@ -34064,7 +35100,9 @@ function BraintrustMiddleware(config = {}) {
34064
35100
  }
34065
35101
  }
34066
35102
  };
34067
- const span = startSpan(spanArgs);
35103
+ const span = startSpan(
35104
+ withSpanInstrumentationName(spanArgs, INSTRUMENTATION_NAMES.AI_SDK)
35105
+ );
34068
35106
  try {
34069
35107
  const { stream, ...rest } = await doStream();
34070
35108
  const textChunks = [];
@@ -34271,7 +35309,12 @@ var EveBridge = class {
34271
35309
  };
34272
35310
  const span = withCurrent(
34273
35311
  NOOP_SPAN,
34274
- () => _internalStartSpanWithInitialMerge({ ...args, startTime })
35312
+ () => _internalStartSpanWithInitialMerge(
35313
+ withSpanInstrumentationName(
35314
+ { ...args, startTime },
35315
+ INSTRUMENTATION_NAMES.EVE
35316
+ )
35317
+ )
34275
35318
  );
34276
35319
  if (typeof rowId !== "string") {
34277
35320
  return span;
@@ -36045,17 +37088,20 @@ var BraintrustObservabilityExporter = class {
36045
37088
  }
36046
37089
  onStart(exported) {
36047
37090
  if (this.spans.has(exported.id)) return;
36048
- const args = {
36049
- name: exported.name,
36050
- spanAttributes: { type: spanTypeFor(exported.type) },
36051
- startTime: epochSeconds(exported.startTime),
36052
- // Use the Mastra span id as the Braintrust row id so that
36053
- // `logFeedback({ id: <mastra span id> })` (and Mastra's score events)
36054
- // attach to the right row. Without this, `SpanImpl` auto-generates a
36055
- // row id (`this._id = eventId ?? idGenerator.getSpanId()`) that no
36056
- // external caller could know.
36057
- event: { id: exported.id }
36058
- };
37091
+ const args = withSpanInstrumentationName(
37092
+ {
37093
+ name: exported.name,
37094
+ spanAttributes: { type: spanTypeFor(exported.type) },
37095
+ startTime: epochSeconds(exported.startTime),
37096
+ // Use the Mastra span id as the Braintrust row id so that
37097
+ // `logFeedback({ id: <mastra span id> })` (and Mastra's score events)
37098
+ // attach to the right row. Without this, `SpanImpl` auto-generates a
37099
+ // row id (`this._id = eventId ?? idGenerator.getSpanId()`) that no
37100
+ // external caller could know.
37101
+ event: { id: exported.id }
37102
+ },
37103
+ INSTRUMENTATION_NAMES.MASTRA
37104
+ );
36059
37105
  const parentRecord = exported.parentSpanId ? this.spans.get(exported.parentSpanId) : void 0;
36060
37106
  if (!this.capturedParent) {
36061
37107
  const probe = currentSpan();
@@ -41441,26 +42487,30 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
41441
42487
  }
41442
42488
  }
41443
42489
  })();
42490
+ let timeoutId;
42491
+ let abortHandler;
42492
+ const cleanupCancellation = () => {
42493
+ if (timeoutId !== void 0) {
42494
+ clearTimeout(timeoutId);
42495
+ timeoutId = void 0;
42496
+ }
42497
+ if (abortHandler && evaluator.signal) {
42498
+ evaluator.signal.removeEventListener("abort", abortHandler);
42499
+ abortHandler = void 0;
42500
+ }
42501
+ };
41444
42502
  const cancel = async () => {
41445
42503
  await new Promise((_, reject2) => {
41446
42504
  if (cancelled) {
41447
42505
  reject2(new InternalAbortError("Evaluator already cancelled"));
41448
42506
  return;
41449
42507
  }
41450
- let timeoutId;
41451
- let abortHandler;
41452
42508
  const rejectOnce = (error) => {
41453
42509
  if (cancelled) {
41454
42510
  return;
41455
42511
  }
41456
42512
  cancelled = true;
41457
- if (timeoutId) {
41458
- clearTimeout(timeoutId);
41459
- timeoutId = void 0;
41460
- }
41461
- if (abortHandler && evaluator.signal) {
41462
- evaluator.signal.removeEventListener("abort", abortHandler);
41463
- }
42513
+ cleanupCancellation();
41464
42514
  reject2(error);
41465
42515
  };
41466
42516
  if (evaluator.timeout) {
@@ -41500,6 +42550,7 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
41500
42550
  }
41501
42551
  throw e;
41502
42552
  } finally {
42553
+ cleanupCancellation();
41503
42554
  if (!collectResults) {
41504
42555
  collectedResults.length = 0;
41505
42556
  }