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/workerd.mjs CHANGED
@@ -4823,7 +4823,51 @@ var SpanCache = class {
4823
4823
  };
4824
4824
 
4825
4825
  // src/span-origin.ts
4826
- var SDK_VERSION = true ? "3.24.0" : "0.0.0";
4826
+ var INSTRUMENTATION_NAMES = {
4827
+ AI_SDK: "ai-sdk",
4828
+ ANTHROPIC: "anthropic",
4829
+ BEDROCK_RUNTIME: "bedrock-runtime",
4830
+ BRAINTRUST_JS_LOGGER: "braintrust-js-logger",
4831
+ CLAUDE_AGENT_SDK: "claude-agent-sdk",
4832
+ COHERE: "cohere",
4833
+ CURSOR_SDK: "cursor-sdk",
4834
+ EVE: "eve",
4835
+ FLUE: "flue",
4836
+ GENKIT: "genkit",
4837
+ GITHUB_COPILOT: "github-copilot",
4838
+ GOOGLE_ADK: "google-adk",
4839
+ GOOGLE_GENAI: "google-genai",
4840
+ GROQ: "groq",
4841
+ HUGGINGFACE: "huggingface",
4842
+ LANGCHAIN: "langchain",
4843
+ LANGSMITH: "langsmith",
4844
+ MASTRA: "mastra",
4845
+ MISTRAL: "mistral",
4846
+ OPENAI: "openai",
4847
+ OPENAI_AGENTS: "openai-agents",
4848
+ OPENAI_CODEX: "openai-codex",
4849
+ OPENROUTER: "openrouter",
4850
+ OPENROUTER_AGENT: "openrouter-agent",
4851
+ PI_CODING_AGENT: "pi-coding-agent",
4852
+ STRANDS_AGENT_SDK: "strands-agent-sdk"
4853
+ };
4854
+ var INTERNAL_SPAN_INSTRUMENTATION_NAME = /* @__PURE__ */ Symbol.for(
4855
+ "braintrust.spanInstrumentationName"
4856
+ );
4857
+ var SDK_VERSION = true ? "3.25.0" : "0.0.0";
4858
+ function withSpanInstrumentationName(args, instrumentationName) {
4859
+ return {
4860
+ ...args,
4861
+ [INTERNAL_SPAN_INSTRUMENTATION_NAME]: instrumentationName
4862
+ };
4863
+ }
4864
+ function getSpanInstrumentationName(args) {
4865
+ if (typeof args !== "object" || args === null) {
4866
+ return void 0;
4867
+ }
4868
+ const value = args[INTERNAL_SPAN_INSTRUMENTATION_NAME];
4869
+ return isSpanInstrumentationName(value) ? value : void 0;
4870
+ }
4827
4871
  function detectSpanOriginEnvironment(explicit) {
4828
4872
  if (explicit) return explicit;
4829
4873
  const envType = isomorph_default.getEnv("BRAINTRUST_ENVIRONMENT_TYPE");
@@ -4895,6 +4939,9 @@ function mergeSpanOriginContext(context, instrumentationName, environment) {
4895
4939
  };
4896
4940
  return next;
4897
4941
  }
4942
+ function isSpanInstrumentationName(value) {
4943
+ return Object.values(INSTRUMENTATION_NAMES).some((name) => name === value);
4944
+ }
4898
4945
  function firstPresent(entries) {
4899
4946
  return entries.find(([key]) => Boolean(isomorph_default.getEnv(key)))?.[1];
4900
4947
  }
@@ -5189,6 +5236,7 @@ var BraintrustState = class _BraintrustState {
5189
5236
  });
5190
5237
  this.spanCache = new SpanCache({ disabled: loginParams.disableSpanCache });
5191
5238
  this.spanOriginEnvironment = detectSpanOriginEnvironment();
5239
+ this._internalSetTraceContextSigningSecret(loginParams.apiKey);
5192
5240
  }
5193
5241
  loginParams;
5194
5242
  id;
@@ -5226,6 +5274,18 @@ var BraintrustState = class _BraintrustState {
5226
5274
  _contextManager = null;
5227
5275
  _otelFlushCallback = null;
5228
5276
  spanOriginEnvironment;
5277
+ traceContextSigningSecret;
5278
+ /** @internal */
5279
+ _internalSetTraceContextSigningSecret(secret) {
5280
+ const normalizedSecret = secret?.trim();
5281
+ if (normalizedSecret) {
5282
+ this.traceContextSigningSecret = normalizedSecret;
5283
+ }
5284
+ }
5285
+ /** @internal */
5286
+ _internalGetTraceContextSigningSecret() {
5287
+ return (this.traceContextSigningSecret ?? this.loginToken ?? isomorph_default.getEnv("BRAINTRUST_API_KEY"))?.trim();
5288
+ }
5229
5289
  resetLoginInfo() {
5230
5290
  this.appUrl = null;
5231
5291
  this.appPublicUrl = null;
@@ -5286,6 +5346,7 @@ var BraintrustState = class _BraintrustState {
5286
5346
  this.gitMetadataSettings = other.gitMetadataSettings;
5287
5347
  this.debugLogLevel = other.debugLogLevel;
5288
5348
  this.debugLogLevelConfigured = other.debugLogLevelConfigured;
5349
+ this.traceContextSigningSecret = other.traceContextSigningSecret;
5289
5350
  setGlobalDebugLogLevel(
5290
5351
  this.debugLogLevelConfigured ? this.debugLogLevel ?? false : void 0
5291
5352
  );
@@ -5373,6 +5434,7 @@ var BraintrustState = class _BraintrustState {
5373
5434
  return this.debugLogLevelConfigured;
5374
5435
  }
5375
5436
  async login(loginParams) {
5437
+ this._internalSetTraceContextSigningSecret(loginParams.apiKey);
5376
5438
  this.setDebugLogLevel(loginParams.debugLogLevel);
5377
5439
  if (this.apiUrl && !loginParams.forceLogin) {
5378
5440
  return;
@@ -7352,6 +7414,7 @@ function init(projectOrOptions, optionalOptions) {
7352
7414
  throw new Error("Cannot open and update an experiment at the same time");
7353
7415
  }
7354
7416
  const state = stateArg ?? _globalState;
7417
+ state._internalSetTraceContextSigningSecret(apiKey);
7355
7418
  state.enforceQueueSizeLimit(false);
7356
7419
  if (open) {
7357
7420
  if (isEmpty2(experiment)) {
@@ -7860,6 +7923,7 @@ function initLogger(options = {}) {
7860
7923
  project_id: projectId
7861
7924
  };
7862
7925
  const state = stateArg ?? _globalState;
7926
+ state._internalSetTraceContextSigningSecret(apiKey);
7863
7927
  state.setDebugLogLevel(debugLogLevel);
7864
7928
  state.spanOriginEnvironment = detectSpanOriginEnvironment(environment);
7865
7929
  state.enforceQueueSizeLimit(true);
@@ -8923,7 +8987,9 @@ function deepCopyEvent(event) {
8923
8987
  const ATTACHMENT_MARKER_KEY = "_bt_internal_saved_attachment_marker";
8924
8988
  const attachmentMarker = ++deepCopyEventMarkerCounter;
8925
8989
  const serialized = JSON.stringify(event, (_k, v) => {
8926
- if (v instanceof SpanImpl || v instanceof NoopSpan) {
8990
+ if (v instanceof Error) {
8991
+ return v.message;
8992
+ } else if (v instanceof SpanImpl || v instanceof NoopSpan) {
8927
8993
  return `<span>`;
8928
8994
  } else if (v instanceof Experiment2) {
8929
8995
  return `<experiment>`;
@@ -9591,6 +9657,7 @@ var SpanImpl = class _SpanImpl {
9591
9657
  constructor(args) {
9592
9658
  this._state = args.state;
9593
9659
  this._propagatedState = args.propagatedState;
9660
+ const instrumentationName = getSpanInstrumentationName(args) ?? INSTRUMENTATION_NAMES.BRAINTRUST_JS_LOGGER;
9594
9661
  const spanAttributes = args.spanAttributes ?? {};
9595
9662
  const rawEvent = args.event ?? {};
9596
9663
  const type = args.type ?? (args.parentSpanIds ? void 0 : args.defaultRootType);
@@ -9622,7 +9689,7 @@ var SpanImpl = class _SpanImpl {
9622
9689
  },
9623
9690
  context: mergeSpanOriginContext(
9624
9691
  { ...callerLocation },
9625
- "braintrust-js-logger",
9692
+ instrumentationName,
9626
9693
  this._state.spanOriginEnvironment
9627
9694
  ),
9628
9695
  span_attributes: {
@@ -11729,15 +11796,25 @@ function hasChoices(value) {
11729
11796
  function normalizeMetadata(metadata) {
11730
11797
  return isObject(metadata) ? metadata : void 0;
11731
11798
  }
11732
- function startSpanForEvent(config, event, channelName) {
11799
+ function startSpanForEvent(config, event, channelName, instrumentationName) {
11733
11800
  const { name, spanAttributes, spanInfoMetadata } = buildStartSpanArgs(
11734
11801
  config,
11735
11802
  event
11736
11803
  );
11737
- const span = startSpan({
11738
- name,
11739
- spanAttributes
11740
- });
11804
+ const spanArgs = withSpanInstrumentationName(
11805
+ {
11806
+ name,
11807
+ spanAttributes
11808
+ },
11809
+ instrumentationName
11810
+ );
11811
+ let span;
11812
+ try {
11813
+ span = config.startSpan?.(spanArgs) ?? startSpan(spanArgs);
11814
+ } catch (error) {
11815
+ debugLogger.error(`Error starting span for ${channelName}:`, error);
11816
+ span = startSpan(spanArgs);
11817
+ }
11741
11818
  const startTime = getCurrentUnixTimestamp();
11742
11819
  try {
11743
11820
  const { input, metadata } = config.extractInput(
@@ -11768,7 +11845,7 @@ function shouldTraceEvent(config, event, channelName) {
11768
11845
  return true;
11769
11846
  }
11770
11847
  }
11771
- function ensureSpanStateForEvent(states, config, event, channelName) {
11848
+ function ensureSpanStateForEvent(states, config, event, channelName, instrumentationName) {
11772
11849
  const key = event;
11773
11850
  const existing = states.get(key);
11774
11851
  if (existing) {
@@ -11777,11 +11854,16 @@ function ensureSpanStateForEvent(states, config, event, channelName) {
11777
11854
  if (!shouldTraceEvent(config, event, channelName)) {
11778
11855
  return void 0;
11779
11856
  }
11780
- const created = startSpanForEvent(config, event, channelName);
11857
+ const created = startSpanForEvent(
11858
+ config,
11859
+ event,
11860
+ channelName,
11861
+ instrumentationName
11862
+ );
11781
11863
  states.set(key, created);
11782
11864
  return created;
11783
11865
  }
11784
- function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelName) {
11866
+ function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelName, instrumentationName) {
11785
11867
  const state = _internalGetGlobalState();
11786
11868
  const startChannel = tracingChannel2.start;
11787
11869
  const contextManager = state?.contextManager;
@@ -11799,7 +11881,8 @@ function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelNam
11799
11881
  states,
11800
11882
  config,
11801
11883
  event,
11802
- channelName
11884
+ channelName,
11885
+ instrumentationName
11803
11886
  );
11804
11887
  return spanState ? contextManager.wrapSpanForStore(spanState.span) : currentSpanStore.getStore();
11805
11888
  }
@@ -11808,15 +11891,21 @@ function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelNam
11808
11891
  startChannel.unbindStore(currentSpanStore);
11809
11892
  };
11810
11893
  }
11811
- function logErrorAndEnd(states, event) {
11894
+ function logErrorAndEnd(states, event, channelName) {
11812
11895
  const spanData = states.get(event);
11813
11896
  if (!spanData) {
11814
11897
  return;
11815
11898
  }
11816
- spanData.span.log({
11817
- error: event.error.message
11818
- });
11819
- spanData.span.end();
11899
+ try {
11900
+ spanData.span.log({ error: event.error });
11901
+ } catch (error) {
11902
+ debugLogger.error(`Error logging failure for ${channelName}:`, error);
11903
+ }
11904
+ try {
11905
+ spanData.span.end();
11906
+ } catch (error) {
11907
+ debugLogger.error(`Error ending span for ${channelName}:`, error);
11908
+ }
11820
11909
  states.delete(event);
11821
11910
  }
11822
11911
  function runStreamingCompletionHook(args) {
@@ -11866,7 +11955,8 @@ function traceAsyncChannel(channel2, config) {
11866
11955
  tracingChannel2,
11867
11956
  states,
11868
11957
  config,
11869
- channelName
11958
+ channelName,
11959
+ channel2.instrumentationName
11870
11960
  );
11871
11961
  const handlers = {
11872
11962
  start: (event) => {
@@ -11877,7 +11967,8 @@ function traceAsyncChannel(channel2, config) {
11877
11967
  states,
11878
11968
  config,
11879
11969
  event,
11880
- channelName
11970
+ channelName,
11971
+ channel2.instrumentationName
11881
11972
  );
11882
11973
  },
11883
11974
  asyncEnd: (event) => {
@@ -11914,7 +12005,7 @@ function traceAsyncChannel(channel2, config) {
11914
12005
  }
11915
12006
  },
11916
12007
  error: (event) => {
11917
- logErrorAndEnd(states, event);
12008
+ logErrorAndEnd(states, event, channelName);
11918
12009
  }
11919
12010
  };
11920
12011
  tracingChannel2.subscribe(handlers);
@@ -11931,7 +12022,8 @@ function traceStreamingChannel(channel2, config) {
11931
12022
  tracingChannel2,
11932
12023
  states,
11933
12024
  config,
11934
- channelName
12025
+ channelName,
12026
+ channel2.instrumentationName
11935
12027
  );
11936
12028
  const handlers = {
11937
12029
  start: (event) => {
@@ -11942,7 +12034,8 @@ function traceStreamingChannel(channel2, config) {
11942
12034
  states,
11943
12035
  config,
11944
12036
  event,
11945
- channelName
12037
+ channelName,
12038
+ channel2.instrumentationName
11946
12039
  );
11947
12040
  },
11948
12041
  asyncEnd: (event) => {
@@ -11961,6 +12054,7 @@ function traceStreamingChannel(channel2, config) {
11961
12054
  }
11962
12055
  },
11963
12056
  onComplete: (chunks) => {
12057
+ let completion2;
11964
12058
  try {
11965
12059
  let output;
11966
12060
  let metrics;
@@ -11991,18 +12085,11 @@ function traceStreamingChannel(channel2, config) {
11991
12085
  } else if (metrics.time_to_first_token === void 0 && chunks.length > 0) {
11992
12086
  metrics.time_to_first_token = getCurrentUnixTimestamp() - startTime;
11993
12087
  }
11994
- runStreamingCompletionHook({
11995
- channelName,
11996
- chunks,
11997
- config,
11998
- endEvent: asyncEndEvent,
12088
+ completion2 = {
11999
12089
  ...metadata !== void 0 ? { metadata } : {},
12000
12090
  metrics,
12001
- output,
12002
- result: asyncEndEvent.result,
12003
- span,
12004
- startTime
12005
- });
12091
+ output
12092
+ };
12006
12093
  span.log({
12007
12094
  output,
12008
12095
  ...metadata !== void 0 ? { metadata } : {},
@@ -12014,11 +12101,49 @@ function traceStreamingChannel(channel2, config) {
12014
12101
  error
12015
12102
  );
12016
12103
  } finally {
12017
- span.end();
12104
+ try {
12105
+ span.end();
12106
+ } catch (error) {
12107
+ debugLogger.error(
12108
+ `Error ending span for ${channelName}:`,
12109
+ error
12110
+ );
12111
+ }
12018
12112
  states.delete(event);
12019
12113
  }
12114
+ if (completion2) {
12115
+ runStreamingCompletionHook({
12116
+ channelName,
12117
+ chunks,
12118
+ config,
12119
+ endEvent: asyncEndEvent,
12120
+ ...completion2.metadata !== void 0 ? { metadata: completion2.metadata } : {},
12121
+ metrics: completion2.metrics,
12122
+ output: completion2.output,
12123
+ result: asyncEndEvent.result,
12124
+ span,
12125
+ startTime
12126
+ });
12127
+ }
12020
12128
  },
12021
12129
  onError: (error) => {
12130
+ try {
12131
+ span.log({ error });
12132
+ } catch (loggingError) {
12133
+ debugLogger.error(
12134
+ `Error logging failure for ${channelName}:`,
12135
+ loggingError
12136
+ );
12137
+ }
12138
+ try {
12139
+ span.end();
12140
+ } catch (endingError) {
12141
+ debugLogger.error(
12142
+ `Error ending span for ${channelName}:`,
12143
+ endingError
12144
+ );
12145
+ }
12146
+ states.delete(event);
12022
12147
  runStreamingErrorHook({
12023
12148
  channelName,
12024
12149
  config,
@@ -12027,11 +12152,6 @@ function traceStreamingChannel(channel2, config) {
12027
12152
  span,
12028
12153
  startTime
12029
12154
  });
12030
- span.log({
12031
- error: error.message
12032
- });
12033
- span.end();
12034
- states.delete(event);
12035
12155
  }
12036
12156
  });
12037
12157
  return;
@@ -12046,6 +12166,7 @@ function traceStreamingChannel(channel2, config) {
12046
12166
  states.delete(event);
12047
12167
  return;
12048
12168
  }
12169
+ let completion;
12049
12170
  try {
12050
12171
  const output = config.extractOutput(
12051
12172
  asyncEndEvent.result,
@@ -12060,17 +12181,11 @@ function traceStreamingChannel(channel2, config) {
12060
12181
  asyncEndEvent.result,
12061
12182
  asyncEndEvent
12062
12183
  );
12063
- runStreamingCompletionHook({
12064
- channelName,
12065
- config,
12066
- endEvent: asyncEndEvent,
12184
+ completion = {
12067
12185
  ...normalizeMetadata(metadata) !== void 0 ? { metadata: normalizeMetadata(metadata) } : {},
12068
12186
  metrics,
12069
- output,
12070
- result: asyncEndEvent.result,
12071
- span,
12072
- startTime
12073
- });
12187
+ output
12188
+ };
12074
12189
  span.log({
12075
12190
  output,
12076
12191
  ...normalizeMetadata(metadata) !== void 0 ? { metadata: normalizeMetadata(metadata) } : {},
@@ -12079,12 +12194,30 @@ function traceStreamingChannel(channel2, config) {
12079
12194
  } catch (error) {
12080
12195
  debugLogger.error(`Error extracting output for ${channelName}:`, error);
12081
12196
  } finally {
12082
- span.end();
12197
+ try {
12198
+ span.end();
12199
+ } catch (error) {
12200
+ debugLogger.error(`Error ending span for ${channelName}:`, error);
12201
+ }
12083
12202
  states.delete(event);
12084
12203
  }
12204
+ if (completion) {
12205
+ runStreamingCompletionHook({
12206
+ channelName,
12207
+ config,
12208
+ endEvent: asyncEndEvent,
12209
+ ...completion.metadata !== void 0 ? { metadata: completion.metadata } : {},
12210
+ metrics: completion.metrics,
12211
+ output: completion.output,
12212
+ result: asyncEndEvent.result,
12213
+ span,
12214
+ startTime
12215
+ });
12216
+ }
12085
12217
  },
12086
12218
  error: (event) => {
12087
12219
  const spanData = states.get(event);
12220
+ logErrorAndEnd(states, event, channelName);
12088
12221
  if (spanData) {
12089
12222
  runStreamingErrorHook({
12090
12223
  channelName,
@@ -12095,7 +12228,6 @@ function traceStreamingChannel(channel2, config) {
12095
12228
  startTime: spanData.startTime
12096
12229
  });
12097
12230
  }
12098
- logErrorAndEnd(states, event);
12099
12231
  }
12100
12232
  };
12101
12233
  tracingChannel2.subscribe(handlers);
@@ -12112,7 +12244,8 @@ function traceSyncStreamChannel(channel2, config) {
12112
12244
  tracingChannel2,
12113
12245
  states,
12114
12246
  config,
12115
- channelName
12247
+ channelName,
12248
+ channel2.instrumentationName
12116
12249
  );
12117
12250
  const handlers = {
12118
12251
  start: (event) => {
@@ -12123,7 +12256,8 @@ function traceSyncStreamChannel(channel2, config) {
12123
12256
  states,
12124
12257
  config,
12125
12258
  event,
12126
- channelName
12259
+ channelName,
12260
+ channel2.instrumentationName
12127
12261
  );
12128
12262
  },
12129
12263
  end: (event) => {
@@ -12217,7 +12351,7 @@ function traceSyncStreamChannel(channel2, config) {
12217
12351
  handleResolvedResult(endEvent.result);
12218
12352
  },
12219
12353
  error: (event) => {
12220
- logErrorAndEnd(states, event);
12354
+ logErrorAndEnd(states, event, channelName);
12221
12355
  }
12222
12356
  };
12223
12357
  tracingChannel2.subscribe(handlers);
@@ -12396,7 +12530,8 @@ function processInputAttachments(input) {
12396
12530
  function channel(spec) {
12397
12531
  return spec;
12398
12532
  }
12399
- function defineChannels(pkg, channels) {
12533
+ function defineChannels(pkg, channels, options) {
12534
+ const { instrumentationName } = options;
12400
12535
  return Object.fromEntries(
12401
12536
  Object.entries(channels).map(([key, spec]) => {
12402
12537
  const fullChannelName = `orchestrion:${pkg}:${spec.channelName}`;
@@ -12409,6 +12544,7 @@ function defineChannels(pkg, channels) {
12409
12544
  key,
12410
12545
  {
12411
12546
  ...asyncSpec,
12547
+ instrumentationName,
12412
12548
  tracingChannel: tracingChannel3,
12413
12549
  tracePromise: (fn, context) => tracingChannel3().tracePromise(
12414
12550
  fn,
@@ -12426,6 +12562,7 @@ function defineChannels(pkg, channels) {
12426
12562
  key,
12427
12563
  {
12428
12564
  ...syncSpec,
12565
+ instrumentationName,
12429
12566
  tracingChannel: tracingChannel2,
12430
12567
  traceSync: (fn, context) => tracingChannel2().traceSync(
12431
12568
  fn,
@@ -12439,44 +12576,48 @@ function defineChannels(pkg, channels) {
12439
12576
  }
12440
12577
 
12441
12578
  // src/instrumentation/plugins/openai-channels.ts
12442
- var openAIChannels = defineChannels("openai", {
12443
- chatCompletionsCreate: channel({
12444
- channelName: "chat.completions.create",
12445
- kind: "async"
12446
- }),
12447
- embeddingsCreate: channel({
12448
- channelName: "embeddings.create",
12449
- kind: "async"
12450
- }),
12451
- betaChatCompletionsParse: channel({
12452
- channelName: "beta.chat.completions.parse",
12453
- kind: "async"
12454
- }),
12455
- betaChatCompletionsStream: channel({
12456
- channelName: "beta.chat.completions.stream",
12457
- kind: "sync-stream"
12458
- }),
12459
- moderationsCreate: channel({
12460
- channelName: "moderations.create",
12461
- kind: "async"
12462
- }),
12463
- responsesCreate: channel({
12464
- channelName: "responses.create",
12465
- kind: "async"
12466
- }),
12467
- responsesStream: channel({
12468
- channelName: "responses.stream",
12469
- kind: "sync-stream"
12470
- }),
12471
- responsesParse: channel({
12472
- channelName: "responses.parse",
12473
- kind: "async"
12474
- }),
12475
- responsesCompact: channel({
12476
- channelName: "responses.compact",
12477
- kind: "async"
12478
- })
12479
- });
12579
+ var openAIChannels = defineChannels(
12580
+ "openai",
12581
+ {
12582
+ chatCompletionsCreate: channel({
12583
+ channelName: "chat.completions.create",
12584
+ kind: "async"
12585
+ }),
12586
+ embeddingsCreate: channel({
12587
+ channelName: "embeddings.create",
12588
+ kind: "async"
12589
+ }),
12590
+ betaChatCompletionsParse: channel({
12591
+ channelName: "beta.chat.completions.parse",
12592
+ kind: "async"
12593
+ }),
12594
+ betaChatCompletionsStream: channel({
12595
+ channelName: "beta.chat.completions.stream",
12596
+ kind: "sync-stream"
12597
+ }),
12598
+ moderationsCreate: channel({
12599
+ channelName: "moderations.create",
12600
+ kind: "async"
12601
+ }),
12602
+ responsesCreate: channel({
12603
+ channelName: "responses.create",
12604
+ kind: "async"
12605
+ }),
12606
+ responsesStream: channel({
12607
+ channelName: "responses.stream",
12608
+ kind: "sync-stream"
12609
+ }),
12610
+ responsesParse: channel({
12611
+ channelName: "responses.parse",
12612
+ kind: "async"
12613
+ }),
12614
+ responsesCompact: channel({
12615
+ channelName: "responses.compact",
12616
+ kind: "async"
12617
+ })
12618
+ },
12619
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENAI }
12620
+ );
12480
12621
 
12481
12622
  // src/openai-utils.ts
12482
12623
  var BRAINTRUST_CACHED_STREAM_METRIC = "__braintrust_cached_metric";
@@ -12991,16 +13132,20 @@ function aggregateResponseStreamEvents(chunks, _streamResult, endEvent) {
12991
13132
  }
12992
13133
 
12993
13134
  // src/instrumentation/plugins/openai-codex-channels.ts
12994
- var openAICodexChannels = defineChannels("@openai/codex-sdk", {
12995
- run: channel({
12996
- channelName: "Thread.run",
12997
- kind: "async"
12998
- }),
12999
- runStreamed: channel({
13000
- channelName: "Thread.runStreamed",
13001
- kind: "async"
13002
- })
13003
- });
13135
+ var openAICodexChannels = defineChannels(
13136
+ "@openai/codex-sdk",
13137
+ {
13138
+ run: channel({
13139
+ channelName: "Thread.run",
13140
+ kind: "async"
13141
+ }),
13142
+ runStreamed: channel({
13143
+ channelName: "Thread.runStreamed",
13144
+ kind: "async"
13145
+ })
13146
+ },
13147
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENAI_CODEX }
13148
+ );
13004
13149
 
13005
13150
  // src/instrumentation/plugins/openai-codex-plugin.ts
13006
13151
  var PATCHED_STREAMED_TURN = /* @__PURE__ */ Symbol.for(
@@ -13088,10 +13233,15 @@ function startCodexRun(event, operation) {
13088
13233
  provider: "openai",
13089
13234
  ...event.moduleVersion ? { "openai_codex.version": event.moduleVersion } : {}
13090
13235
  };
13091
- const span = startSpan({
13092
- name: "OpenAI Codex",
13093
- spanAttributes: { type: "task" /* TASK */ }
13094
- });
13236
+ const span = startSpan(
13237
+ withSpanInstrumentationName(
13238
+ {
13239
+ name: "OpenAI Codex",
13240
+ spanAttributes: { type: "task" /* TASK */ }
13241
+ },
13242
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
13243
+ )
13244
+ );
13095
13245
  const startTime = getCurrentUnixTimestamp();
13096
13246
  safeLog(span, {
13097
13247
  input: sanitizedInput,
@@ -13240,7 +13390,12 @@ async function createCompletedItemSpan(state, item) {
13240
13390
  if (!spanArgs) {
13241
13391
  return;
13242
13392
  }
13243
- const span = startSpan(spanArgs.start);
13393
+ const span = startSpan(
13394
+ withSpanInstrumentationName(
13395
+ spanArgs.start,
13396
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
13397
+ )
13398
+ );
13244
13399
  safeLog(span, spanArgs.end);
13245
13400
  span.end();
13246
13401
  }
@@ -13282,15 +13437,20 @@ async function ensureActiveLlmSpan(state) {
13282
13437
  ...state.metadata["openai_codex.thread_id"] ? { "openai_codex.thread_id": state.metadata["openai_codex.thread_id"] } : {},
13283
13438
  "openai_codex.llm_sequence": sequence
13284
13439
  };
13285
- const span = startSpan({
13286
- event: {
13287
- ...sequence === 1 ? { input: state.input } : {},
13288
- metadata
13289
- },
13290
- name: "OpenAI Codex LLM",
13291
- parent: await state.span.export(),
13292
- spanAttributes: { type: "llm" /* LLM */ }
13293
- });
13440
+ const span = startSpan(
13441
+ withSpanInstrumentationName(
13442
+ {
13443
+ event: {
13444
+ ...sequence === 1 ? { input: state.input } : {},
13445
+ metadata
13446
+ },
13447
+ name: "OpenAI Codex LLM",
13448
+ parent: await state.span.export(),
13449
+ spanAttributes: { type: "llm" /* LLM */ }
13450
+ },
13451
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
13452
+ )
13453
+ );
13294
13454
  state.activeLlmSpan = {
13295
13455
  anonymousMessages: [],
13296
13456
  anonymousReasoning: [],
@@ -13336,7 +13496,15 @@ async function startCodexItemSpan(state, item) {
13336
13496
  if (!spanArgs) {
13337
13497
  return;
13338
13498
  }
13339
- state.activeItemSpans.set(itemId, startSpan(spanArgs.start));
13499
+ state.activeItemSpans.set(
13500
+ itemId,
13501
+ startSpan(
13502
+ withSpanInstrumentationName(
13503
+ spanArgs.start,
13504
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
13505
+ )
13506
+ )
13507
+ );
13340
13508
  }
13341
13509
  function updateCodexItem(state, item) {
13342
13510
  if (item.type === "agent_message" && typeof item.text === "string") {
@@ -13646,20 +13814,24 @@ function extractAnthropicCacheTokens(cacheReadTokens = 0, cacheCreationTokens =
13646
13814
  }
13647
13815
 
13648
13816
  // src/instrumentation/plugins/anthropic-channels.ts
13649
- var anthropicChannels = defineChannels("@anthropic-ai/sdk", {
13650
- messagesCreate: channel({
13651
- channelName: "messages.create",
13652
- kind: "async"
13653
- }),
13654
- betaMessagesCreate: channel({
13655
- channelName: "beta.messages.create",
13656
- kind: "async"
13657
- }),
13658
- betaMessagesToolRunner: channel({
13659
- channelName: "beta.messages.toolRunner",
13660
- kind: "sync-stream"
13661
- })
13662
- });
13817
+ var anthropicChannels = defineChannels(
13818
+ "@anthropic-ai/sdk",
13819
+ {
13820
+ messagesCreate: channel({
13821
+ channelName: "messages.create",
13822
+ kind: "async"
13823
+ }),
13824
+ betaMessagesCreate: channel({
13825
+ channelName: "beta.messages.create",
13826
+ kind: "async"
13827
+ }),
13828
+ betaMessagesToolRunner: channel({
13829
+ channelName: "beta.messages.toolRunner",
13830
+ kind: "sync-stream"
13831
+ })
13832
+ },
13833
+ { instrumentationName: INSTRUMENTATION_NAMES.ANTHROPIC }
13834
+ );
13663
13835
 
13664
13836
  // src/instrumentation/plugins/anthropic-plugin.ts
13665
13837
  var ANTHROPIC_TOOL_RUNNER_TOOL_WRAPPED = /* @__PURE__ */ Symbol.for(
@@ -13732,12 +13904,17 @@ var AnthropicPlugin = class extends BasePlugin {
13732
13904
  return;
13733
13905
  }
13734
13906
  const params = event.arguments[0] ?? {};
13735
- const span = startSpan({
13736
- name: "anthropic.beta.messages.toolRunner",
13737
- spanAttributes: {
13738
- type: "task" /* TASK */
13739
- }
13740
- });
13907
+ const span = startSpan(
13908
+ withSpanInstrumentationName(
13909
+ {
13910
+ name: "anthropic.beta.messages.toolRunner",
13911
+ spanAttributes: {
13912
+ type: "task" /* TASK */
13913
+ }
13914
+ },
13915
+ INSTRUMENTATION_NAMES.ANTHROPIC
13916
+ )
13917
+ );
13741
13918
  span.log({
13742
13919
  input: processAttachmentsInInput(
13743
13920
  coalesceInput(params.messages ?? [], params.system)
@@ -13878,19 +14055,22 @@ function wrapAnthropicToolRunnerTool(tool, index, state) {
13878
14055
  return finalizeError(error);
13879
14056
  }
13880
14057
  },
13881
- {
13882
- event: {
13883
- input: getAnthropicToolRunnerInput(args),
13884
- metadata: {
13885
- "gen_ai.tool.name": toolName,
13886
- provider: "anthropic"
14058
+ withSpanInstrumentationName(
14059
+ {
14060
+ event: {
14061
+ input: getAnthropicToolRunnerInput(args),
14062
+ metadata: {
14063
+ "gen_ai.tool.name": toolName,
14064
+ provider: "anthropic"
14065
+ }
14066
+ },
14067
+ name: `tool: ${toolName}`,
14068
+ spanAttributes: {
14069
+ type: "tool" /* TOOL */
13887
14070
  }
13888
14071
  },
13889
- name: `tool: ${toolName}`,
13890
- spanAttributes: {
13891
- type: "tool" /* TOOL */
13892
- }
13893
- }
14072
+ INSTRUMENTATION_NAMES.ANTHROPIC
14073
+ )
13894
14074
  );
13895
14075
  },
13896
14076
  writable: runDescriptor?.writable ?? true
@@ -14485,6 +14665,267 @@ function currentWorkflowAgentWrapperSpan() {
14485
14665
  return void 0;
14486
14666
  }
14487
14667
 
14668
+ // src/wrappers/ai-sdk/harness-agent-context.ts
14669
+ var BRAINTRUST_TURN_CONTEXT_KEY = "__braintrust_trace_context";
14670
+ var sessionTurnParents = /* @__PURE__ */ new WeakMap();
14671
+ var wrapperTurnParents = /* @__PURE__ */ new WeakMap();
14672
+ var patchedLifecycleMethods = /* @__PURE__ */ new WeakMap();
14673
+ var harnessTurnParentStore;
14674
+ function serializedTurnContext(value) {
14675
+ if (!isObject(value)) {
14676
+ return void 0;
14677
+ }
14678
+ const context = value[BRAINTRUST_TURN_CONTEXT_KEY];
14679
+ if (!isObject(context) || typeof context.parent !== "string" || typeof context.sessionId !== "string" || typeof context.signature !== "string") {
14680
+ return void 0;
14681
+ }
14682
+ const expectedSignature = signTurnContext({
14683
+ parent: context.parent,
14684
+ sessionId: context.sessionId
14685
+ });
14686
+ if (!expectedSignature || !isomorph_default.timingSafeEqual?.(context.signature, expectedSignature)) {
14687
+ return void 0;
14688
+ }
14689
+ const parent = SpanComponentsV4.fromStr(context.parent);
14690
+ if (!parent.data.row_id || !parent.data.root_span_id || !parent.data.span_id) {
14691
+ return void 0;
14692
+ }
14693
+ return {
14694
+ parent: context.parent,
14695
+ sessionId: context.sessionId
14696
+ };
14697
+ }
14698
+ function signTurnContext(context) {
14699
+ const secret = _internalGetGlobalState()._internalGetTraceContextSigningSecret();
14700
+ return secret ? isomorph_default.hmacSha256?.(
14701
+ secret,
14702
+ JSON.stringify([BRAINTRUST_TURN_CONTEXT_KEY, context])
14703
+ ) : void 0;
14704
+ }
14705
+ function continuationParentFromCreateSessionParams(params) {
14706
+ if (!isObject(params)) {
14707
+ return void 0;
14708
+ }
14709
+ const continuation = params.continueFrom ?? (isObject(params.resumeFrom) ? params.resumeFrom.continueFrom : void 0);
14710
+ const context = serializedTurnContext(continuation);
14711
+ if (!context) {
14712
+ return void 0;
14713
+ }
14714
+ if (params.sessionId !== context.sessionId) {
14715
+ return void 0;
14716
+ }
14717
+ return context.parent;
14718
+ }
14719
+ function exportSpanSynchronously(span) {
14720
+ const parentInfo = span.getParentInfo();
14721
+ if (!parentInfo) {
14722
+ return void 0;
14723
+ }
14724
+ const objectId = parentInfo.objectId.getSync().value;
14725
+ if (!objectId && !parentInfo.computeObjectMetadataArgs) {
14726
+ return void 0;
14727
+ }
14728
+ return new SpanComponentsV4({
14729
+ object_type: parentInfo.objectType,
14730
+ ...objectId ? { object_id: objectId } : {
14731
+ compute_object_metadata_args: parentInfo.computeObjectMetadataArgs ?? {}
14732
+ },
14733
+ row_id: span.id,
14734
+ root_span_id: span.rootSpanId,
14735
+ span_id: span.spanId
14736
+ }).toStr();
14737
+ }
14738
+ function exportedParent(parent) {
14739
+ return typeof parent === "string" ? parent : exportSpanSynchronously(parent);
14740
+ }
14741
+ function addSerializedContext(args) {
14742
+ if (!isObject(args.continuation) || args.sessionId === void 0) {
14743
+ return;
14744
+ }
14745
+ const parent = exportedParent(args.parent);
14746
+ if (!parent) {
14747
+ return;
14748
+ }
14749
+ const context = {
14750
+ parent,
14751
+ sessionId: args.sessionId
14752
+ };
14753
+ const signature = signTurnContext(context);
14754
+ if (!signature) {
14755
+ return;
14756
+ }
14757
+ Object.defineProperty(args.continuation, BRAINTRUST_TURN_CONTEXT_KEY, {
14758
+ configurable: true,
14759
+ enumerable: true,
14760
+ value: {
14761
+ ...context,
14762
+ signature
14763
+ },
14764
+ writable: true
14765
+ });
14766
+ }
14767
+ function lifecycleMethodDescriptor(session, method) {
14768
+ let owner = session;
14769
+ while (owner) {
14770
+ const descriptor = Object.getOwnPropertyDescriptor(owner, method);
14771
+ if (descriptor) {
14772
+ return { descriptor, owner };
14773
+ }
14774
+ owner = Object.getPrototypeOf(owner);
14775
+ }
14776
+ return void 0;
14777
+ }
14778
+ function patchLifecycleMethod(session, method) {
14779
+ let resolvedDescriptor;
14780
+ try {
14781
+ resolvedDescriptor = lifecycleMethodDescriptor(session, method);
14782
+ } catch {
14783
+ return;
14784
+ }
14785
+ if (!resolvedDescriptor || !("value" in resolvedDescriptor.descriptor) || typeof resolvedDescriptor.descriptor.value !== "function") {
14786
+ return;
14787
+ }
14788
+ const { descriptor, owner } = resolvedDescriptor;
14789
+ const patched = patchedLifecycleMethods.get(owner);
14790
+ if (patched?.has(method)) {
14791
+ return;
14792
+ }
14793
+ const original = descriptor.value;
14794
+ const replacement = function(...args) {
14795
+ const result = Reflect.apply(original, this, args);
14796
+ const addContext = (state) => {
14797
+ try {
14798
+ const parent = sessionTurnParents.get(this);
14799
+ if (!parent) {
14800
+ return;
14801
+ }
14802
+ const continuation = method === "suspendTurn" ? state : isObject(state) ? state.continueFrom : void 0;
14803
+ addSerializedContext({
14804
+ continuation,
14805
+ parent,
14806
+ sessionId: typeof this.sessionId === "string" ? this.sessionId : void 0
14807
+ });
14808
+ } catch {
14809
+ }
14810
+ };
14811
+ try {
14812
+ if (isObject(result) && typeof result.then === "function") {
14813
+ void Promise.resolve(result).then(addContext, () => {
14814
+ });
14815
+ } else {
14816
+ addContext(result);
14817
+ }
14818
+ } catch {
14819
+ }
14820
+ return result;
14821
+ };
14822
+ try {
14823
+ Object.defineProperty(owner, method, {
14824
+ ...descriptor,
14825
+ value: replacement
14826
+ });
14827
+ const ownerMethods = patched ?? /* @__PURE__ */ new Set();
14828
+ ownerMethods.add(method);
14829
+ if (!patched) {
14830
+ patchedLifecycleMethods.set(owner, ownerMethods);
14831
+ }
14832
+ } catch {
14833
+ }
14834
+ }
14835
+ function patchLifecycleMethods(session) {
14836
+ patchLifecycleMethod(session, "suspendTurn");
14837
+ patchLifecycleMethod(session, "detach");
14838
+ patchLifecycleMethod(session, "stop");
14839
+ }
14840
+ function registerHarnessTurnSpan(args) {
14841
+ if (!isObject(args.session)) {
14842
+ return;
14843
+ }
14844
+ const session = args.session;
14845
+ sessionTurnParents.set(session, args.span);
14846
+ wrapperTurnParents.set(args.span, args.span);
14847
+ patchLifecycleMethods(session);
14848
+ }
14849
+ function harnessContinuationParent(session) {
14850
+ return isObject(session) ? sessionTurnParents.get(session) : void 0;
14851
+ }
14852
+ function captureHarnessCreateSessionParent(params) {
14853
+ try {
14854
+ return continuationParentFromCreateSessionParams(params);
14855
+ } catch {
14856
+ return void 0;
14857
+ }
14858
+ }
14859
+ function registerHarnessSessionParent(session, parent) {
14860
+ if (!parent || !isObject(session)) {
14861
+ return;
14862
+ }
14863
+ const harnessSession = session;
14864
+ sessionTurnParents.set(harnessSession, parent);
14865
+ patchLifecycleMethods(harnessSession);
14866
+ }
14867
+ function currentHarnessTurnParent() {
14868
+ return harnessTurnParentStore?.getStore() ?? wrapperTurnParents.get(currentSpan());
14869
+ }
14870
+ function bindHarnessTurnParentToStart(tracingChannel2, parentFromEvent) {
14871
+ const startChannel = tracingChannel2.start;
14872
+ if (!startChannel) {
14873
+ return () => {
14874
+ };
14875
+ }
14876
+ harnessTurnParentStore ??= isomorph_default.newAsyncLocalStorage();
14877
+ const store = harnessTurnParentStore;
14878
+ startChannel.bindStore(
14879
+ store,
14880
+ (event) => parentFromEvent(event) ?? store.getStore()
14881
+ );
14882
+ return () => {
14883
+ startChannel.unbindStore(store);
14884
+ };
14885
+ }
14886
+ function startHarnessTurnChildSpan(parent, args) {
14887
+ const spanArgs = withSpanInstrumentationName(
14888
+ args,
14889
+ INSTRUMENTATION_NAMES.AI_SDK
14890
+ );
14891
+ return typeof parent === "string" ? startSpan({ ...spanArgs, parent }) : parent.startSpan(spanArgs);
14892
+ }
14893
+ function updateHarnessTurn(parent, update = {}) {
14894
+ if (!parent) {
14895
+ return;
14896
+ }
14897
+ const log3 = (event) => {
14898
+ if (typeof parent === "string") {
14899
+ updateSpan({ exported: parent, ...event });
14900
+ } else {
14901
+ parent.log(event);
14902
+ }
14903
+ };
14904
+ try {
14905
+ if (Object.prototype.hasOwnProperty.call(update, "output")) {
14906
+ log3({ output: null });
14907
+ }
14908
+ log3(update);
14909
+ } catch {
14910
+ }
14911
+ }
14912
+ function endHarnessTurn(parent) {
14913
+ const endTime = getCurrentUnixTimestamp();
14914
+ if (!parent) {
14915
+ return endTime;
14916
+ }
14917
+ try {
14918
+ const event = { metrics: { end: endTime } };
14919
+ if (typeof parent === "string") {
14920
+ updateSpan({ exported: parent, ...event });
14921
+ } else {
14922
+ parent.log(event);
14923
+ }
14924
+ } catch {
14925
+ }
14926
+ return endTime;
14927
+ }
14928
+
14488
14929
  // src/wrappers/ai-sdk/telemetry.ts
14489
14930
  function braintrustAISDKTelemetry() {
14490
14931
  const operations = /* @__PURE__ */ new Map();
@@ -14503,14 +14944,17 @@ function braintrustAISDKTelemetry() {
14503
14944
  console.error(`Error in Braintrust AI SDK telemetry ${name}:`, error);
14504
14945
  }
14505
14946
  };
14506
- const startChildSpan = (operationKey, name, type, event) => {
14947
+ const startChildSpan = (operationKey, name, type, event, parentOverride) => {
14507
14948
  const parent = operations.get(operationKey)?.span;
14508
- const spanArgs = {
14509
- name,
14510
- spanAttributes: { type },
14511
- ...event ? { event } : {}
14512
- };
14513
- const span = parent ? parent.startSpan(spanArgs) : startSpan(spanArgs);
14949
+ const spanArgs = withSpanInstrumentationName(
14950
+ {
14951
+ name,
14952
+ spanAttributes: { type },
14953
+ ...event ? { event } : {}
14954
+ },
14955
+ INSTRUMENTATION_NAMES.AI_SDK
14956
+ );
14957
+ const span = parentOverride ? startHarnessTurnChildSpan(parentOverride, spanArgs) : parent ? parent.startSpan(spanArgs) : startSpan(spanArgs);
14514
14958
  const state = operations.get(operationKey);
14515
14959
  if (state && type === "llm" /* LLM */) {
14516
14960
  state.hadModelChild = true;
@@ -14790,14 +15234,30 @@ function braintrustAISDKTelemetry() {
14790
15234
  const workflowAgent = operationName === "WorkflowAgent.stream";
14791
15235
  const wrapperSpan = workflowAgent ? currentWorkflowAgentWrapperSpan() : void 0;
14792
15236
  const ownsSpan = !wrapperSpan;
14793
- const span = ownsSpan ? startSpan({
14794
- name: operationName,
14795
- spanAttributes: { type: "function" /* FUNCTION */ }
14796
- }) : wrapperSpan;
15237
+ const harnessTurnParent = currentHarnessTurnParent();
15238
+ const span = ownsSpan ? harnessTurnParent ? startHarnessTurnChildSpan(
15239
+ harnessTurnParent,
15240
+ withSpanInstrumentationName(
15241
+ {
15242
+ name: operationName,
15243
+ spanAttributes: { type: "function" /* FUNCTION */ }
15244
+ },
15245
+ INSTRUMENTATION_NAMES.AI_SDK
15246
+ )
15247
+ ) : startSpan(
15248
+ withSpanInstrumentationName(
15249
+ {
15250
+ name: operationName,
15251
+ spanAttributes: { type: "function" /* FUNCTION */ }
15252
+ },
15253
+ INSTRUMENTATION_NAMES.AI_SDK
15254
+ )
15255
+ ) : wrapperSpan;
14797
15256
  const operationKey = createOperationKey(event, operationName);
14798
15257
  registerOperation({
14799
15258
  callId: event.callId,
14800
15259
  hadModelChild: false,
15260
+ harnessTurnParent,
14801
15261
  loggedInput: false,
14802
15262
  operationName,
14803
15263
  operationKey,
@@ -15038,7 +15498,8 @@ function braintrustAISDKTelemetry() {
15038
15498
  toolCallId,
15039
15499
  ...typeof event.toolCall.toolName === "string" ? { toolName: event.toolCall.toolName } : {}
15040
15500
  }
15041
- }
15501
+ },
15502
+ state?.harnessTurnParent
15042
15503
  );
15043
15504
  toolSpans.set(toolCallId, { operationKey, span });
15044
15505
  });
@@ -15274,92 +15735,102 @@ function finishOutput(result, operationName) {
15274
15735
  }
15275
15736
 
15276
15737
  // src/instrumentation/plugins/ai-sdk-channels.ts
15277
- var aiSDKChannels = defineChannels("ai", {
15278
- generateText: channel({
15279
- channelName: "generateText",
15280
- kind: "async"
15281
- }),
15282
- streamText: channel({
15283
- channelName: "streamText",
15284
- kind: "async"
15285
- }),
15286
- streamTextSync: channel({
15287
- channelName: "streamText.sync",
15288
- kind: "sync-stream"
15289
- }),
15290
- generateObject: channel({
15291
- channelName: "generateObject",
15292
- kind: "async"
15293
- }),
15294
- streamObject: channel({
15295
- channelName: "streamObject",
15296
- kind: "async"
15297
- }),
15298
- streamObjectSync: channel({
15299
- channelName: "streamObject.sync",
15300
- kind: "sync-stream"
15301
- }),
15302
- embed: channel(
15303
- {
15738
+ var aiSDKChannels = defineChannels(
15739
+ "ai",
15740
+ {
15741
+ generateText: channel({
15742
+ channelName: "generateText",
15743
+ kind: "async"
15744
+ }),
15745
+ streamText: channel({
15746
+ channelName: "streamText",
15747
+ kind: "async"
15748
+ }),
15749
+ streamTextSync: channel({
15750
+ channelName: "streamText.sync",
15751
+ kind: "sync-stream"
15752
+ }),
15753
+ generateObject: channel({
15754
+ channelName: "generateObject",
15755
+ kind: "async"
15756
+ }),
15757
+ streamObject: channel({
15758
+ channelName: "streamObject",
15759
+ kind: "async"
15760
+ }),
15761
+ streamObjectSync: channel({
15762
+ channelName: "streamObject.sync",
15763
+ kind: "sync-stream"
15764
+ }),
15765
+ embed: channel({
15304
15766
  channelName: "embed",
15305
15767
  kind: "async"
15306
- }
15307
- ),
15308
- embedMany: channel({
15309
- channelName: "embedMany",
15310
- kind: "async"
15311
- }),
15312
- rerank: channel({
15313
- channelName: "rerank",
15314
- kind: "async"
15315
- }),
15316
- agentGenerate: channel({
15317
- channelName: "Agent.generate",
15318
- kind: "async"
15319
- }),
15320
- agentStream: channel({
15321
- channelName: "Agent.stream",
15322
- kind: "async"
15323
- }),
15324
- agentStreamSync: channel({
15325
- channelName: "Agent.stream.sync",
15326
- kind: "sync-stream"
15327
- }),
15328
- toolLoopAgentGenerate: channel({
15329
- channelName: "ToolLoopAgent.generate",
15330
- kind: "async"
15331
- }),
15332
- toolLoopAgentStream: channel({
15333
- channelName: "ToolLoopAgent.stream",
15334
- kind: "async"
15335
- }),
15336
- workflowAgentStream: channel({
15337
- channelName: "WorkflowAgent.stream",
15338
- kind: "async"
15339
- }),
15340
- v7CreateTelemetryDispatcher: channel({
15341
- channelName: "createTelemetryDispatcher",
15342
- kind: "sync-stream"
15343
- })
15344
- });
15345
- var harnessAgentChannels = defineChannels("@ai-sdk/harness", {
15346
- generate: channel({
15347
- channelName: "HarnessAgent.generate",
15348
- kind: "async"
15349
- }),
15350
- stream: channel({
15351
- channelName: "HarnessAgent.stream",
15352
- kind: "async"
15353
- }),
15354
- continueGenerate: channel({
15355
- channelName: "HarnessAgent.continueGenerate",
15356
- kind: "async"
15357
- }),
15358
- continueStream: channel({
15359
- channelName: "HarnessAgent.continueStream",
15360
- kind: "async"
15361
- })
15362
- });
15768
+ }),
15769
+ embedMany: channel({
15770
+ channelName: "embedMany",
15771
+ kind: "async"
15772
+ }),
15773
+ rerank: channel({
15774
+ channelName: "rerank",
15775
+ kind: "async"
15776
+ }),
15777
+ agentGenerate: channel({
15778
+ channelName: "Agent.generate",
15779
+ kind: "async"
15780
+ }),
15781
+ agentStream: channel({
15782
+ channelName: "Agent.stream",
15783
+ kind: "async"
15784
+ }),
15785
+ agentStreamSync: channel({
15786
+ channelName: "Agent.stream.sync",
15787
+ kind: "sync-stream"
15788
+ }),
15789
+ toolLoopAgentGenerate: channel({
15790
+ channelName: "ToolLoopAgent.generate",
15791
+ kind: "async"
15792
+ }),
15793
+ toolLoopAgentStream: channel({
15794
+ channelName: "ToolLoopAgent.stream",
15795
+ kind: "async"
15796
+ }),
15797
+ workflowAgentStream: channel({
15798
+ channelName: "WorkflowAgent.stream",
15799
+ kind: "async"
15800
+ }),
15801
+ v7CreateTelemetryDispatcher: channel({
15802
+ channelName: "createTelemetryDispatcher",
15803
+ kind: "sync-stream"
15804
+ })
15805
+ },
15806
+ { instrumentationName: INSTRUMENTATION_NAMES.AI_SDK }
15807
+ );
15808
+ var harnessAgentChannels = defineChannels(
15809
+ "@ai-sdk/harness",
15810
+ {
15811
+ createSession: channel({
15812
+ channelName: "HarnessAgent.createSession",
15813
+ kind: "async"
15814
+ }),
15815
+ generate: channel({
15816
+ channelName: "HarnessAgent.generate",
15817
+ kind: "async"
15818
+ }),
15819
+ stream: channel({
15820
+ channelName: "HarnessAgent.stream",
15821
+ kind: "async"
15822
+ }),
15823
+ continueGenerate: channel({
15824
+ channelName: "HarnessAgent.continueGenerate",
15825
+ kind: "async"
15826
+ }),
15827
+ continueStream: channel({
15828
+ channelName: "HarnessAgent.continueStream",
15829
+ kind: "async"
15830
+ })
15831
+ },
15832
+ { instrumentationName: INSTRUMENTATION_NAMES.AI_SDK }
15833
+ );
15363
15834
 
15364
15835
  // src/instrumentation/plugins/ai-sdk-plugin.ts
15365
15836
  var DEFAULT_DENY_OUTPUT_PATHS = [
@@ -15436,6 +15907,17 @@ var AISDKPlugin = class extends BasePlugin {
15436
15907
  subscribeToAISDK() {
15437
15908
  const denyOutputPaths = this.config.denyOutputPaths || DEFAULT_DENY_OUTPUT_PATHS;
15438
15909
  this.unsubscribers.push(subscribeToAISDKV7TelemetryDispatcher());
15910
+ this.unsubscribers.push(subscribeToHarnessAgentCreateSession());
15911
+ this.unsubscribers.push(
15912
+ subscribeToHarnessContinuation(
15913
+ harnessAgentChannels.continueGenerate,
15914
+ denyOutputPaths
15915
+ ),
15916
+ subscribeToHarnessContinuation(
15917
+ harnessAgentChannels.continueStream,
15918
+ denyOutputPaths
15919
+ )
15920
+ );
15439
15921
  this.unsubscribers.push(
15440
15922
  traceStreamingChannel(aiSDKChannels.generateText, {
15441
15923
  name: "generateText",
@@ -15631,8 +16113,9 @@ var AISDKPlugin = class extends BasePlugin {
15631
16113
  this.unsubscribers.push(
15632
16114
  traceStreamingChannel(harnessAgentChannels.generate, {
15633
16115
  name: "HarnessAgent.generate",
16116
+ startSpan: _internalStartSpanWithInitialMerge,
15634
16117
  type: "task" /* TASK */,
15635
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
16118
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
15636
16119
  extractOutput: (result, endEvent) => processAISDKOutput(
15637
16120
  result,
15638
16121
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -15644,8 +16127,9 @@ var AISDKPlugin = class extends BasePlugin {
15644
16127
  this.unsubscribers.push(
15645
16128
  traceStreamingChannel(harnessAgentChannels.stream, {
15646
16129
  name: "HarnessAgent.stream",
16130
+ startSpan: _internalStartSpanWithInitialMerge,
15647
16131
  type: "task" /* TASK */,
15648
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
16132
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
15649
16133
  extractOutput: (result, endEvent) => processAISDKOutput(
15650
16134
  result,
15651
16135
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -15670,8 +16154,10 @@ var AISDKPlugin = class extends BasePlugin {
15670
16154
  this.unsubscribers.push(
15671
16155
  traceStreamingChannel(harnessAgentChannels.continueGenerate, {
15672
16156
  name: "HarnessAgent.continueGenerate",
16157
+ shouldTrace: (args) => !harnessContinuationParent(harnessSessionFromArguments(args)),
16158
+ startSpan: _internalStartSpanWithInitialMerge,
15673
16159
  type: "task" /* TASK */,
15674
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
16160
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
15675
16161
  extractOutput: (result, endEvent) => processAISDKOutput(
15676
16162
  result,
15677
16163
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -15683,8 +16169,10 @@ var AISDKPlugin = class extends BasePlugin {
15683
16169
  this.unsubscribers.push(
15684
16170
  traceStreamingChannel(harnessAgentChannels.continueStream, {
15685
16171
  name: "HarnessAgent.continueStream",
16172
+ shouldTrace: (args) => !harnessContinuationParent(harnessSessionFromArguments(args)),
16173
+ startSpan: _internalStartSpanWithInitialMerge,
15686
16174
  type: "task" /* TASK */,
15687
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
16175
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
15688
16176
  extractOutput: (result, endEvent) => processAISDKOutput(
15689
16177
  result,
15690
16178
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -15776,6 +16264,8 @@ var AISDKPlugin = class extends BasePlugin {
15776
16264
  defaultDenyOutputPaths: denyOutputPaths,
15777
16265
  endEvent,
15778
16266
  onComplete: () => unregisterWorkflowAgentWrapperSpan(span),
16267
+ onCancel: () => unregisterWorkflowAgentWrapperSpan(span),
16268
+ onError: () => unregisterWorkflowAgentWrapperSpan(span),
15779
16269
  result,
15780
16270
  span,
15781
16271
  startTime
@@ -15784,6 +16274,153 @@ var AISDKPlugin = class extends BasePlugin {
15784
16274
  );
15785
16275
  }
15786
16276
  };
16277
+ function subscribeToHarnessAgentCreateSession() {
16278
+ const channel2 = harnessAgentChannels.createSession.tracingChannel();
16279
+ const parents = /* @__PURE__ */ new WeakMap();
16280
+ const handlers = {
16281
+ start: (event) => {
16282
+ const parent = captureHarnessCreateSessionParent(event.arguments?.[0]);
16283
+ if (parent) {
16284
+ parents.set(event, parent);
16285
+ }
16286
+ },
16287
+ asyncEnd: (event) => {
16288
+ registerHarnessSessionParent(event.result, parents.get(event));
16289
+ parents.delete(event);
16290
+ },
16291
+ error: (event) => {
16292
+ parents.delete(event);
16293
+ }
16294
+ };
16295
+ channel2.subscribe(handlers);
16296
+ return () => channel2.unsubscribe(handlers);
16297
+ }
16298
+ function harnessContinuationParentFromEvent(event) {
16299
+ try {
16300
+ return harnessContinuationParent(event.arguments?.[0]?.session);
16301
+ } catch {
16302
+ return void 0;
16303
+ }
16304
+ }
16305
+ function subscribeToHarnessContinuation(continuationChannel, defaultDenyOutputPaths) {
16306
+ const channel2 = continuationChannel.tracingChannel();
16307
+ const parents = /* @__PURE__ */ new WeakMap();
16308
+ const startTimes = /* @__PURE__ */ new WeakMap();
16309
+ const unbindParentStore = bindHarnessTurnParentToStart(
16310
+ channel2,
16311
+ harnessContinuationParentFromEvent
16312
+ );
16313
+ const handlers = {
16314
+ start: (event) => {
16315
+ const parent = harnessContinuationParentFromEvent(event);
16316
+ if (!parent) {
16317
+ return;
16318
+ }
16319
+ parents.set(event, parent);
16320
+ startTimes.set(event, getCurrentUnixTimestamp());
16321
+ try {
16322
+ const params = event.arguments?.[0];
16323
+ if (params) {
16324
+ prepareAISDKHarnessAgentInput(params, event.self);
16325
+ }
16326
+ } catch (error) {
16327
+ debugLogger.error(
16328
+ "Error preparing Harness continuation telemetry:",
16329
+ error
16330
+ );
16331
+ }
16332
+ },
16333
+ asyncEnd: (event) => {
16334
+ const parent = parents.get(event);
16335
+ const startTime = startTimes.get(event) ?? getCurrentUnixTimestamp();
16336
+ parents.delete(event);
16337
+ startTimes.delete(event);
16338
+ if (!parent) {
16339
+ return;
16340
+ }
16341
+ const endEvent = event;
16342
+ const span = {
16343
+ end: () => endHarnessTurn(parent),
16344
+ log: (update) => updateHarnessTurn(
16345
+ parent,
16346
+ Object.prototype.hasOwnProperty.call(update, "error") && !Object.prototype.hasOwnProperty.call(update, "output") ? { ...update, output: null } : update
16347
+ )
16348
+ };
16349
+ try {
16350
+ if (isAsyncIterable(endEvent.result)) {
16351
+ patchStreamIfNeeded(endEvent.result, {
16352
+ onComplete: (chunks) => {
16353
+ try {
16354
+ const { metadata, metrics, output } = aggregateAISDKChunks(
16355
+ chunks,
16356
+ endEvent.result,
16357
+ endEvent
16358
+ );
16359
+ span.log({
16360
+ ...metadata ? { metadata } : {},
16361
+ metrics,
16362
+ output
16363
+ });
16364
+ } catch (error) {
16365
+ debugLogger.error(
16366
+ "Error aggregating Harness continuation stream:",
16367
+ error
16368
+ );
16369
+ } finally {
16370
+ span.end();
16371
+ }
16372
+ },
16373
+ onError: (error) => {
16374
+ span.log({ error: toLoggedError(error), output: null });
16375
+ span.end();
16376
+ }
16377
+ });
16378
+ return;
16379
+ }
16380
+ if (patchAISDKStreamingResult({
16381
+ defaultDenyOutputPaths,
16382
+ endEvent,
16383
+ result: endEvent.result,
16384
+ resolvePromiseUsage: true,
16385
+ span,
16386
+ startTime
16387
+ })) {
16388
+ return;
16389
+ }
16390
+ finalizeAISDKChildTracing(endEvent);
16391
+ span.log({
16392
+ metrics: extractTokenMetrics(endEvent.result),
16393
+ output: processAISDKOutput(
16394
+ endEvent.result,
16395
+ resolveDenyOutputPaths(endEvent, defaultDenyOutputPaths)
16396
+ )
16397
+ });
16398
+ span.end();
16399
+ } catch (error) {
16400
+ debugLogger.error("Error tracing Harness continuation:", error);
16401
+ span.end();
16402
+ }
16403
+ },
16404
+ error: (event) => {
16405
+ const parent = parents.get(event);
16406
+ parents.delete(event);
16407
+ startTimes.delete(event);
16408
+ if (!parent) {
16409
+ return;
16410
+ }
16411
+ updateHarnessTurn(parent, {
16412
+ error: toLoggedError(event.error),
16413
+ output: null
16414
+ });
16415
+ endHarnessTurn(parent);
16416
+ }
16417
+ };
16418
+ channel2.subscribe(handlers);
16419
+ return () => {
16420
+ unbindParentStore();
16421
+ channel2.unsubscribe(handlers);
16422
+ };
16423
+ }
15787
16424
  function subscribeToAISDKV7TelemetryDispatcher() {
15788
16425
  const channel2 = aiSDKChannels.v7CreateTelemetryDispatcher.tracingChannel();
15789
16426
  const telemetry = braintrustAISDKTelemetry();
@@ -16236,7 +16873,13 @@ function prepareAISDKCallInput(params, event, span, defaultDenyOutputPaths, chil
16236
16873
  metadata
16237
16874
  };
16238
16875
  }
16239
- function prepareAISDKHarnessAgentInput(params, self) {
16876
+ function prepareAISDKHarnessAgentInput(params, self, span) {
16877
+ if (span) {
16878
+ registerHarnessTurnSpan({
16879
+ session: params.session,
16880
+ span
16881
+ });
16882
+ }
16240
16883
  if (isObject(self)) {
16241
16884
  try {
16242
16885
  if (isObject(self.settings)) {
@@ -16275,6 +16918,10 @@ function prepareAISDKHarnessAgentInput(params, self) {
16275
16918
  metadata
16276
16919
  };
16277
16920
  }
16921
+ function harnessSessionFromArguments(args) {
16922
+ const params = args[0];
16923
+ return isObject(params) ? params.session : void 0;
16924
+ }
16278
16925
  function prepareAISDKWorkflowAgentStreamInput(params, event, span, defaultDenyOutputPaths) {
16279
16926
  registerWorkflowAgentWrapperSpan(span);
16280
16927
  const { input } = processAISDKWorkflowAgentCallInput(params);
@@ -16722,19 +17369,22 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
16722
17369
  activeEntry.openSpans.delete(span);
16723
17370
  }
16724
17371
  },
16725
- {
16726
- name: "doGenerate",
16727
- spanAttributes: {
16728
- type: "llm" /* LLM */
17372
+ withSpanInstrumentationName(
17373
+ {
17374
+ name: "doGenerate",
17375
+ spanAttributes: {
17376
+ type: "llm" /* LLM */
17377
+ },
17378
+ event: buildAISDKModelStartEvent(
17379
+ callOptions,
17380
+ activeEntry.baseMetadata,
17381
+ {
17382
+ workflowAgent: activeEntry.childTracingOptions.workflowAgent
17383
+ }
17384
+ )
16729
17385
  },
16730
- event: buildAISDKModelStartEvent(
16731
- callOptions,
16732
- activeEntry.baseMetadata,
16733
- {
16734
- workflowAgent: activeEntry.childTracingOptions.workflowAgent
16735
- }
16736
- )
16737
- }
17386
+ INSTRUMENTATION_NAMES.AI_SDK
17387
+ )
16738
17388
  );
16739
17389
  };
16740
17390
  if (originalDoStream) {
@@ -16744,19 +17394,24 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
16744
17394
  return Reflect.apply(originalDoStream, resolvedModel, [callOptions]);
16745
17395
  }
16746
17396
  closeOpenAISDKModelPatchSpans(activeEntry);
16747
- const span = activeEntry.parentSpan.startSpan({
16748
- name: "doStream",
16749
- spanAttributes: {
16750
- type: "llm" /* LLM */
16751
- },
16752
- event: buildAISDKModelStartEvent(
16753
- callOptions,
16754
- activeEntry.baseMetadata,
17397
+ const span = activeEntry.parentSpan.startSpan(
17398
+ withSpanInstrumentationName(
16755
17399
  {
16756
- workflowAgent: activeEntry.childTracingOptions.workflowAgent
16757
- }
17400
+ name: "doStream",
17401
+ spanAttributes: {
17402
+ type: "llm" /* LLM */
17403
+ },
17404
+ event: buildAISDKModelStartEvent(
17405
+ callOptions,
17406
+ activeEntry.baseMetadata,
17407
+ {
17408
+ workflowAgent: activeEntry.childTracingOptions.workflowAgent
17409
+ }
17410
+ )
17411
+ },
17412
+ INSTRUMENTATION_NAMES.AI_SDK
16758
17413
  )
16759
- });
17414
+ );
16760
17415
  activeEntry.openSpans.add(span);
16761
17416
  const streamStartTime = getCurrentUnixTimestamp();
16762
17417
  const result = await withCurrent(
@@ -16928,12 +17583,17 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
16928
17583
  }
16929
17584
  if (isAsyncGenerator(result)) {
16930
17585
  return (async function* () {
16931
- const span = activeEntry.parentSpan.startSpan({
16932
- name: activeEntry.name,
16933
- spanAttributes: {
16934
- type: "tool" /* TOOL */
16935
- }
16936
- });
17586
+ const span = activeEntry.parentSpan.startSpan(
17587
+ withSpanInstrumentationName(
17588
+ {
17589
+ name: activeEntry.name,
17590
+ spanAttributes: {
17591
+ type: "tool" /* TOOL */
17592
+ }
17593
+ },
17594
+ INSTRUMENTATION_NAMES.AI_SDK
17595
+ )
17596
+ );
16937
17597
  span.log({ input: serializeToolExecutionInput(args) });
16938
17598
  try {
16939
17599
  let lastValue;
@@ -16957,12 +17617,15 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
16957
17617
  span.log({ output: awaitedResult });
16958
17618
  return awaitedResult;
16959
17619
  },
16960
- {
16961
- name: activeEntry.name,
16962
- spanAttributes: {
16963
- type: "tool" /* TOOL */
16964
- }
16965
- }
17620
+ withSpanInstrumentationName(
17621
+ {
17622
+ name: activeEntry.name,
17623
+ spanAttributes: {
17624
+ type: "tool" /* TOOL */
17625
+ }
17626
+ },
17627
+ INSTRUMENTATION_NAMES.AI_SDK
17628
+ )
16966
17629
  );
16967
17630
  };
16968
17631
  cleanup.push(() => {
@@ -17121,6 +17784,8 @@ function patchAISDKStreamingResult(args) {
17121
17784
  defaultDenyOutputPaths,
17122
17785
  endEvent,
17123
17786
  onComplete,
17787
+ onCancel,
17788
+ onError,
17124
17789
  result,
17125
17790
  resolvePromiseUsage,
17126
17791
  span,
@@ -17132,14 +17797,43 @@ function patchAISDKStreamingResult(args) {
17132
17797
  const resultRecord = result;
17133
17798
  attachKnownResultPromiseHandlers(resultRecord);
17134
17799
  let finalized = false;
17135
- const finalize = () => {
17800
+ const finalize = (outcome) => {
17136
17801
  if (finalized) {
17137
17802
  return;
17138
17803
  }
17139
17804
  finalized = true;
17140
- finalizeAISDKChildTracing(endEvent);
17141
- span.end();
17142
- onComplete?.();
17805
+ try {
17806
+ finalizeAISDKChildTracing(endEvent);
17807
+ } catch (error) {
17808
+ debugLogger.error("Error finalizing AI SDK child tracing:", error);
17809
+ }
17810
+ try {
17811
+ span.end();
17812
+ } catch (error) {
17813
+ debugLogger.error("Error ending AI SDK streaming span:", error);
17814
+ }
17815
+ if (outcome && "error" in outcome) {
17816
+ try {
17817
+ onError?.(outcome.error);
17818
+ } catch (error) {
17819
+ debugLogger.error("Error in AI SDK streaming error hook:", error);
17820
+ }
17821
+ } else if (outcome) {
17822
+ try {
17823
+ onComplete?.(outcome);
17824
+ } catch (error) {
17825
+ debugLogger.error("Error in AI SDK streaming completion hook:", error);
17826
+ }
17827
+ } else {
17828
+ try {
17829
+ onCancel?.();
17830
+ } catch (error) {
17831
+ debugLogger.error(
17832
+ "Error in AI SDK streaming cancellation hook:",
17833
+ error
17834
+ );
17835
+ }
17836
+ }
17143
17837
  };
17144
17838
  let outputLogged = false;
17145
17839
  const logStreamingOutput = async (firstChunkTime) => {
@@ -17173,15 +17867,29 @@ function patchAISDKStreamingResult(args) {
17173
17867
  resolveDenyOutputPaths(endEvent, defaultDenyOutputPaths)
17174
17868
  );
17175
17869
  const metadata = buildResolvedMetadataPayload(result).metadata;
17176
- span.log({
17177
- output,
17178
- ...metadata ? { metadata } : {},
17179
- metrics
17180
- });
17870
+ try {
17871
+ span.log({
17872
+ output,
17873
+ ...metadata ? { metadata } : {},
17874
+ metrics
17875
+ });
17876
+ } catch (error) {
17877
+ debugLogger.error("Error logging AI SDK streaming output:", error);
17878
+ }
17879
+ finalize({ metrics, output });
17181
17880
  } catch (error) {
17182
- span.log({ error: toLoggedError(error) });
17183
- } finally {
17184
- finalize();
17881
+ const loggedError = toLoggedError(error);
17882
+ try {
17883
+ span.log({ error: loggedError });
17884
+ } catch (loggingError) {
17885
+ debugLogger.error(
17886
+ "Error logging AI SDK streaming failure:",
17887
+ loggingError
17888
+ );
17889
+ }
17890
+ finalize({
17891
+ error: error instanceof Error ? error : new Error(String(loggedError))
17892
+ });
17185
17893
  }
17186
17894
  };
17187
17895
  const createAsyncIterableHooks = () => {
@@ -17198,11 +17906,16 @@ function patchAISDKStreamingResult(args) {
17198
17906
  onError: (error) => {
17199
17907
  if (!outputLogged) {
17200
17908
  outputLogged = true;
17201
- span.log({
17202
- error: error.message
17203
- });
17909
+ try {
17910
+ span.log({ error });
17911
+ } catch (loggingError) {
17912
+ debugLogger.error(
17913
+ "Error logging AI SDK stream failure:",
17914
+ loggingError
17915
+ );
17916
+ }
17204
17917
  }
17205
- finalize();
17918
+ finalize({ error });
17206
17919
  },
17207
17920
  onCancel: finalize
17208
17921
  };
@@ -17288,8 +18001,18 @@ function patchAISDKStreamingResult(args) {
17288
18001
  }
17289
18002
  controller.enqueue(value);
17290
18003
  } catch (error) {
17291
- span.log({ error: toLoggedError(error) });
17292
- finalize();
18004
+ const loggedError = toLoggedError(error);
18005
+ try {
18006
+ span.log({ error: loggedError });
18007
+ } catch (loggingError) {
18008
+ debugLogger.error(
18009
+ "Error logging AI SDK base stream failure:",
18010
+ loggingError
18011
+ );
18012
+ }
18013
+ finalize({
18014
+ error: error instanceof Error ? error : new Error(String(loggedError))
18015
+ });
17293
18016
  controller.error(error);
17294
18017
  }
17295
18018
  },
@@ -18078,7 +18801,8 @@ var claudeAgentSDKChannels = defineChannels(
18078
18801
  channelName: "query",
18079
18802
  kind: "sync-stream"
18080
18803
  })
18081
- }
18804
+ },
18805
+ { instrumentationName: INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK }
18082
18806
  );
18083
18807
 
18084
18808
  // src/instrumentation/plugins/claude-agent-sdk-instrumentation-constants.ts
@@ -18226,22 +18950,27 @@ function wrapLocalClaudeToolHandler(handler, getMetadata) {
18226
18950
  const spanName = metadata.serverName ? `tool: ${metadata.serverName}/${metadata.toolName}` : `tool: ${metadata.toolName}`;
18227
18951
  const runWithResolvedParent = async () => {
18228
18952
  const parent = toolUseId && localToolParentResolver ? await localToolParentResolver(toolUseId).catch(() => void 0) : void 0;
18229
- const span = startSpan({
18230
- event: {
18231
- input: handlerArgs[0],
18232
- metadata: {
18233
- "claude_agent_sdk.raw_tool_name": rawToolName,
18234
- "gen_ai.tool.name": metadata.toolName,
18235
- ...toolUseId && { "gen_ai.tool.call.id": toolUseId },
18236
- ...metadata.serverName && {
18237
- "mcp.server": metadata.serverName
18238
- }
18239
- }
18240
- },
18241
- name: spanName,
18242
- ...parent && { parent },
18243
- spanAttributes: { type: "tool" /* TOOL */ }
18244
- });
18953
+ const span = startSpan(
18954
+ withSpanInstrumentationName(
18955
+ {
18956
+ event: {
18957
+ input: handlerArgs[0],
18958
+ metadata: {
18959
+ "claude_agent_sdk.raw_tool_name": rawToolName,
18960
+ "gen_ai.tool.name": metadata.toolName,
18961
+ ...toolUseId && { "gen_ai.tool.call.id": toolUseId },
18962
+ ...metadata.serverName && {
18963
+ "mcp.server": metadata.serverName
18964
+ }
18965
+ }
18966
+ },
18967
+ name: spanName,
18968
+ ...parent && { parent },
18969
+ spanAttributes: { type: "tool" /* TOOL */ }
18970
+ },
18971
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
18972
+ )
18973
+ );
18245
18974
  const runHandler = () => Reflect.apply(handler, this, handlerArgs);
18246
18975
  const finalizeSuccess = (result) => {
18247
18976
  span.log({ output: result });
@@ -18566,14 +19295,19 @@ async function createLLMSpanForMessages(messages, promptMessages, conversationHi
18566
19295
  ).filter(
18567
19296
  (c) => c !== void 0
18568
19297
  );
18569
- const span = existingSpan ?? startSpan({
18570
- name: "anthropic.messages.create",
18571
- parent: parentSpan,
18572
- spanAttributes: {
18573
- type: "llm" /* LLM */
18574
- },
18575
- startTime
18576
- });
19298
+ const span = existingSpan ?? startSpan(
19299
+ withSpanInstrumentationName(
19300
+ {
19301
+ name: "anthropic.messages.create",
19302
+ parent: parentSpan,
19303
+ spanAttributes: {
19304
+ type: "llm" /* LLM */
19305
+ },
19306
+ startTime
19307
+ },
19308
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
19309
+ )
19310
+ );
18577
19311
  span.log({
18578
19312
  input,
18579
19313
  metadata: model ? { model } : void 0,
@@ -18676,25 +19410,30 @@ function createToolTracingHooks(resolveParentSpan, activeToolSpans, mcpServers,
18676
19410
  return {};
18677
19411
  }
18678
19412
  const parsed = parseToolName(input.tool_name);
18679
- const toolSpan = startSpan({
18680
- event: {
18681
- input: input.tool_input,
18682
- metadata: {
18683
- "claude_agent_sdk.cwd": input.cwd,
18684
- "claude_agent_sdk.raw_tool_name": parsed.rawToolName,
18685
- "claude_agent_sdk.session_id": input.session_id,
18686
- "gen_ai.tool.call.id": toolUseID,
18687
- "gen_ai.tool.name": parsed.toolName,
18688
- ...parsed.mcpServer && { "mcp.server": parsed.mcpServer },
18689
- ...getMcpServerMetadata(parsed.mcpServer, mcpServers)
18690
- }
18691
- },
18692
- name: parsed.displayName,
18693
- parent: await resolveParentSpan(toolUseID, {
18694
- agentId: input.agent_id
18695
- }),
18696
- spanAttributes: { type: "tool" /* TOOL */ }
18697
- });
19413
+ const toolSpan = startSpan(
19414
+ withSpanInstrumentationName(
19415
+ {
19416
+ event: {
19417
+ input: input.tool_input,
19418
+ metadata: {
19419
+ "claude_agent_sdk.cwd": input.cwd,
19420
+ "claude_agent_sdk.raw_tool_name": parsed.rawToolName,
19421
+ "claude_agent_sdk.session_id": input.session_id,
19422
+ "gen_ai.tool.call.id": toolUseID,
19423
+ "gen_ai.tool.name": parsed.toolName,
19424
+ ...parsed.mcpServer && { "mcp.server": parsed.mcpServer },
19425
+ ...getMcpServerMetadata(parsed.mcpServer, mcpServers)
19426
+ }
19427
+ },
19428
+ name: parsed.displayName,
19429
+ parent: await resolveParentSpan(toolUseID, {
19430
+ agentId: input.agent_id
19431
+ }),
19432
+ spanAttributes: { type: "tool" /* TOOL */ }
19433
+ },
19434
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
19435
+ )
19436
+ );
18698
19437
  activeToolSpans.set(toolUseID, toolSpan);
18699
19438
  return {};
18700
19439
  };
@@ -19060,14 +19799,19 @@ async function ensureSubAgentSpan(subAgentDetailsByToolUseId, rootSpan, activeTo
19060
19799
  const spanName = formatSubAgentSpanName(details);
19061
19800
  const parentToolSpan = activeToolSpans.get(parentToolUseId);
19062
19801
  const parentSpan = parentToolSpan ? await parentToolSpan.export() : await rootSpan.export();
19063
- const subAgentSpan = startSpan({
19064
- event: {
19065
- metadata: subAgentDetailsToMetadata(details)
19066
- },
19067
- name: spanName,
19068
- parent: parentSpan,
19069
- spanAttributes: { type: "task" /* TASK */ }
19070
- });
19802
+ const subAgentSpan = startSpan(
19803
+ withSpanInstrumentationName(
19804
+ {
19805
+ event: {
19806
+ metadata: subAgentDetailsToMetadata(details)
19807
+ },
19808
+ name: spanName,
19809
+ parent: parentSpan,
19810
+ spanAttributes: { type: "task" /* TASK */ }
19811
+ },
19812
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
19813
+ )
19814
+ );
19071
19815
  subAgentSpans.set(parentToolUseId, subAgentSpan);
19072
19816
  return subAgentSpan;
19073
19817
  }
@@ -19088,14 +19832,19 @@ async function ensureActiveLlmSpanForParentToolUse(rootSpan, activeLlmSpansByPar
19088
19832
  );
19089
19833
  llmParentSpan = await subAgentSpan.export();
19090
19834
  }
19091
- const llmSpan = startSpan({
19092
- name: "anthropic.messages.create",
19093
- parent: llmParentSpan,
19094
- spanAttributes: {
19095
- type: "llm" /* LLM */
19096
- },
19097
- startTime
19098
- });
19835
+ const llmSpan = startSpan(
19836
+ withSpanInstrumentationName(
19837
+ {
19838
+ name: "anthropic.messages.create",
19839
+ parent: llmParentSpan,
19840
+ spanAttributes: {
19841
+ type: "llm" /* LLM */
19842
+ },
19843
+ startTime
19844
+ },
19845
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
19846
+ )
19847
+ );
19099
19848
  activeLlmSpansByParentToolUse.set(parentKey, llmSpan);
19100
19849
  return llmSpan;
19101
19850
  }
@@ -19364,12 +20113,17 @@ var ClaudeAgentSDKPlugin = class extends BasePlugin {
19364
20113
  }
19365
20114
  })();
19366
20115
  }
19367
- const span = startSpan({
19368
- name: "Claude Agent",
19369
- spanAttributes: {
19370
- type: "task" /* TASK */
19371
- }
19372
- });
20116
+ const span = startSpan(
20117
+ withSpanInstrumentationName(
20118
+ {
20119
+ name: "Claude Agent",
20120
+ spanAttributes: {
20121
+ type: "task" /* TASK */
20122
+ }
20123
+ },
20124
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
20125
+ )
20126
+ );
19373
20127
  const startTime = getCurrentUnixTimestamp();
19374
20128
  try {
19375
20129
  span.log({
@@ -19534,24 +20288,28 @@ var ClaudeAgentSDKPlugin = class extends BasePlugin {
19534
20288
  };
19535
20289
 
19536
20290
  // src/instrumentation/plugins/cursor-sdk-channels.ts
19537
- var cursorSDKChannels = defineChannels("@cursor/sdk", {
19538
- create: channel({
19539
- channelName: "Agent.create",
19540
- kind: "async"
19541
- }),
19542
- resume: channel({
19543
- channelName: "Agent.resume",
19544
- kind: "async"
19545
- }),
19546
- prompt: channel({
19547
- channelName: "Agent.prompt",
19548
- kind: "async"
19549
- }),
19550
- send: channel({
19551
- channelName: "agent.send",
19552
- kind: "async"
19553
- })
19554
- });
20291
+ var cursorSDKChannels = defineChannels(
20292
+ "@cursor/sdk",
20293
+ {
20294
+ create: channel({
20295
+ channelName: "Agent.create",
20296
+ kind: "async"
20297
+ }),
20298
+ resume: channel({
20299
+ channelName: "Agent.resume",
20300
+ kind: "async"
20301
+ }),
20302
+ prompt: channel({
20303
+ channelName: "Agent.prompt",
20304
+ kind: "async"
20305
+ }),
20306
+ send: channel({
20307
+ channelName: "agent.send",
20308
+ kind: "async"
20309
+ })
20310
+ },
20311
+ { instrumentationName: INSTRUMENTATION_NAMES.CURSOR_SDK }
20312
+ );
19555
20313
 
19556
20314
  // src/instrumentation/plugins/cursor-sdk-plugin.ts
19557
20315
  var PATCHED_AGENT = /* @__PURE__ */ Symbol.for("braintrust.cursor-sdk.auto-patched-agent");
@@ -19603,10 +20361,15 @@ var CursorSDKPlugin = class extends BasePlugin {
19603
20361
  provider: "cursor",
19604
20362
  ...event.moduleVersion ? { "cursor_sdk.version": event.moduleVersion } : {}
19605
20363
  };
19606
- const span = startSpan({
19607
- name: "Cursor Agent",
19608
- spanAttributes: { type: "task" /* TASK */ }
19609
- });
20364
+ const span = startSpan(
20365
+ withSpanInstrumentationName(
20366
+ {
20367
+ name: "Cursor Agent",
20368
+ spanAttributes: { type: "task" /* TASK */ }
20369
+ },
20370
+ INSTRUMENTATION_NAMES.CURSOR_SDK
20371
+ )
20372
+ );
19610
20373
  const startTime = getCurrentUnixTimestamp();
19611
20374
  safeLog2(span, {
19612
20375
  input: sanitizeUserMessage(message),
@@ -19668,10 +20431,15 @@ var CursorSDKPlugin = class extends BasePlugin {
19668
20431
  provider: "cursor",
19669
20432
  ...event.moduleVersion ? { "cursor_sdk.version": event.moduleVersion } : {}
19670
20433
  };
19671
- const span = startSpan({
19672
- name: "Cursor Agent",
19673
- spanAttributes: { type: "task" /* TASK */ }
19674
- });
20434
+ const span = startSpan(
20435
+ withSpanInstrumentationName(
20436
+ {
20437
+ name: "Cursor Agent",
20438
+ spanAttributes: { type: "task" /* TASK */ }
20439
+ },
20440
+ INSTRUMENTATION_NAMES.CURSOR_SDK
20441
+ )
20442
+ );
19675
20443
  const startTime = getCurrentUnixTimestamp();
19676
20444
  safeLog2(span, {
19677
20445
  input: sanitizeUserMessage(message),
@@ -20118,29 +20886,39 @@ async function startToolSpan(state, args) {
20118
20886
  if (args.truncated?.result !== void 0) {
20119
20887
  metadata["cursor_sdk.tool.result_truncated"] = args.truncated.result;
20120
20888
  }
20121
- const span = startSpan({
20122
- event: {
20123
- input: args.args,
20124
- metadata
20125
- },
20126
- name: `tool: ${name}`,
20127
- parent: await state.span.export(),
20128
- spanAttributes: { type: "tool" /* TOOL */ }
20129
- });
20889
+ const span = startSpan(
20890
+ withSpanInstrumentationName(
20891
+ {
20892
+ event: {
20893
+ input: args.args,
20894
+ metadata
20895
+ },
20896
+ name: `tool: ${name}`,
20897
+ parent: await state.span.export(),
20898
+ spanAttributes: { type: "tool" /* TOOL */ }
20899
+ },
20900
+ INSTRUMENTATION_NAMES.CURSOR_SDK
20901
+ )
20902
+ );
20130
20903
  let subAgentSpan;
20131
20904
  if (isSubAgentToolName(name)) {
20132
- subAgentSpan = startSpan({
20133
- event: {
20134
- input: args.args,
20135
- metadata: {
20136
- "cursor_sdk.subagent.tool_call_id": args.callId,
20137
- "gen_ai.tool.name": name
20138
- }
20139
- },
20140
- name: formatSubAgentSpanName2(args.toolCall, args.args),
20141
- parent: await span.export(),
20142
- spanAttributes: { type: "task" /* TASK */ }
20143
- });
20905
+ subAgentSpan = startSpan(
20906
+ withSpanInstrumentationName(
20907
+ {
20908
+ event: {
20909
+ input: args.args,
20910
+ metadata: {
20911
+ "cursor_sdk.subagent.tool_call_id": args.callId,
20912
+ "gen_ai.tool.name": name
20913
+ }
20914
+ },
20915
+ name: formatSubAgentSpanName2(args.toolCall, args.args),
20916
+ parent: await span.export(),
20917
+ spanAttributes: { type: "task" /* TASK */ }
20918
+ },
20919
+ INSTRUMENTATION_NAMES.CURSOR_SDK
20920
+ )
20921
+ );
20144
20922
  }
20145
20923
  return { span, subAgentSpan };
20146
20924
  }
@@ -20399,24 +21177,28 @@ function cleanMetrics2(metrics) {
20399
21177
  }
20400
21178
 
20401
21179
  // src/instrumentation/plugins/openai-agents-channels.ts
20402
- var openAIAgentsCoreChannels = defineChannels("@openai/agents-core", {
20403
- onTraceStart: channel({
20404
- channelName: "tracing.processor.onTraceStart",
20405
- kind: "async"
20406
- }),
20407
- onTraceEnd: channel({
20408
- channelName: "tracing.processor.onTraceEnd",
20409
- kind: "async"
20410
- }),
20411
- onSpanStart: channel({
20412
- channelName: "tracing.processor.onSpanStart",
20413
- kind: "async"
20414
- }),
20415
- onSpanEnd: channel({
20416
- channelName: "tracing.processor.onSpanEnd",
20417
- kind: "async"
20418
- })
20419
- });
21180
+ var openAIAgentsCoreChannels = defineChannels(
21181
+ "@openai/agents-core",
21182
+ {
21183
+ onTraceStart: channel({
21184
+ channelName: "tracing.processor.onTraceStart",
21185
+ kind: "async"
21186
+ }),
21187
+ onTraceEnd: channel({
21188
+ channelName: "tracing.processor.onTraceEnd",
21189
+ kind: "async"
21190
+ }),
21191
+ onSpanStart: channel({
21192
+ channelName: "tracing.processor.onSpanStart",
21193
+ kind: "async"
21194
+ }),
21195
+ onSpanEnd: channel({
21196
+ channelName: "tracing.processor.onSpanEnd",
21197
+ kind: "async"
21198
+ })
21199
+ },
21200
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENAI_AGENTS }
21201
+ );
20420
21202
 
20421
21203
  // src/instrumentation/plugins/openai-agents-trace-processor.ts
20422
21204
  function isSpanData(spanData, type) {
@@ -20532,16 +21314,19 @@ var OpenAIAgentsTraceProcessor = class _OpenAIAgentsTraceProcessor {
20532
21314
  this.evictOldestTrace();
20533
21315
  }
20534
21316
  const current = currentSpan();
20535
- const span = current && current !== NOOP_SPAN ? current.startSpan({
20536
- name: trace.name,
20537
- type: "task" /* TASK */
20538
- }) : this.logger ? this.logger.startSpan({
20539
- name: trace.name,
20540
- type: "task" /* TASK */
20541
- }) : startSpan({
20542
- name: trace.name,
20543
- type: "task" /* TASK */
20544
- });
21317
+ const spanArgs = withSpanInstrumentationName(
21318
+ {
21319
+ name: trace.name,
21320
+ type: "task" /* TASK */
21321
+ },
21322
+ INSTRUMENTATION_NAMES.OPENAI_AGENTS
21323
+ );
21324
+ const span = current && current !== NOOP_SPAN ? current.startSpan(spanArgs) : this.logger ? this.logger.startSpan(spanArgs) : startSpan(
21325
+ withSpanInstrumentationName(
21326
+ spanArgs,
21327
+ INSTRUMENTATION_NAMES.OPENAI_AGENTS
21328
+ )
21329
+ );
20545
21330
  span.log({
20546
21331
  input: "Agent workflow started",
20547
21332
  metadata: {
@@ -20592,10 +21377,15 @@ var OpenAIAgentsTraceProcessor = class _OpenAIAgentsTraceProcessor {
20592
21377
  if (!parentSpan) {
20593
21378
  return Promise.resolve();
20594
21379
  }
20595
- const childSpan = parentSpan.startSpan({
20596
- name: spanNameFromAgents(span),
20597
- type: spanTypeFromAgents(span)
20598
- });
21380
+ const childSpan = parentSpan.startSpan(
21381
+ withSpanInstrumentationName(
21382
+ {
21383
+ name: spanNameFromAgents(span),
21384
+ type: spanTypeFromAgents(span)
21385
+ },
21386
+ INSTRUMENTATION_NAMES.OPENAI_AGENTS
21387
+ )
21388
+ );
20599
21389
  traceData.childSpans.set(span.spanId, childSpan);
20600
21390
  return Promise.resolve();
20601
21391
  }
@@ -20860,24 +21650,28 @@ var OpenAIAgentsPlugin = class extends BasePlugin {
20860
21650
  };
20861
21651
 
20862
21652
  // src/instrumentation/plugins/google-genai-channels.ts
20863
- var googleGenAIChannels = defineChannels("@google/genai", {
20864
- generateContent: channel({
20865
- channelName: "models.generateContent",
20866
- kind: "async"
20867
- }),
20868
- generateContentStream: channel({
20869
- channelName: "models.generateContentStream",
20870
- kind: "async"
20871
- }),
20872
- embedContent: channel({
20873
- channelName: "models.embedContent",
20874
- kind: "async"
20875
- }),
20876
- interactionsCreate: channel({
20877
- channelName: "interactions.create",
20878
- kind: "async"
20879
- })
20880
- });
21653
+ var googleGenAIChannels = defineChannels(
21654
+ "@google/genai",
21655
+ {
21656
+ generateContent: channel({
21657
+ channelName: "models.generateContent",
21658
+ kind: "async"
21659
+ }),
21660
+ generateContentStream: channel({
21661
+ channelName: "models.generateContentStream",
21662
+ kind: "async"
21663
+ }),
21664
+ embedContent: channel({
21665
+ channelName: "models.embedContent",
21666
+ kind: "async"
21667
+ }),
21668
+ interactionsCreate: channel({
21669
+ channelName: "interactions.create",
21670
+ kind: "async"
21671
+ })
21672
+ },
21673
+ { instrumentationName: INSTRUMENTATION_NAMES.GOOGLE_GENAI }
21674
+ );
20881
21675
 
20882
21676
  // src/instrumentation/plugins/google-genai-plugin.ts
20883
21677
  var GOOGLE_GENAI_INTERNAL_CONTEXT = {
@@ -20915,13 +21709,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
20915
21709
  const params = event.arguments[0];
20916
21710
  const input = serializeGenerateContentInput(params);
20917
21711
  const metadata = extractGenerateContentMetadata(params);
20918
- const span = startSpan({
20919
- name: "generate_content",
20920
- spanAttributes: {
20921
- type: "llm" /* LLM */
20922
- },
20923
- event: createWrapperParityEvent({ input, metadata })
20924
- });
21712
+ const span = startSpan(
21713
+ withSpanInstrumentationName(
21714
+ {
21715
+ name: "generate_content",
21716
+ spanAttributes: {
21717
+ type: "llm" /* LLM */
21718
+ },
21719
+ event: createWrapperParityEvent({ input, metadata })
21720
+ },
21721
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
21722
+ )
21723
+ );
20925
21724
  return {
20926
21725
  span,
20927
21726
  startTime: getCurrentUnixTimestamp()
@@ -20934,13 +21733,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
20934
21733
  const params = event.arguments[0];
20935
21734
  const input = serializeGenerateContentInput(params);
20936
21735
  const metadata = extractGenerateContentMetadata(params);
20937
- const span = startSpan({
20938
- name: "generate_content",
20939
- spanAttributes: {
20940
- type: "llm" /* LLM */
20941
- },
20942
- event: createWrapperParityEvent({ input, metadata })
20943
- });
21736
+ const span = startSpan(
21737
+ withSpanInstrumentationName(
21738
+ {
21739
+ name: "generate_content",
21740
+ spanAttributes: {
21741
+ type: "llm" /* LLM */
21742
+ },
21743
+ event: createWrapperParityEvent({ input, metadata })
21744
+ },
21745
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
21746
+ )
21747
+ );
20944
21748
  return {
20945
21749
  span,
20946
21750
  startTime: getCurrentUnixTimestamp()
@@ -21016,13 +21820,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
21016
21820
  const params = event.arguments[0];
21017
21821
  const input = serializeEmbedContentInput(params);
21018
21822
  const metadata = extractEmbedContentMetadata(params);
21019
- const span = startSpan({
21020
- name: "embed_content",
21021
- spanAttributes: {
21022
- type: "llm" /* LLM */
21023
- },
21024
- event: createWrapperParityEvent({ input, metadata })
21025
- });
21823
+ const span = startSpan(
21824
+ withSpanInstrumentationName(
21825
+ {
21826
+ name: "embed_content",
21827
+ spanAttributes: {
21828
+ type: "llm" /* LLM */
21829
+ },
21830
+ event: createWrapperParityEvent({ input, metadata })
21831
+ },
21832
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
21833
+ )
21834
+ );
21026
21835
  return {
21027
21836
  span,
21028
21837
  startTime: getCurrentUnixTimestamp()
@@ -21035,13 +21844,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
21035
21844
  const params = event.arguments[0];
21036
21845
  const input = serializeEmbedContentInput(params);
21037
21846
  const metadata = extractEmbedContentMetadata(params);
21038
- const span = startSpan({
21039
- name: "embed_content",
21040
- spanAttributes: {
21041
- type: "llm" /* LLM */
21042
- },
21043
- event: createWrapperParityEvent({ input, metadata })
21044
- });
21847
+ const span = startSpan(
21848
+ withSpanInstrumentationName(
21849
+ {
21850
+ name: "embed_content",
21851
+ spanAttributes: {
21852
+ type: "llm" /* LLM */
21853
+ },
21854
+ event: createWrapperParityEvent({ input, metadata })
21855
+ },
21856
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
21857
+ )
21858
+ );
21045
21859
  return {
21046
21860
  span,
21047
21861
  startTime: getCurrentUnixTimestamp()
@@ -21152,16 +21966,21 @@ function patchGoogleGenAIStreamingResult(args) {
21152
21966
  const requestStartTime = startTime ?? getCurrentUnixTimestamp();
21153
21967
  const ensureSpan = () => {
21154
21968
  if (!span) {
21155
- span = startSpan({
21156
- name: "generate_content_stream",
21157
- spanAttributes: {
21158
- type: "llm" /* LLM */
21159
- },
21160
- event: {
21161
- input,
21162
- metadata
21163
- }
21164
- });
21969
+ span = startSpan(
21970
+ withSpanInstrumentationName(
21971
+ {
21972
+ name: "generate_content_stream",
21973
+ spanAttributes: {
21974
+ type: "llm" /* LLM */
21975
+ },
21976
+ event: {
21977
+ input,
21978
+ metadata
21979
+ }
21980
+ },
21981
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
21982
+ )
21983
+ );
21165
21984
  }
21166
21985
  return span;
21167
21986
  };
@@ -21929,28 +22748,32 @@ function tryToDict(obj) {
21929
22748
  }
21930
22749
 
21931
22750
  // src/instrumentation/plugins/huggingface-channels.ts
21932
- var huggingFaceChannels = defineChannels("@huggingface/inference", {
21933
- chatCompletion: channel({
21934
- channelName: "chatCompletion",
21935
- kind: "async"
21936
- }),
21937
- chatCompletionStream: channel({
21938
- channelName: "chatCompletionStream",
21939
- kind: "sync-stream"
21940
- }),
21941
- textGeneration: channel({
21942
- channelName: "textGeneration",
21943
- kind: "async"
21944
- }),
21945
- textGenerationStream: channel({
21946
- channelName: "textGenerationStream",
21947
- kind: "sync-stream"
21948
- }),
21949
- featureExtraction: channel({
21950
- channelName: "featureExtraction",
21951
- kind: "async"
21952
- })
21953
- });
22751
+ var huggingFaceChannels = defineChannels(
22752
+ "@huggingface/inference",
22753
+ {
22754
+ chatCompletion: channel({
22755
+ channelName: "chatCompletion",
22756
+ kind: "async"
22757
+ }),
22758
+ chatCompletionStream: channel({
22759
+ channelName: "chatCompletionStream",
22760
+ kind: "sync-stream"
22761
+ }),
22762
+ textGeneration: channel({
22763
+ channelName: "textGeneration",
22764
+ kind: "async"
22765
+ }),
22766
+ textGenerationStream: channel({
22767
+ channelName: "textGenerationStream",
22768
+ kind: "sync-stream"
22769
+ }),
22770
+ featureExtraction: channel({
22771
+ channelName: "featureExtraction",
22772
+ kind: "async"
22773
+ })
22774
+ },
22775
+ { instrumentationName: INSTRUMENTATION_NAMES.HUGGINGFACE }
22776
+ );
21954
22777
 
21955
22778
  // src/instrumentation/plugins/huggingface-plugin.ts
21956
22779
  var REQUEST_METADATA_ALLOWLIST = /* @__PURE__ */ new Set([
@@ -22377,20 +23200,24 @@ function extractTextGenerationStreamMetadata(chunks) {
22377
23200
  }
22378
23201
 
22379
23202
  // src/instrumentation/plugins/openrouter-agent-channels.ts
22380
- var openRouterAgentChannels = defineChannels("@openrouter/agent", {
22381
- callModel: channel({
22382
- channelName: "callModel",
22383
- kind: "sync-stream"
22384
- }),
22385
- callModelTurn: channel({
22386
- channelName: "callModel.turn",
22387
- kind: "async"
22388
- }),
22389
- toolExecute: channel({
22390
- channelName: "tool.execute",
22391
- kind: "async"
22392
- })
22393
- });
23203
+ var openRouterAgentChannels = defineChannels(
23204
+ "@openrouter/agent",
23205
+ {
23206
+ callModel: channel({
23207
+ channelName: "callModel",
23208
+ kind: "sync-stream"
23209
+ }),
23210
+ callModelTurn: channel({
23211
+ channelName: "callModel.turn",
23212
+ kind: "async"
23213
+ }),
23214
+ toolExecute: channel({
23215
+ channelName: "tool.execute",
23216
+ kind: "async"
23217
+ })
23218
+ },
23219
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENROUTER_AGENT }
23220
+ );
22394
23221
 
22395
23222
  // src/instrumentation/plugins/openrouter-agent-plugin.ts
22396
23223
  var OpenRouterAgentPlugin = class extends BasePlugin {
@@ -23160,38 +23987,40 @@ function normalizeError(error) {
23160
23987
  }
23161
23988
 
23162
23989
  // src/instrumentation/plugins/openrouter-channels.ts
23163
- var openRouterChannels = defineChannels("@openrouter/sdk", {
23164
- chatSend: channel({
23165
- channelName: "chat.send",
23166
- kind: "async"
23167
- }),
23168
- embeddingsGenerate: channel({
23169
- channelName: "embeddings.generate",
23170
- kind: "async"
23171
- }),
23172
- rerankRerank: channel(
23173
- {
23990
+ var openRouterChannels = defineChannels(
23991
+ "@openrouter/sdk",
23992
+ {
23993
+ chatSend: channel({
23994
+ channelName: "chat.send",
23995
+ kind: "async"
23996
+ }),
23997
+ embeddingsGenerate: channel({
23998
+ channelName: "embeddings.generate",
23999
+ kind: "async"
24000
+ }),
24001
+ rerankRerank: channel({
23174
24002
  channelName: "rerank.rerank",
23175
24003
  kind: "async"
23176
- }
23177
- ),
23178
- betaResponsesSend: channel({
23179
- channelName: "beta.responses.send",
23180
- kind: "async"
23181
- }),
23182
- callModel: channel({
23183
- channelName: "callModel",
23184
- kind: "sync-stream"
23185
- }),
23186
- callModelTurn: channel({
23187
- channelName: "callModel.turn",
23188
- kind: "async"
23189
- }),
23190
- toolExecute: channel({
23191
- channelName: "tool.execute",
23192
- kind: "async"
23193
- })
23194
- });
24004
+ }),
24005
+ betaResponsesSend: channel({
24006
+ channelName: "beta.responses.send",
24007
+ kind: "async"
24008
+ }),
24009
+ callModel: channel({
24010
+ channelName: "callModel",
24011
+ kind: "sync-stream"
24012
+ }),
24013
+ callModelTurn: channel({
24014
+ channelName: "callModel.turn",
24015
+ kind: "async"
24016
+ }),
24017
+ toolExecute: channel({
24018
+ channelName: "tool.execute",
24019
+ kind: "async"
24020
+ })
24021
+ },
24022
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENROUTER }
24023
+ );
23195
24024
 
23196
24025
  // src/instrumentation/plugins/openrouter-plugin.ts
23197
24026
  var OpenRouterPlugin = class extends BasePlugin {
@@ -24231,52 +25060,56 @@ function normalizeError2(error) {
24231
25060
  }
24232
25061
 
24233
25062
  // src/instrumentation/plugins/mistral-channels.ts
24234
- var mistralChannels = defineChannels("@mistralai/mistralai", {
24235
- chatComplete: channel({
24236
- channelName: "chat.complete",
24237
- kind: "async"
24238
- }),
24239
- chatStream: channel({
24240
- channelName: "chat.stream",
24241
- kind: "async"
24242
- }),
24243
- embeddingsCreate: channel({
24244
- channelName: "embeddings.create",
24245
- kind: "async"
24246
- }),
24247
- classifiersModerate: channel({
24248
- channelName: "classifiers.moderate",
24249
- kind: "async"
24250
- }),
24251
- classifiersModerateChat: channel({
24252
- channelName: "classifiers.moderateChat",
24253
- kind: "async"
24254
- }),
24255
- classifiersClassify: channel({
24256
- channelName: "classifiers.classify",
24257
- kind: "async"
24258
- }),
24259
- classifiersClassifyChat: channel({
24260
- channelName: "classifiers.classifyChat",
24261
- kind: "async"
24262
- }),
24263
- fimComplete: channel({
24264
- channelName: "fim.complete",
24265
- kind: "async"
24266
- }),
24267
- fimStream: channel({
24268
- channelName: "fim.stream",
24269
- kind: "async"
24270
- }),
24271
- agentsComplete: channel({
24272
- channelName: "agents.complete",
24273
- kind: "async"
24274
- }),
24275
- agentsStream: channel({
24276
- channelName: "agents.stream",
24277
- kind: "async"
24278
- })
24279
- });
25063
+ var mistralChannels = defineChannels(
25064
+ "@mistralai/mistralai",
25065
+ {
25066
+ chatComplete: channel({
25067
+ channelName: "chat.complete",
25068
+ kind: "async"
25069
+ }),
25070
+ chatStream: channel({
25071
+ channelName: "chat.stream",
25072
+ kind: "async"
25073
+ }),
25074
+ embeddingsCreate: channel({
25075
+ channelName: "embeddings.create",
25076
+ kind: "async"
25077
+ }),
25078
+ classifiersModerate: channel({
25079
+ channelName: "classifiers.moderate",
25080
+ kind: "async"
25081
+ }),
25082
+ classifiersModerateChat: channel({
25083
+ channelName: "classifiers.moderateChat",
25084
+ kind: "async"
25085
+ }),
25086
+ classifiersClassify: channel({
25087
+ channelName: "classifiers.classify",
25088
+ kind: "async"
25089
+ }),
25090
+ classifiersClassifyChat: channel({
25091
+ channelName: "classifiers.classifyChat",
25092
+ kind: "async"
25093
+ }),
25094
+ fimComplete: channel({
25095
+ channelName: "fim.complete",
25096
+ kind: "async"
25097
+ }),
25098
+ fimStream: channel({
25099
+ channelName: "fim.stream",
25100
+ kind: "async"
25101
+ }),
25102
+ agentsComplete: channel({
25103
+ channelName: "agents.complete",
25104
+ kind: "async"
25105
+ }),
25106
+ agentsStream: channel({
25107
+ channelName: "agents.stream",
25108
+ kind: "async"
25109
+ })
25110
+ },
25111
+ { instrumentationName: INSTRUMENTATION_NAMES.MISTRAL }
25112
+ );
24280
25113
 
24281
25114
  // src/instrumentation/plugins/mistral-plugin.ts
24282
25115
  var MistralPlugin = class extends BasePlugin {
@@ -24896,20 +25729,24 @@ function aggregateMistralStreamChunks(chunks) {
24896
25729
  }
24897
25730
 
24898
25731
  // src/instrumentation/plugins/google-adk-channels.ts
24899
- var googleADKChannels = defineChannels("@google/adk", {
24900
- runnerRunAsync: channel({
24901
- channelName: "runner.runAsync",
24902
- kind: "sync-stream"
24903
- }),
24904
- agentRunAsync: channel({
24905
- channelName: "agent.runAsync",
24906
- kind: "sync-stream"
24907
- }),
24908
- toolRunAsync: channel({
24909
- channelName: "tool.runAsync",
24910
- kind: "async"
24911
- })
24912
- });
25732
+ var googleADKChannels = defineChannels(
25733
+ "@google/adk",
25734
+ {
25735
+ runnerRunAsync: channel({
25736
+ channelName: "runner.runAsync",
25737
+ kind: "sync-stream"
25738
+ }),
25739
+ agentRunAsync: channel({
25740
+ channelName: "agent.runAsync",
25741
+ kind: "sync-stream"
25742
+ }),
25743
+ toolRunAsync: channel({
25744
+ channelName: "tool.runAsync",
25745
+ kind: "async"
25746
+ })
25747
+ },
25748
+ { instrumentationName: INSTRUMENTATION_NAMES.GOOGLE_ADK }
25749
+ );
24913
25750
 
24914
25751
  // src/instrumentation/plugins/google-adk-plugin.ts
24915
25752
  var GoogleADKPlugin = class extends BasePlugin {
@@ -24934,12 +25771,17 @@ var GoogleADKPlugin = class extends BasePlugin {
24934
25771
  const createState = (event) => {
24935
25772
  const params = event.arguments[0] ?? {};
24936
25773
  const contextKey = extractRunnerContextKey(params);
24937
- const span = startSpan({
24938
- name: "Google ADK Runner",
24939
- spanAttributes: {
24940
- type: "task" /* TASK */
24941
- }
24942
- });
25774
+ const span = startSpan(
25775
+ withSpanInstrumentationName(
25776
+ {
25777
+ name: "Google ADK Runner",
25778
+ spanAttributes: {
25779
+ type: "task" /* TASK */
25780
+ }
25781
+ },
25782
+ INSTRUMENTATION_NAMES.GOOGLE_ADK
25783
+ )
25784
+ );
24943
25785
  const startTime = getCurrentUnixTimestamp();
24944
25786
  try {
24945
25787
  const metadata = extractRunnerMetadata(params);
@@ -25025,18 +25867,23 @@ var GoogleADKPlugin = class extends BasePlugin {
25025
25867
  this.activeRunnerSpans
25026
25868
  );
25027
25869
  const contextKey = extractInvocationContextKey(parentContext);
25028
- const span = startSpan({
25029
- name: agentName ? `Agent: ${agentName}` : "Google ADK Agent",
25030
- spanAttributes: {
25031
- type: "task" /* TASK */
25032
- },
25033
- ...runnerParentSpan ? {
25034
- parentSpanIds: {
25035
- spanId: runnerParentSpan.spanId,
25036
- rootSpanId: runnerParentSpan.rootSpanId
25037
- }
25038
- } : {}
25039
- });
25870
+ const span = startSpan(
25871
+ withSpanInstrumentationName(
25872
+ {
25873
+ name: agentName ? `Agent: ${agentName}` : "Google ADK Agent",
25874
+ spanAttributes: {
25875
+ type: "task" /* TASK */
25876
+ },
25877
+ ...runnerParentSpan ? {
25878
+ parentSpanIds: {
25879
+ spanId: runnerParentSpan.spanId,
25880
+ rootSpanId: runnerParentSpan.rootSpanId
25881
+ }
25882
+ } : {}
25883
+ },
25884
+ INSTRUMENTATION_NAMES.GOOGLE_ADK
25885
+ )
25886
+ );
25040
25887
  const startTime = getCurrentUnixTimestamp();
25041
25888
  try {
25042
25889
  const metadata = {
@@ -25129,22 +25976,27 @@ var GoogleADKPlugin = class extends BasePlugin {
25129
25976
  this.activeAgentSpans,
25130
25977
  this.activeRunnerSpans
25131
25978
  );
25132
- const createSpan = () => startSpan({
25133
- name: toolName ? `tool: ${toolName}` : "Google ADK Tool",
25134
- spanAttributes: {
25135
- type: "tool" /* TOOL */
25136
- },
25137
- event: {
25138
- input: req.args,
25139
- metadata: {
25140
- provider: "google-adk",
25141
- ...toolName && { "google_adk.tool_name": toolName },
25142
- ...extractToolCallId(req) && {
25143
- "google_adk.tool_call_id": extractToolCallId(req)
25979
+ const createSpan = () => startSpan(
25980
+ withSpanInstrumentationName(
25981
+ {
25982
+ name: toolName ? `tool: ${toolName}` : "Google ADK Tool",
25983
+ spanAttributes: {
25984
+ type: "tool" /* TOOL */
25985
+ },
25986
+ event: {
25987
+ input: req.args,
25988
+ metadata: {
25989
+ provider: "google-adk",
25990
+ ...toolName && { "google_adk.tool_name": toolName },
25991
+ ...extractToolCallId(req) && {
25992
+ "google_adk.tool_call_id": extractToolCallId(req)
25993
+ }
25994
+ }
25144
25995
  }
25145
- }
25146
- }
25147
- });
25996
+ },
25997
+ INSTRUMENTATION_NAMES.GOOGLE_ADK
25998
+ )
25999
+ );
25148
26000
  const span = parentSpan ? withCurrent(parentSpan, () => createSpan()) : createSpan();
25149
26001
  const startTime = getCurrentUnixTimestamp();
25150
26002
  states.set(event, { span, startTime });
@@ -25543,24 +26395,28 @@ function cleanMetrics4(metrics) {
25543
26395
  }
25544
26396
 
25545
26397
  // src/instrumentation/plugins/cohere-channels.ts
25546
- var cohereChannels = defineChannels("cohere-ai", {
25547
- chat: channel({
25548
- channelName: "chat",
25549
- kind: "async"
25550
- }),
25551
- chatStream: channel({
25552
- channelName: "chatStream",
25553
- kind: "async"
25554
- }),
25555
- embed: channel({
25556
- channelName: "embed",
25557
- kind: "async"
25558
- }),
25559
- rerank: channel({
25560
- channelName: "rerank",
25561
- kind: "async"
25562
- })
25563
- });
26398
+ var cohereChannels = defineChannels(
26399
+ "cohere-ai",
26400
+ {
26401
+ chat: channel({
26402
+ channelName: "chat",
26403
+ kind: "async"
26404
+ }),
26405
+ chatStream: channel({
26406
+ channelName: "chatStream",
26407
+ kind: "async"
26408
+ }),
26409
+ embed: channel({
26410
+ channelName: "embed",
26411
+ kind: "async"
26412
+ }),
26413
+ rerank: channel({
26414
+ channelName: "rerank",
26415
+ kind: "async"
26416
+ })
26417
+ },
26418
+ { instrumentationName: INSTRUMENTATION_NAMES.COHERE }
26419
+ );
25564
26420
 
25565
26421
  // src/instrumentation/plugins/cohere-plugin.ts
25566
26422
  var CoherePlugin = class extends BasePlugin {
@@ -26229,18 +27085,20 @@ function aggregateCohereChatStreamChunks(chunks) {
26229
27085
  }
26230
27086
 
26231
27087
  // src/instrumentation/plugins/groq-channels.ts
26232
- var groqChannels = defineChannels("groq-sdk", {
26233
- chatCompletionsCreate: channel({
26234
- channelName: "chat.completions.create",
26235
- kind: "async"
26236
- }),
26237
- embeddingsCreate: channel(
26238
- {
27088
+ var groqChannels = defineChannels(
27089
+ "groq-sdk",
27090
+ {
27091
+ chatCompletionsCreate: channel({
27092
+ channelName: "chat.completions.create",
27093
+ kind: "async"
27094
+ }),
27095
+ embeddingsCreate: channel({
26239
27096
  channelName: "embeddings.create",
26240
27097
  kind: "async"
26241
- }
26242
- )
26243
- });
27098
+ })
27099
+ },
27100
+ { instrumentationName: INSTRUMENTATION_NAMES.GROQ }
27101
+ );
26244
27102
 
26245
27103
  // src/instrumentation/plugins/groq-plugin.ts
26246
27104
  var GroqPlugin = class extends BasePlugin {
@@ -26343,15 +27201,27 @@ var clientSendChannel = channel({
26343
27201
  channelName: "client.send",
26344
27202
  kind: "async"
26345
27203
  });
26346
- var bedrockRuntimeChannels = defineChannels("aws-bedrock-runtime", {
26347
- clientSend: clientSendChannel
26348
- });
26349
- var smithyCoreChannels = defineChannels("@smithy/core", {
26350
- clientSend: clientSendChannel
26351
- });
26352
- var smithyClientChannels = defineChannels("@smithy/smithy-client", {
26353
- clientSend: clientSendChannel
26354
- });
27204
+ var bedrockRuntimeChannels = defineChannels(
27205
+ "aws-bedrock-runtime",
27206
+ {
27207
+ clientSend: clientSendChannel
27208
+ },
27209
+ { instrumentationName: INSTRUMENTATION_NAMES.BEDROCK_RUNTIME }
27210
+ );
27211
+ var smithyCoreChannels = defineChannels(
27212
+ "@smithy/core",
27213
+ {
27214
+ clientSend: clientSendChannel
27215
+ },
27216
+ { instrumentationName: INSTRUMENTATION_NAMES.BEDROCK_RUNTIME }
27217
+ );
27218
+ var smithyClientChannels = defineChannels(
27219
+ "@smithy/smithy-client",
27220
+ {
27221
+ clientSend: clientSendChannel
27222
+ },
27223
+ { instrumentationName: INSTRUMENTATION_NAMES.BEDROCK_RUNTIME }
27224
+ );
26355
27225
 
26356
27226
  // src/instrumentation/plugins/bedrock-runtime-common.ts
26357
27227
  var BEDROCK_RUNTIME_COMMAND_OPERATIONS = {
@@ -26985,38 +27855,46 @@ function extractTextFromJsonLike(value) {
26985
27855
  }
26986
27856
 
26987
27857
  // src/instrumentation/plugins/genkit-channels.ts
26988
- var genkitChannels = defineChannels("@genkit-ai/ai", {
26989
- generate: channel({
26990
- channelName: "generate",
26991
- kind: "async"
26992
- }),
26993
- generateStream: channel({
26994
- channelName: "generateStream",
26995
- kind: "sync-stream"
26996
- }),
26997
- embed: channel({
26998
- channelName: "embed",
26999
- kind: "async"
27000
- }),
27001
- embedMany: channel({
27002
- channelName: "embedMany",
27003
- kind: "async"
27004
- }),
27005
- actionRun: channel({
27006
- channelName: "action.run",
27007
- kind: "async"
27008
- }),
27009
- actionStream: channel({
27010
- channelName: "action.stream",
27011
- kind: "sync-stream"
27012
- })
27013
- });
27014
- var genkitCoreChannels = defineChannels("@genkit-ai/core", {
27015
- actionSpan: channel({
27016
- channelName: "action.span",
27017
- kind: "async"
27018
- })
27019
- });
27858
+ var genkitChannels = defineChannels(
27859
+ "@genkit-ai/ai",
27860
+ {
27861
+ generate: channel({
27862
+ channelName: "generate",
27863
+ kind: "async"
27864
+ }),
27865
+ generateStream: channel({
27866
+ channelName: "generateStream",
27867
+ kind: "sync-stream"
27868
+ }),
27869
+ embed: channel({
27870
+ channelName: "embed",
27871
+ kind: "async"
27872
+ }),
27873
+ embedMany: channel({
27874
+ channelName: "embedMany",
27875
+ kind: "async"
27876
+ }),
27877
+ actionRun: channel({
27878
+ channelName: "action.run",
27879
+ kind: "async"
27880
+ }),
27881
+ actionStream: channel({
27882
+ channelName: "action.stream",
27883
+ kind: "sync-stream"
27884
+ })
27885
+ },
27886
+ { instrumentationName: INSTRUMENTATION_NAMES.GENKIT }
27887
+ );
27888
+ var genkitCoreChannels = defineChannels(
27889
+ "@genkit-ai/core",
27890
+ {
27891
+ actionSpan: channel({
27892
+ channelName: "action.span",
27893
+ kind: "async"
27894
+ })
27895
+ },
27896
+ { instrumentationName: INSTRUMENTATION_NAMES.GENKIT }
27897
+ );
27020
27898
 
27021
27899
  // src/instrumentation/plugins/genkit-plugin.ts
27022
27900
  var GenkitPlugin = class extends BasePlugin {
@@ -27201,12 +28079,17 @@ function startActionSpanState(args) {
27201
28079
  if (!shouldTraceAction(args.metadata, args.runStepName)) {
27202
28080
  return void 0;
27203
28081
  }
27204
- const span = startSpan({
27205
- name: actionSpanName(args.metadata, args.runStepName),
27206
- spanAttributes: {
27207
- type: actionSpanType(args.metadata)
27208
- }
27209
- });
28082
+ const span = startSpan(
28083
+ withSpanInstrumentationName(
28084
+ {
28085
+ name: actionSpanName(args.metadata, args.runStepName),
28086
+ spanAttributes: {
28087
+ type: actionSpanType(args.metadata)
28088
+ }
28089
+ },
28090
+ INSTRUMENTATION_NAMES.GENKIT
28091
+ )
28092
+ );
27210
28093
  const startTime = getCurrentUnixTimestamp();
27211
28094
  span.log({
27212
28095
  input: args.input,
@@ -27567,20 +28450,24 @@ function stringValue(value) {
27567
28450
  }
27568
28451
 
27569
28452
  // src/instrumentation/plugins/github-copilot-channels.ts
27570
- var gitHubCopilotChannels = defineChannels("@github/copilot-sdk", {
27571
- createSession: channel({
27572
- channelName: "client.createSession",
27573
- kind: "async"
27574
- }),
27575
- resumeSession: channel({
27576
- channelName: "client.resumeSession",
27577
- kind: "async"
27578
- }),
27579
- sendAndWait: channel({
27580
- channelName: "session.sendAndWait",
27581
- kind: "async"
27582
- })
27583
- });
28453
+ var gitHubCopilotChannels = defineChannels(
28454
+ "@github/copilot-sdk",
28455
+ {
28456
+ createSession: channel({
28457
+ channelName: "client.createSession",
28458
+ kind: "async"
28459
+ }),
28460
+ resumeSession: channel({
28461
+ channelName: "client.resumeSession",
28462
+ kind: "async"
28463
+ }),
28464
+ sendAndWait: channel({
28465
+ channelName: "session.sendAndWait",
28466
+ kind: "async"
28467
+ })
28468
+ },
28469
+ { instrumentationName: INSTRUMENTATION_NAMES.GITHUB_COPILOT }
28470
+ );
27584
28471
 
27585
28472
  // src/instrumentation/plugins/github-copilot-plugin.ts
27586
28473
  var ROOT_AGENT_KEY = "__root__";
@@ -27671,11 +28558,16 @@ async function handleTurnStart(state, agentId) {
27671
28558
  return;
27672
28559
  }
27673
28560
  const parentId = await getParentIdForAgent(state, agentId);
27674
- const span = startSpan({
27675
- name: "Copilot Turn",
27676
- parent: parentId,
27677
- spanAttributes: { type: "task" /* TASK */ }
27678
- });
28561
+ const span = startSpan(
28562
+ withSpanInstrumentationName(
28563
+ {
28564
+ name: "Copilot Turn",
28565
+ parent: parentId,
28566
+ spanAttributes: { type: "task" /* TASK */ }
28567
+ },
28568
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
28569
+ )
28570
+ );
27679
28571
  const pendingUserMessage = state.pendingUserMessages.get(key);
27680
28572
  if (pendingUserMessage) {
27681
28573
  span.log({ input: pendingUserMessage });
@@ -27706,11 +28598,16 @@ async function handleUsage(state, agentId, usage) {
27706
28598
  const parentId = turn ? await turn.id : await state.session.id;
27707
28599
  const content = state.currentMessageContent.get(key);
27708
28600
  const { metrics, metadata } = extractMetricsFromUsage(usage);
27709
- const llmSpan = startSpan({
27710
- name: "github.copilot.llm",
27711
- parent: parentId,
27712
- spanAttributes: { type: "llm" /* LLM */ }
27713
- });
28601
+ const llmSpan = startSpan(
28602
+ withSpanInstrumentationName(
28603
+ {
28604
+ name: "github.copilot.llm",
28605
+ parent: parentId,
28606
+ spanAttributes: { type: "llm" /* LLM */ }
28607
+ },
28608
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
28609
+ )
28610
+ );
27714
28611
  llmSpan.log({
27715
28612
  output: content ?? void 0,
27716
28613
  metadata,
@@ -27736,11 +28633,16 @@ async function handleToolStart(state, agentId, toolCallId, toolName, args, mcpSe
27736
28633
  }
27737
28634
  const parentId = await getToolParentId(state, agentId);
27738
28635
  const displayName = mcpServerName ? `tool: ${mcpServerName}/${toolName}` : `tool: ${toolName}`;
27739
- const span = startSpan({
27740
- name: displayName,
27741
- parent: parentId,
27742
- spanAttributes: { type: "tool" /* TOOL */ }
27743
- });
28636
+ const span = startSpan(
28637
+ withSpanInstrumentationName(
28638
+ {
28639
+ name: displayName,
28640
+ parent: parentId,
28641
+ spanAttributes: { type: "tool" /* TOOL */ }
28642
+ },
28643
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
28644
+ )
28645
+ );
27744
28646
  const metadata = {
27745
28647
  "gen_ai.tool.name": toolName,
27746
28648
  "gen_ai.tool.call.id": toolCallId
@@ -27776,11 +28678,16 @@ async function handleSubagentStarted(state, agentId, toolCallId, agentDisplayNam
27776
28678
  }
27777
28679
  const tool = state.activeTools.get(toolCallId);
27778
28680
  const parentId = tool ? await tool.id : await state.session.id;
27779
- const span = startSpan({
27780
- name: `Agent: ${agentDisplayName}`,
27781
- parent: parentId,
27782
- spanAttributes: { type: "task" /* TASK */ }
27783
- });
28681
+ const span = startSpan(
28682
+ withSpanInstrumentationName(
28683
+ {
28684
+ name: `Agent: ${agentDisplayName}`,
28685
+ parent: parentId,
28686
+ spanAttributes: { type: "task" /* TASK */ }
28687
+ },
28688
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
28689
+ )
28690
+ );
27784
28691
  span.log({
27785
28692
  metadata: {
27786
28693
  "github_copilot.agent_name": agentDisplayName,
@@ -28006,10 +28913,15 @@ function makeSessionHandlers(sessionStates, configArgIndex, includeProviderMetad
28006
28913
  if (!config || typeof config !== "object") {
28007
28914
  return;
28008
28915
  }
28009
- const sessionSpan = startSpan({
28010
- name: "Copilot Session",
28011
- spanAttributes: { type: "task" /* TASK */ }
28012
- });
28916
+ const sessionSpan = startSpan(
28917
+ withSpanInstrumentationName(
28918
+ {
28919
+ name: "Copilot Session",
28920
+ spanAttributes: { type: "task" /* TASK */ }
28921
+ },
28922
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
28923
+ )
28924
+ );
28013
28925
  const metadata = {};
28014
28926
  if (config.model) {
28015
28927
  metadata["github_copilot.model"] = config.model;
@@ -28097,12 +29009,16 @@ var GitHubCopilotPlugin = class extends BasePlugin {
28097
29009
  };
28098
29010
 
28099
29011
  // src/instrumentation/plugins/flue-channels.ts
28100
- var flueChannels = defineChannels("@flue/runtime", {
28101
- createContext: channel({
28102
- channelName: "createFlueContext",
28103
- kind: "sync-stream"
28104
- })
28105
- });
29012
+ var flueChannels = defineChannels(
29013
+ "@flue/runtime",
29014
+ {
29015
+ createContext: channel({
29016
+ channelName: "createFlueContext",
29017
+ kind: "sync-stream"
29018
+ })
29019
+ },
29020
+ { instrumentationName: INSTRUMENTATION_NAMES.FLUE }
29021
+ );
28106
29022
 
28107
29023
  // src/instrumentation/plugins/flue-plugin.ts
28108
29024
  var FLUE_AUTO_STATE = /* @__PURE__ */ Symbol.for("braintrust.flue.auto-state");
@@ -28445,15 +29361,20 @@ var FlueObserveBridge = class {
28445
29361
  safeLog3(existing.span, { input, metadata });
28446
29362
  return;
28447
29363
  }
28448
- const span = startSpan({
28449
- name: `workflow:${workflowName}`,
28450
- spanAttributes: { type: "task" /* TASK */ },
28451
- startTime: eventTime(event.startedAt ?? event.timestamp),
28452
- event: {
28453
- input,
28454
- metadata
28455
- }
28456
- });
29364
+ const span = startSpan(
29365
+ withSpanInstrumentationName(
29366
+ {
29367
+ name: `workflow:${workflowName}`,
29368
+ spanAttributes: { type: "task" /* TASK */ },
29369
+ startTime: eventTime(event.startedAt ?? event.timestamp),
29370
+ event: {
29371
+ input,
29372
+ metadata
29373
+ }
29374
+ },
29375
+ INSTRUMENTATION_NAMES.FLUE
29376
+ )
29377
+ );
28457
29378
  this.runsById.set(event.runId, { metadata, span });
28458
29379
  }
28459
29380
  handleRunResume(event, ctx) {
@@ -28473,12 +29394,17 @@ var FlueObserveBridge = class {
28473
29394
  safeLog3(existing.span, { metadata });
28474
29395
  return;
28475
29396
  }
28476
- const span = startSpan({
28477
- name: `workflow:${workflowName}`,
28478
- spanAttributes: { type: "task" /* TASK */ },
28479
- startTime: eventTime(event.startedAt ?? event.timestamp),
28480
- event: { metadata }
28481
- });
29397
+ const span = startSpan(
29398
+ withSpanInstrumentationName(
29399
+ {
29400
+ name: `workflow:${workflowName}`,
29401
+ spanAttributes: { type: "task" /* TASK */ },
29402
+ startTime: eventTime(event.startedAt ?? event.timestamp),
29403
+ event: { metadata }
29404
+ },
29405
+ INSTRUMENTATION_NAMES.FLUE
29406
+ )
29407
+ );
28482
29408
  this.runsById.set(event.runId, { metadata, span });
28483
29409
  }
28484
29410
  handleRunEnd(event) {
@@ -29117,7 +30043,14 @@ function stateMatchesRun(state, runId) {
29117
30043
  return state.metadata["flue.run_id"] === runId;
29118
30044
  }
29119
30045
  function startFlueSpan(parent, args) {
29120
- return parent ? withCurrent(parent, () => startSpan(args)) : startSpan(args);
30046
+ return parent ? withCurrent(
30047
+ parent,
30048
+ () => startSpan(
30049
+ withSpanInstrumentationName(args, INSTRUMENTATION_NAMES.FLUE)
30050
+ )
30051
+ ) : startSpan(
30052
+ withSpanInstrumentationName(args, INSTRUMENTATION_NAMES.FLUE)
30053
+ );
29121
30054
  }
29122
30055
  function runWithCurrentSpanStore(span, next) {
29123
30056
  const state = _internalGetGlobalState();
@@ -29207,9 +30140,13 @@ var BraintrustLangChainCallbackHandler = class {
29207
30140
  ...this.options.debug ? { runId, parentRunId } : {}
29208
30141
  }
29209
30142
  };
29210
- let span = parentSpan.startSpan(args);
30143
+ const spanArgs = withSpanInstrumentationName(
30144
+ args,
30145
+ INSTRUMENTATION_NAMES.LANGCHAIN
30146
+ );
30147
+ let span = parentSpan.startSpan(spanArgs);
29211
30148
  if (!Object.is(this.options.logger, NOOP_SPAN) && Object.is(span, NOOP_SPAN)) {
29212
- span = initLogger().startSpan(args);
30149
+ span = initLogger().startSpan(spanArgs);
29213
30150
  }
29214
30151
  this.spans.set(runId, span);
29215
30152
  }
@@ -29506,16 +30443,20 @@ function isRecord(value) {
29506
30443
  }
29507
30444
 
29508
30445
  // src/instrumentation/plugins/langchain-channels.ts
29509
- var langChainChannels = defineChannels("@langchain/core", {
29510
- configure: channel({
29511
- channelName: "CallbackManager.configure",
29512
- kind: "sync-stream"
29513
- }),
29514
- configureSync: channel({
29515
- channelName: "CallbackManager._configureSync",
29516
- kind: "sync-stream"
29517
- })
29518
- });
30446
+ var langChainChannels = defineChannels(
30447
+ "@langchain/core",
30448
+ {
30449
+ configure: channel({
30450
+ channelName: "CallbackManager.configure",
30451
+ kind: "sync-stream"
30452
+ }),
30453
+ configureSync: channel({
30454
+ channelName: "CallbackManager._configureSync",
30455
+ kind: "sync-stream"
30456
+ })
30457
+ },
30458
+ { instrumentationName: INSTRUMENTATION_NAMES.LANGCHAIN }
30459
+ );
29519
30460
 
29520
30461
  // src/instrumentation/plugins/langchain-plugin.ts
29521
30462
  var LangChainPlugin = class extends BasePlugin {
@@ -29603,20 +30544,24 @@ function isBraintrustHandler(handler) {
29603
30544
  }
29604
30545
 
29605
30546
  // src/instrumentation/plugins/langsmith-channels.ts
29606
- var langSmithChannels = defineChannels("langsmith", {
29607
- createRun: channel({
29608
- channelName: "Client.createRun",
29609
- kind: "async"
29610
- }),
29611
- updateRun: channel({
29612
- channelName: "Client.updateRun",
29613
- kind: "async"
29614
- }),
29615
- batchIngestRuns: channel({
29616
- channelName: "Client.batchIngestRuns",
29617
- kind: "async"
29618
- })
29619
- });
30547
+ var langSmithChannels = defineChannels(
30548
+ "langsmith",
30549
+ {
30550
+ createRun: channel({
30551
+ channelName: "Client.createRun",
30552
+ kind: "async"
30553
+ }),
30554
+ updateRun: channel({
30555
+ channelName: "Client.updateRun",
30556
+ kind: "async"
30557
+ }),
30558
+ batchIngestRuns: channel({
30559
+ channelName: "Client.batchIngestRuns",
30560
+ kind: "async"
30561
+ })
30562
+ },
30563
+ { instrumentationName: INSTRUMENTATION_NAMES.LANGSMITH }
30564
+ );
29620
30565
 
29621
30566
  // src/instrumentation/plugins/langsmith-plugin.ts
29622
30567
  var MAX_COMPLETED_RUNS = 1e4;
@@ -29780,19 +30725,24 @@ var LangSmithPlugin = class extends BasePlugin {
29780
30725
  const traceId = stringValue2(ownValue(run, "trace_id")) ?? id;
29781
30726
  const parentId = stringValue2(ownValue(run, "parent_run_id")) ?? stringValue2(ownValue(ownValue(run, "parent_run"), "id"));
29782
30727
  const startTime = timestampSeconds(ownValue(run, "start_time"));
29783
- return startSpan({
29784
- name: stringValue2(ownValue(run, "name")) ?? "LangSmith run",
29785
- spanId: id,
29786
- parentSpanIds: {
29787
- parentSpanIds: parentId ? [parentId] : [],
29788
- rootSpanId: traceId
29789
- },
29790
- spanAttributes: {
29791
- type: mapRunType(ownValue(run, "run_type"))
29792
- },
29793
- ...startTime === void 0 ? {} : { startTime },
29794
- event: { id }
29795
- });
30728
+ return startSpan(
30729
+ withSpanInstrumentationName(
30730
+ {
30731
+ name: stringValue2(ownValue(run, "name")) ?? "LangSmith run",
30732
+ spanId: id,
30733
+ parentSpanIds: {
30734
+ parentSpanIds: parentId ? [parentId] : [],
30735
+ rootSpanId: traceId
30736
+ },
30737
+ spanAttributes: {
30738
+ type: mapRunType(ownValue(run, "run_type"))
30739
+ },
30740
+ ...startTime === void 0 ? {} : { startTime },
30741
+ event: { id }
30742
+ },
30743
+ INSTRUMENTATION_NAMES.LANGSMITH
30744
+ )
30745
+ );
29796
30746
  }
29797
30747
  logRun(span, run, previous, includeOutput) {
29798
30748
  const inputs = preferOwnValue(run, previous, "inputs");
@@ -30050,7 +31000,8 @@ var piCodingAgentChannels = defineChannels(
30050
31000
  channelName: "AgentSession.prompt",
30051
31001
  kind: "async"
30052
31002
  })
30053
- }
31003
+ },
31004
+ { instrumentationName: INSTRUMENTATION_NAMES.PI_CODING_AGENT }
30054
31005
  );
30055
31006
 
30056
31007
  // src/instrumentation/plugins/pi-coding-agent-plugin.ts
@@ -30134,14 +31085,19 @@ function startPiPromptRun(event, onFinalize) {
30134
31085
  ...session.model?.id || agent.state?.model?.id ? { model: session.model?.id ?? agent.state?.model?.id } : {},
30135
31086
  ...event.moduleVersion ? { "pi_coding_agent.version": event.moduleVersion } : {}
30136
31087
  };
30137
- const span = startSpan({
30138
- event: {
30139
- input: extractPromptInput(event.arguments[0], event.arguments[1]),
30140
- metadata
30141
- },
30142
- name: "AgentSession.prompt",
30143
- spanAttributes: { type: "task" /* TASK */ }
30144
- });
31088
+ const span = startSpan(
31089
+ withSpanInstrumentationName(
31090
+ {
31091
+ event: {
31092
+ input: extractPromptInput(event.arguments[0], event.arguments[1]),
31093
+ metadata
31094
+ },
31095
+ name: "AgentSession.prompt",
31096
+ spanAttributes: { type: "task" /* TASK */ }
31097
+ },
31098
+ INSTRUMENTATION_NAMES.PI_CODING_AGENT
31099
+ )
31100
+ );
30145
31101
  const streamPatchState = installPiStreamPatch(agent);
30146
31102
  const options = event.arguments[1];
30147
31103
  const promptText = event.arguments[0];
@@ -30311,15 +31267,20 @@ async function startPiLlmSpan(state, model, context, options) {
30311
31267
  ...extractToolMetadata(context.tools),
30312
31268
  "pi_coding_agent.operation": "agent.streamFn"
30313
31269
  };
30314
- const span = startSpan({
30315
- event: {
30316
- input: processInputAttachments(normalizePiContextInput(context)),
30317
- metadata
30318
- },
30319
- name: getLlmSpanName(model),
30320
- parent: await state.span.export(),
30321
- spanAttributes: { type: "llm" /* LLM */ }
30322
- });
31270
+ const span = startSpan(
31271
+ withSpanInstrumentationName(
31272
+ {
31273
+ event: {
31274
+ input: processInputAttachments(normalizePiContextInput(context)),
31275
+ metadata
31276
+ },
31277
+ name: getLlmSpanName(model),
31278
+ parent: await state.span.export(),
31279
+ spanAttributes: { type: "llm" /* LLM */ }
31280
+ },
31281
+ INSTRUMENTATION_NAMES.PI_CODING_AGENT
31282
+ )
31283
+ );
30323
31284
  const llmState = {
30324
31285
  finalized: false,
30325
31286
  metadata,
@@ -30487,15 +31448,20 @@ async function startPiToolSpan(state, event) {
30487
31448
  "pi_coding_agent.tool.name": event.toolName
30488
31449
  };
30489
31450
  try {
30490
- const span = startSpan({
30491
- event: {
30492
- input: event.args,
30493
- metadata
30494
- },
30495
- name: event.toolName || "tool",
30496
- parent: await state.span.export(),
30497
- spanAttributes: { type: "tool" /* TOOL */ }
30498
- });
31451
+ const span = startSpan(
31452
+ withSpanInstrumentationName(
31453
+ {
31454
+ event: {
31455
+ input: event.args,
31456
+ metadata
31457
+ },
31458
+ name: event.toolName || "tool",
31459
+ parent: await state.span.export(),
31460
+ spanAttributes: { type: "tool" /* TOOL */ }
31461
+ },
31462
+ INSTRUMENTATION_NAMES.PI_CODING_AGENT
31463
+ )
31464
+ );
30499
31465
  state.activeToolSpans.set(event.toolCallId, {
30500
31466
  restoreAutoInstrumentation,
30501
31467
  span
@@ -30927,20 +31893,24 @@ function logInstrumentationError4(context, error) {
30927
31893
  }
30928
31894
 
30929
31895
  // src/instrumentation/plugins/strands-agent-sdk-channels.ts
30930
- var strandsAgentSDKChannels = defineChannels("@strands-agents/sdk", {
30931
- agentStream: channel({
30932
- channelName: "Agent.stream",
30933
- kind: "sync-stream"
30934
- }),
30935
- graphStream: channel({
30936
- channelName: "Graph.stream",
30937
- kind: "sync-stream"
30938
- }),
30939
- swarmStream: channel({
30940
- channelName: "Swarm.stream",
30941
- kind: "sync-stream"
30942
- })
30943
- });
31896
+ var strandsAgentSDKChannels = defineChannels(
31897
+ "@strands-agents/sdk",
31898
+ {
31899
+ agentStream: channel({
31900
+ channelName: "Agent.stream",
31901
+ kind: "sync-stream"
31902
+ }),
31903
+ graphStream: channel({
31904
+ channelName: "Graph.stream",
31905
+ kind: "sync-stream"
31906
+ }),
31907
+ swarmStream: channel({
31908
+ channelName: "Swarm.stream",
31909
+ kind: "sync-stream"
31910
+ })
31911
+ },
31912
+ { instrumentationName: INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK }
31913
+ );
30944
31914
 
30945
31915
  // src/instrumentation/plugins/strands-agent-sdk-plugin.ts
30946
31916
  var MAX_STRANDS_STRING_ATTACHMENT_CACHE_ENTRIES = 32;
@@ -31095,22 +32065,32 @@ function startAgentStream(event, activeChildParents) {
31095
32065
  );
31096
32066
  const span = parentSpan ? withCurrent(
31097
32067
  parentSpan,
31098
- () => startSpan({
31099
- event: {
31100
- input,
31101
- metadata
32068
+ () => startSpan(
32069
+ withSpanInstrumentationName(
32070
+ {
32071
+ event: {
32072
+ input,
32073
+ metadata
32074
+ },
32075
+ name: formatAgentSpanName(agent),
32076
+ spanAttributes: { type: "task" /* TASK */ }
32077
+ },
32078
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
32079
+ )
32080
+ )
32081
+ ) : startSpan(
32082
+ withSpanInstrumentationName(
32083
+ {
32084
+ event: {
32085
+ input,
32086
+ metadata
32087
+ },
32088
+ name: formatAgentSpanName(agent),
32089
+ spanAttributes: { type: "task" /* TASK */ }
31102
32090
  },
31103
- name: formatAgentSpanName(agent),
31104
- spanAttributes: { type: "task" /* TASK */ }
31105
- })
31106
- ) : startSpan({
31107
- event: {
31108
- input,
31109
- metadata
31110
- },
31111
- name: formatAgentSpanName(agent),
31112
- spanAttributes: { type: "task" /* TASK */ }
31113
- });
32091
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
32092
+ )
32093
+ );
31114
32094
  return {
31115
32095
  activeTools: /* @__PURE__ */ new Map(),
31116
32096
  attachmentCache,
@@ -31132,22 +32112,32 @@ function startMultiAgentStream(event, operation, activeChildParents) {
31132
32112
  const input = processStrandsInputAttachments(event.arguments[0]);
31133
32113
  const span = parentSpan ? withCurrent(
31134
32114
  parentSpan,
31135
- () => startSpan({
31136
- event: {
31137
- input,
31138
- metadata
32115
+ () => startSpan(
32116
+ withSpanInstrumentationName(
32117
+ {
32118
+ event: {
32119
+ input,
32120
+ metadata
32121
+ },
32122
+ name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
32123
+ spanAttributes: { type: "task" /* TASK */ }
32124
+ },
32125
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
32126
+ )
32127
+ )
32128
+ ) : startSpan(
32129
+ withSpanInstrumentationName(
32130
+ {
32131
+ event: {
32132
+ input,
32133
+ metadata
32134
+ },
32135
+ name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
32136
+ spanAttributes: { type: "task" /* TASK */ }
31139
32137
  },
31140
- name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
31141
- spanAttributes: { type: "task" /* TASK */ }
31142
- })
31143
- ) : startSpan({
31144
- event: {
31145
- input,
31146
- metadata
31147
- },
31148
- name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
31149
- spanAttributes: { type: "task" /* TASK */ }
31150
- });
32138
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
32139
+ )
32140
+ );
31151
32141
  return {
31152
32142
  activeNodes: /* @__PURE__ */ new Map(),
31153
32143
  finalized: false,
@@ -31249,17 +32239,22 @@ function startModelSpan(state, event) {
31249
32239
  };
31250
32240
  const span = withCurrent(
31251
32241
  state.span,
31252
- () => startSpan({
31253
- event: {
31254
- input: Array.isArray(event.agent?.messages) ? processStrandsInputAttachments(
31255
- event.agent.messages,
31256
- state.attachmentCache
31257
- ) : void 0,
31258
- metadata
31259
- },
31260
- name: formatModelSpanName(model),
31261
- spanAttributes: { type: "llm" /* LLM */ }
31262
- })
32242
+ () => startSpan(
32243
+ withSpanInstrumentationName(
32244
+ {
32245
+ event: {
32246
+ input: Array.isArray(event.agent?.messages) ? processStrandsInputAttachments(
32247
+ event.agent.messages,
32248
+ state.attachmentCache
32249
+ ) : void 0,
32250
+ metadata
32251
+ },
32252
+ name: formatModelSpanName(model),
32253
+ spanAttributes: { type: "llm" /* LLM */ }
32254
+ },
32255
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
32256
+ )
32257
+ )
31263
32258
  );
31264
32259
  state.activeModel = {
31265
32260
  metadata,
@@ -31311,20 +32306,25 @@ function startToolSpan2(state, event) {
31311
32306
  const name = extractToolName3(toolUse, event.tool);
31312
32307
  const span = withCurrent(
31313
32308
  state.span,
31314
- () => startSpan({
31315
- event: {
31316
- input: toolUse?.input,
31317
- metadata: {
31318
- "gen_ai.tool.call.id": toolUse?.toolUseId,
31319
- "gen_ai.tool.name": name,
31320
- "strands.operation": "tool.call",
31321
- "strands.tool.name": name,
31322
- provider: "strands"
31323
- }
31324
- },
31325
- name: `tool: ${name}`,
31326
- spanAttributes: { type: "tool" /* TOOL */ }
31327
- })
32309
+ () => startSpan(
32310
+ withSpanInstrumentationName(
32311
+ {
32312
+ event: {
32313
+ input: toolUse?.input,
32314
+ metadata: {
32315
+ "gen_ai.tool.call.id": toolUse?.toolUseId,
32316
+ "gen_ai.tool.name": name,
32317
+ "strands.operation": "tool.call",
32318
+ "strands.tool.name": name,
32319
+ provider: "strands"
32320
+ }
32321
+ },
32322
+ name: `tool: ${name}`,
32323
+ spanAttributes: { type: "tool" /* TOOL */ }
32324
+ },
32325
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
32326
+ )
32327
+ )
31328
32328
  );
31329
32329
  state.activeTools.set(key, {
31330
32330
  span,
@@ -31395,11 +32395,16 @@ function startNodeSpan(state, event, activeChildParents) {
31395
32395
  };
31396
32396
  const span = withCurrent(
31397
32397
  state.span,
31398
- () => startSpan({
31399
- event: { metadata },
31400
- name: `node: ${nodeId}`,
31401
- spanAttributes: { type: "task" /* TASK */ }
31402
- })
32398
+ () => startSpan(
32399
+ withSpanInstrumentationName(
32400
+ {
32401
+ event: { metadata },
32402
+ name: `node: ${nodeId}`,
32403
+ spanAttributes: { type: "task" /* TASK */ }
32404
+ },
32405
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
32406
+ )
32407
+ )
31403
32408
  );
31404
32409
  const nodeState = {
31405
32410
  ...child ? { child } : {},
@@ -33127,6 +34132,12 @@ var wrapAgentClass = (AgentClass, options = {}) => {
33127
34132
  const original = Reflect.get(instanceTarget, prop, instanceTarget);
33128
34133
  if (harnessAgent && typeof original === "function") {
33129
34134
  switch (prop) {
34135
+ case "createSession":
34136
+ return wrapHarnessAgentCreateSession(
34137
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
34138
+ original,
34139
+ harnessAgent
34140
+ );
33130
34141
  case "generate":
33131
34142
  return wrapHarnessAgentGenerate(
33132
34143
  original,
@@ -33176,6 +34187,19 @@ var wrapAgentClass = (AgentClass, options = {}) => {
33176
34187
  }
33177
34188
  });
33178
34189
  };
34190
+ var wrapHarnessAgentCreateSession = (createSession, instance) => {
34191
+ const wrapper = function(params) {
34192
+ return harnessAgentChannels.createSession.tracePromise(
34193
+ () => params === void 0 ? createSession.call(instance) : createSession.call(instance, params),
34194
+ createAISDKChannelContext(params ?? {}, { self: instance })
34195
+ );
34196
+ };
34197
+ Object.defineProperty(wrapper, "name", {
34198
+ value: "HarnessAgent.createSession",
34199
+ writable: false
34200
+ });
34201
+ return wrapper;
34202
+ };
33179
34203
  var wrapHarnessAgentGenerate = (generate, instance, channel2, name, options) => makeGenerateTextWrapper(
33180
34204
  channel2,
33181
34205
  name,
@@ -33445,12 +34469,17 @@ var BraintrustLanguageModelWrapper = class {
33445
34469
  // For the first cut, do not support custom span_info arguments. We can
33446
34470
  // propagate those via async local storage
33447
34471
  async doGenerate(options) {
33448
- const span = startSpan({
33449
- name: "Chat Completion",
33450
- spanAttributes: {
33451
- type: "llm"
33452
- }
33453
- });
34472
+ const span = startSpan(
34473
+ withSpanInstrumentationName(
34474
+ {
34475
+ name: "Chat Completion",
34476
+ spanAttributes: {
34477
+ type: "llm"
34478
+ }
34479
+ },
34480
+ INSTRUMENTATION_NAMES.AI_SDK
34481
+ )
34482
+ );
33454
34483
  const { prompt, mode, ...rest } = options;
33455
34484
  const startTime = getCurrentUnixTimestamp();
33456
34485
  try {
@@ -33481,12 +34510,17 @@ var BraintrustLanguageModelWrapper = class {
33481
34510
  async doStream(options) {
33482
34511
  const { prompt, mode, ...rest } = options;
33483
34512
  const startTime = getCurrentUnixTimestamp();
33484
- const span = startSpan({
33485
- name: "Chat Completion",
33486
- spanAttributes: {
33487
- type: "llm"
33488
- }
33489
- });
34513
+ const span = startSpan(
34514
+ withSpanInstrumentationName(
34515
+ {
34516
+ name: "Chat Completion",
34517
+ spanAttributes: {
34518
+ type: "llm"
34519
+ }
34520
+ },
34521
+ INSTRUMENTATION_NAMES.AI_SDK
34522
+ )
34523
+ );
33490
34524
  span.log({
33491
34525
  input: postProcessPrompt(prompt),
33492
34526
  metadata: {
@@ -33841,7 +34875,9 @@ function BraintrustMiddleware(config = {}) {
33841
34875
  }
33842
34876
  }
33843
34877
  };
33844
- const span = startSpan(spanArgs);
34878
+ const span = startSpan(
34879
+ withSpanInstrumentationName(spanArgs, INSTRUMENTATION_NAMES.AI_SDK)
34880
+ );
33845
34881
  try {
33846
34882
  const result = await doGenerate();
33847
34883
  const metadata = {};
@@ -33903,7 +34939,9 @@ function BraintrustMiddleware(config = {}) {
33903
34939
  }
33904
34940
  }
33905
34941
  };
33906
- const span = startSpan(spanArgs);
34942
+ const span = startSpan(
34943
+ withSpanInstrumentationName(spanArgs, INSTRUMENTATION_NAMES.AI_SDK)
34944
+ );
33907
34945
  try {
33908
34946
  const { stream, ...rest } = await doStream();
33909
34947
  const textChunks = [];
@@ -34110,7 +35148,12 @@ var EveBridge = class {
34110
35148
  };
34111
35149
  const span = withCurrent(
34112
35150
  NOOP_SPAN,
34113
- () => _internalStartSpanWithInitialMerge({ ...args, startTime })
35151
+ () => _internalStartSpanWithInitialMerge(
35152
+ withSpanInstrumentationName(
35153
+ { ...args, startTime },
35154
+ INSTRUMENTATION_NAMES.EVE
35155
+ )
35156
+ )
34114
35157
  );
34115
35158
  if (typeof rowId !== "string") {
34116
35159
  return span;
@@ -35884,17 +36927,20 @@ var BraintrustObservabilityExporter = class {
35884
36927
  }
35885
36928
  onStart(exported) {
35886
36929
  if (this.spans.has(exported.id)) return;
35887
- const args = {
35888
- name: exported.name,
35889
- spanAttributes: { type: spanTypeFor(exported.type) },
35890
- startTime: epochSeconds(exported.startTime),
35891
- // Use the Mastra span id as the Braintrust row id so that
35892
- // `logFeedback({ id: <mastra span id> })` (and Mastra's score events)
35893
- // attach to the right row. Without this, `SpanImpl` auto-generates a
35894
- // row id (`this._id = eventId ?? idGenerator.getSpanId()`) that no
35895
- // external caller could know.
35896
- event: { id: exported.id }
35897
- };
36930
+ const args = withSpanInstrumentationName(
36931
+ {
36932
+ name: exported.name,
36933
+ spanAttributes: { type: spanTypeFor(exported.type) },
36934
+ startTime: epochSeconds(exported.startTime),
36935
+ // Use the Mastra span id as the Braintrust row id so that
36936
+ // `logFeedback({ id: <mastra span id> })` (and Mastra's score events)
36937
+ // attach to the right row. Without this, `SpanImpl` auto-generates a
36938
+ // row id (`this._id = eventId ?? idGenerator.getSpanId()`) that no
36939
+ // external caller could know.
36940
+ event: { id: exported.id }
36941
+ },
36942
+ INSTRUMENTATION_NAMES.MASTRA
36943
+ );
35898
36944
  const parentRecord = exported.parentSpanId ? this.spans.get(exported.parentSpanId) : void 0;
35899
36945
  if (!this.capturedParent) {
35900
36946
  const probe = currentSpan();
@@ -41280,26 +42326,30 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
41280
42326
  }
41281
42327
  }
41282
42328
  })();
42329
+ let timeoutId;
42330
+ let abortHandler;
42331
+ const cleanupCancellation = () => {
42332
+ if (timeoutId !== void 0) {
42333
+ clearTimeout(timeoutId);
42334
+ timeoutId = void 0;
42335
+ }
42336
+ if (abortHandler && evaluator.signal) {
42337
+ evaluator.signal.removeEventListener("abort", abortHandler);
42338
+ abortHandler = void 0;
42339
+ }
42340
+ };
41283
42341
  const cancel = async () => {
41284
42342
  await new Promise((_, reject2) => {
41285
42343
  if (cancelled) {
41286
42344
  reject2(new InternalAbortError("Evaluator already cancelled"));
41287
42345
  return;
41288
42346
  }
41289
- let timeoutId;
41290
- let abortHandler;
41291
42347
  const rejectOnce = (error) => {
41292
42348
  if (cancelled) {
41293
42349
  return;
41294
42350
  }
41295
42351
  cancelled = true;
41296
- if (timeoutId) {
41297
- clearTimeout(timeoutId);
41298
- timeoutId = void 0;
41299
- }
41300
- if (abortHandler && evaluator.signal) {
41301
- evaluator.signal.removeEventListener("abort", abortHandler);
41302
- }
42352
+ cleanupCancellation();
41303
42353
  reject2(error);
41304
42354
  };
41305
42355
  if (evaluator.timeout) {
@@ -41339,6 +42389,7 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
41339
42389
  }
41340
42390
  throw e;
41341
42391
  } finally {
42392
+ cleanupCancellation();
41342
42393
  if (!collectResults) {
41343
42394
  collectedResults.length = 0;
41344
42395
  }