braintrust 3.24.0 → 3.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dev/dist/index.d.mts +5 -0
  2. package/dev/dist/index.d.ts +5 -0
  3. package/dev/dist/index.js +2614 -1567
  4. package/dev/dist/index.mjs +2037 -990
  5. package/dist/apply-auto-instrumentation.js +200 -199
  6. package/dist/apply-auto-instrumentation.mjs +8 -7
  7. package/dist/auto-instrumentations/bundler/esbuild.cjs +596 -462
  8. package/dist/auto-instrumentations/bundler/esbuild.mjs +2 -2
  9. package/dist/auto-instrumentations/bundler/next.cjs +596 -462
  10. package/dist/auto-instrumentations/bundler/next.mjs +3 -3
  11. package/dist/auto-instrumentations/bundler/rollup.cjs +596 -462
  12. package/dist/auto-instrumentations/bundler/rollup.mjs +2 -2
  13. package/dist/auto-instrumentations/bundler/vite.cjs +596 -462
  14. package/dist/auto-instrumentations/bundler/vite.mjs +2 -2
  15. package/dist/auto-instrumentations/bundler/webpack-loader.cjs +596 -462
  16. package/dist/auto-instrumentations/bundler/webpack.cjs +596 -462
  17. package/dist/auto-instrumentations/bundler/webpack.mjs +3 -3
  18. package/dist/auto-instrumentations/{chunk-BURMPO7L.mjs → chunk-7P6563SW.mjs} +1 -1
  19. package/dist/auto-instrumentations/{chunk-F43DNLPD.mjs → chunk-CZ24KNHT.mjs} +569 -442
  20. package/dist/auto-instrumentations/{chunk-GSZHTAQW.mjs → chunk-JPVCUKTY.mjs} +30 -21
  21. package/dist/auto-instrumentations/hook.mjs +648 -476
  22. package/dist/auto-instrumentations/index.cjs +568 -442
  23. package/dist/auto-instrumentations/index.mjs +1 -1
  24. package/dist/browser.d.mts +7 -0
  25. package/dist/browser.d.ts +7 -0
  26. package/dist/browser.js +2022 -971
  27. package/dist/browser.mjs +2022 -971
  28. package/dist/{chunk-XE5FS7QY.mjs → chunk-2SANLSWX.mjs} +1375 -597
  29. package/dist/{chunk-7F6GCRHH.mjs → chunk-ABR2QWDP.mjs} +702 -456
  30. package/dist/{chunk-SU6EHKJV.js → chunk-GSIDVFE6.js} +2176 -1398
  31. package/dist/{chunk-7AUY2XWX.js → chunk-P25IOOU4.js} +704 -458
  32. package/dist/cli.js +2005 -958
  33. package/dist/edge-light.js +2022 -971
  34. package/dist/edge-light.mjs +2022 -971
  35. package/dist/index.d.mts +7 -0
  36. package/dist/index.d.ts +7 -0
  37. package/dist/index.js +447 -402
  38. package/dist/index.mjs +72 -27
  39. package/dist/instrumentation/index.d.mts +5 -0
  40. package/dist/instrumentation/index.d.ts +5 -0
  41. package/dist/instrumentation/index.js +1990 -981
  42. package/dist/instrumentation/index.mjs +1990 -981
  43. package/dist/vitest-evals-reporter.js +16 -16
  44. package/dist/vitest-evals-reporter.mjs +2 -2
  45. package/dist/workerd.js +2022 -971
  46. package/dist/workerd.mjs +2022 -971
  47. package/package.json +2 -2
package/dist/browser.mjs CHANGED
@@ -4826,7 +4826,51 @@ var SpanCache = class {
4826
4826
  };
4827
4827
 
4828
4828
  // src/span-origin.ts
4829
- var SDK_VERSION = true ? "3.24.0" : "0.0.0";
4829
+ var INSTRUMENTATION_NAMES = {
4830
+ AI_SDK: "ai-sdk",
4831
+ ANTHROPIC: "anthropic",
4832
+ BEDROCK_RUNTIME: "bedrock-runtime",
4833
+ BRAINTRUST_JS_LOGGER: "braintrust-js-logger",
4834
+ CLAUDE_AGENT_SDK: "claude-agent-sdk",
4835
+ COHERE: "cohere",
4836
+ CURSOR_SDK: "cursor-sdk",
4837
+ EVE: "eve",
4838
+ FLUE: "flue",
4839
+ GENKIT: "genkit",
4840
+ GITHUB_COPILOT: "github-copilot",
4841
+ GOOGLE_ADK: "google-adk",
4842
+ GOOGLE_GENAI: "google-genai",
4843
+ GROQ: "groq",
4844
+ HUGGINGFACE: "huggingface",
4845
+ LANGCHAIN: "langchain",
4846
+ LANGSMITH: "langsmith",
4847
+ MASTRA: "mastra",
4848
+ MISTRAL: "mistral",
4849
+ OPENAI: "openai",
4850
+ OPENAI_AGENTS: "openai-agents",
4851
+ OPENAI_CODEX: "openai-codex",
4852
+ OPENROUTER: "openrouter",
4853
+ OPENROUTER_AGENT: "openrouter-agent",
4854
+ PI_CODING_AGENT: "pi-coding-agent",
4855
+ STRANDS_AGENT_SDK: "strands-agent-sdk"
4856
+ };
4857
+ var INTERNAL_SPAN_INSTRUMENTATION_NAME = /* @__PURE__ */ Symbol.for(
4858
+ "braintrust.spanInstrumentationName"
4859
+ );
4860
+ var SDK_VERSION = true ? "3.25.0" : "0.0.0";
4861
+ function withSpanInstrumentationName(args, instrumentationName) {
4862
+ return {
4863
+ ...args,
4864
+ [INTERNAL_SPAN_INSTRUMENTATION_NAME]: instrumentationName
4865
+ };
4866
+ }
4867
+ function getSpanInstrumentationName(args) {
4868
+ if (typeof args !== "object" || args === null) {
4869
+ return void 0;
4870
+ }
4871
+ const value = args[INTERNAL_SPAN_INSTRUMENTATION_NAME];
4872
+ return isSpanInstrumentationName(value) ? value : void 0;
4873
+ }
4830
4874
  function detectSpanOriginEnvironment(explicit) {
4831
4875
  if (explicit) return explicit;
4832
4876
  const envType = isomorph_default.getEnv("BRAINTRUST_ENVIRONMENT_TYPE");
@@ -4898,6 +4942,9 @@ function mergeSpanOriginContext(context, instrumentationName, environment) {
4898
4942
  };
4899
4943
  return next;
4900
4944
  }
4945
+ function isSpanInstrumentationName(value) {
4946
+ return Object.values(INSTRUMENTATION_NAMES).some((name) => name === value);
4947
+ }
4901
4948
  function firstPresent(entries) {
4902
4949
  return entries.find(([key]) => Boolean(isomorph_default.getEnv(key)))?.[1];
4903
4950
  }
@@ -5192,6 +5239,7 @@ var BraintrustState = class _BraintrustState {
5192
5239
  });
5193
5240
  this.spanCache = new SpanCache({ disabled: loginParams.disableSpanCache });
5194
5241
  this.spanOriginEnvironment = detectSpanOriginEnvironment();
5242
+ this._internalSetTraceContextSigningSecret(loginParams.apiKey);
5195
5243
  }
5196
5244
  loginParams;
5197
5245
  id;
@@ -5229,6 +5277,18 @@ var BraintrustState = class _BraintrustState {
5229
5277
  _contextManager = null;
5230
5278
  _otelFlushCallback = null;
5231
5279
  spanOriginEnvironment;
5280
+ traceContextSigningSecret;
5281
+ /** @internal */
5282
+ _internalSetTraceContextSigningSecret(secret) {
5283
+ const normalizedSecret = secret?.trim();
5284
+ if (normalizedSecret) {
5285
+ this.traceContextSigningSecret = normalizedSecret;
5286
+ }
5287
+ }
5288
+ /** @internal */
5289
+ _internalGetTraceContextSigningSecret() {
5290
+ return (this.traceContextSigningSecret ?? this.loginToken ?? isomorph_default.getEnv("BRAINTRUST_API_KEY"))?.trim();
5291
+ }
5232
5292
  resetLoginInfo() {
5233
5293
  this.appUrl = null;
5234
5294
  this.appPublicUrl = null;
@@ -5289,6 +5349,7 @@ var BraintrustState = class _BraintrustState {
5289
5349
  this.gitMetadataSettings = other.gitMetadataSettings;
5290
5350
  this.debugLogLevel = other.debugLogLevel;
5291
5351
  this.debugLogLevelConfigured = other.debugLogLevelConfigured;
5352
+ this.traceContextSigningSecret = other.traceContextSigningSecret;
5292
5353
  setGlobalDebugLogLevel(
5293
5354
  this.debugLogLevelConfigured ? this.debugLogLevel ?? false : void 0
5294
5355
  );
@@ -5376,6 +5437,7 @@ var BraintrustState = class _BraintrustState {
5376
5437
  return this.debugLogLevelConfigured;
5377
5438
  }
5378
5439
  async login(loginParams) {
5440
+ this._internalSetTraceContextSigningSecret(loginParams.apiKey);
5379
5441
  this.setDebugLogLevel(loginParams.debugLogLevel);
5380
5442
  if (this.apiUrl && !loginParams.forceLogin) {
5381
5443
  return;
@@ -7355,6 +7417,7 @@ function init(projectOrOptions, optionalOptions) {
7355
7417
  throw new Error("Cannot open and update an experiment at the same time");
7356
7418
  }
7357
7419
  const state = stateArg ?? _globalState;
7420
+ state._internalSetTraceContextSigningSecret(apiKey);
7358
7421
  state.enforceQueueSizeLimit(false);
7359
7422
  if (open) {
7360
7423
  if (isEmpty2(experiment)) {
@@ -7863,6 +7926,7 @@ function initLogger(options = {}) {
7863
7926
  project_id: projectId
7864
7927
  };
7865
7928
  const state = stateArg ?? _globalState;
7929
+ state._internalSetTraceContextSigningSecret(apiKey);
7866
7930
  state.setDebugLogLevel(debugLogLevel);
7867
7931
  state.spanOriginEnvironment = detectSpanOriginEnvironment(environment);
7868
7932
  state.enforceQueueSizeLimit(true);
@@ -8926,7 +8990,9 @@ function deepCopyEvent(event) {
8926
8990
  const ATTACHMENT_MARKER_KEY = "_bt_internal_saved_attachment_marker";
8927
8991
  const attachmentMarker = ++deepCopyEventMarkerCounter;
8928
8992
  const serialized = JSON.stringify(event, (_k, v) => {
8929
- if (v instanceof SpanImpl || v instanceof NoopSpan) {
8993
+ if (v instanceof Error) {
8994
+ return v.message;
8995
+ } else if (v instanceof SpanImpl || v instanceof NoopSpan) {
8930
8996
  return `<span>`;
8931
8997
  } else if (v instanceof Experiment2) {
8932
8998
  return `<experiment>`;
@@ -9594,6 +9660,7 @@ var SpanImpl = class _SpanImpl {
9594
9660
  constructor(args) {
9595
9661
  this._state = args.state;
9596
9662
  this._propagatedState = args.propagatedState;
9663
+ const instrumentationName = getSpanInstrumentationName(args) ?? INSTRUMENTATION_NAMES.BRAINTRUST_JS_LOGGER;
9597
9664
  const spanAttributes = args.spanAttributes ?? {};
9598
9665
  const rawEvent = args.event ?? {};
9599
9666
  const type = args.type ?? (args.parentSpanIds ? void 0 : args.defaultRootType);
@@ -9625,7 +9692,7 @@ var SpanImpl = class _SpanImpl {
9625
9692
  },
9626
9693
  context: mergeSpanOriginContext(
9627
9694
  { ...callerLocation },
9628
- "braintrust-js-logger",
9695
+ instrumentationName,
9629
9696
  this._state.spanOriginEnvironment
9630
9697
  ),
9631
9698
  span_attributes: {
@@ -11609,15 +11676,25 @@ function hasChoices(value) {
11609
11676
  function normalizeMetadata(metadata) {
11610
11677
  return isObject(metadata) ? metadata : void 0;
11611
11678
  }
11612
- function startSpanForEvent(config, event, channelName) {
11679
+ function startSpanForEvent(config, event, channelName, instrumentationName) {
11613
11680
  const { name, spanAttributes, spanInfoMetadata } = buildStartSpanArgs(
11614
11681
  config,
11615
11682
  event
11616
11683
  );
11617
- const span = startSpan({
11618
- name,
11619
- spanAttributes
11620
- });
11684
+ const spanArgs = withSpanInstrumentationName(
11685
+ {
11686
+ name,
11687
+ spanAttributes
11688
+ },
11689
+ instrumentationName
11690
+ );
11691
+ let span;
11692
+ try {
11693
+ span = config.startSpan?.(spanArgs) ?? startSpan(spanArgs);
11694
+ } catch (error) {
11695
+ debugLogger.error(`Error starting span for ${channelName}:`, error);
11696
+ span = startSpan(spanArgs);
11697
+ }
11621
11698
  const startTime = getCurrentUnixTimestamp();
11622
11699
  try {
11623
11700
  const { input, metadata } = config.extractInput(
@@ -11648,7 +11725,7 @@ function shouldTraceEvent(config, event, channelName) {
11648
11725
  return true;
11649
11726
  }
11650
11727
  }
11651
- function ensureSpanStateForEvent(states, config, event, channelName) {
11728
+ function ensureSpanStateForEvent(states, config, event, channelName, instrumentationName) {
11652
11729
  const key = event;
11653
11730
  const existing = states.get(key);
11654
11731
  if (existing) {
@@ -11657,11 +11734,16 @@ function ensureSpanStateForEvent(states, config, event, channelName) {
11657
11734
  if (!shouldTraceEvent(config, event, channelName)) {
11658
11735
  return void 0;
11659
11736
  }
11660
- const created = startSpanForEvent(config, event, channelName);
11737
+ const created = startSpanForEvent(
11738
+ config,
11739
+ event,
11740
+ channelName,
11741
+ instrumentationName
11742
+ );
11661
11743
  states.set(key, created);
11662
11744
  return created;
11663
11745
  }
11664
- function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelName) {
11746
+ function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelName, instrumentationName) {
11665
11747
  const state = _internalGetGlobalState();
11666
11748
  const startChannel = tracingChannel2.start;
11667
11749
  const contextManager = state?.contextManager;
@@ -11679,7 +11761,8 @@ function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelNam
11679
11761
  states,
11680
11762
  config,
11681
11763
  event,
11682
- channelName
11764
+ channelName,
11765
+ instrumentationName
11683
11766
  );
11684
11767
  return spanState ? contextManager.wrapSpanForStore(spanState.span) : currentSpanStore.getStore();
11685
11768
  }
@@ -11688,15 +11771,21 @@ function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelNam
11688
11771
  startChannel.unbindStore(currentSpanStore);
11689
11772
  };
11690
11773
  }
11691
- function logErrorAndEnd(states, event) {
11774
+ function logErrorAndEnd(states, event, channelName) {
11692
11775
  const spanData = states.get(event);
11693
11776
  if (!spanData) {
11694
11777
  return;
11695
11778
  }
11696
- spanData.span.log({
11697
- error: event.error.message
11698
- });
11699
- spanData.span.end();
11779
+ try {
11780
+ spanData.span.log({ error: event.error });
11781
+ } catch (error) {
11782
+ debugLogger.error(`Error logging failure for ${channelName}:`, error);
11783
+ }
11784
+ try {
11785
+ spanData.span.end();
11786
+ } catch (error) {
11787
+ debugLogger.error(`Error ending span for ${channelName}:`, error);
11788
+ }
11700
11789
  states.delete(event);
11701
11790
  }
11702
11791
  function runStreamingCompletionHook(args) {
@@ -11746,7 +11835,8 @@ function traceAsyncChannel(channel2, config) {
11746
11835
  tracingChannel2,
11747
11836
  states,
11748
11837
  config,
11749
- channelName
11838
+ channelName,
11839
+ channel2.instrumentationName
11750
11840
  );
11751
11841
  const handlers = {
11752
11842
  start: (event) => {
@@ -11757,7 +11847,8 @@ function traceAsyncChannel(channel2, config) {
11757
11847
  states,
11758
11848
  config,
11759
11849
  event,
11760
- channelName
11850
+ channelName,
11851
+ channel2.instrumentationName
11761
11852
  );
11762
11853
  },
11763
11854
  asyncEnd: (event) => {
@@ -11794,7 +11885,7 @@ function traceAsyncChannel(channel2, config) {
11794
11885
  }
11795
11886
  },
11796
11887
  error: (event) => {
11797
- logErrorAndEnd(states, event);
11888
+ logErrorAndEnd(states, event, channelName);
11798
11889
  }
11799
11890
  };
11800
11891
  tracingChannel2.subscribe(handlers);
@@ -11811,7 +11902,8 @@ function traceStreamingChannel(channel2, config) {
11811
11902
  tracingChannel2,
11812
11903
  states,
11813
11904
  config,
11814
- channelName
11905
+ channelName,
11906
+ channel2.instrumentationName
11815
11907
  );
11816
11908
  const handlers = {
11817
11909
  start: (event) => {
@@ -11822,7 +11914,8 @@ function traceStreamingChannel(channel2, config) {
11822
11914
  states,
11823
11915
  config,
11824
11916
  event,
11825
- channelName
11917
+ channelName,
11918
+ channel2.instrumentationName
11826
11919
  );
11827
11920
  },
11828
11921
  asyncEnd: (event) => {
@@ -11841,6 +11934,7 @@ function traceStreamingChannel(channel2, config) {
11841
11934
  }
11842
11935
  },
11843
11936
  onComplete: (chunks) => {
11937
+ let completion2;
11844
11938
  try {
11845
11939
  let output;
11846
11940
  let metrics;
@@ -11871,18 +11965,11 @@ function traceStreamingChannel(channel2, config) {
11871
11965
  } else if (metrics.time_to_first_token === void 0 && chunks.length > 0) {
11872
11966
  metrics.time_to_first_token = getCurrentUnixTimestamp() - startTime;
11873
11967
  }
11874
- runStreamingCompletionHook({
11875
- channelName,
11876
- chunks,
11877
- config,
11878
- endEvent: asyncEndEvent,
11968
+ completion2 = {
11879
11969
  ...metadata !== void 0 ? { metadata } : {},
11880
11970
  metrics,
11881
- output,
11882
- result: asyncEndEvent.result,
11883
- span,
11884
- startTime
11885
- });
11971
+ output
11972
+ };
11886
11973
  span.log({
11887
11974
  output,
11888
11975
  ...metadata !== void 0 ? { metadata } : {},
@@ -11894,11 +11981,49 @@ function traceStreamingChannel(channel2, config) {
11894
11981
  error
11895
11982
  );
11896
11983
  } finally {
11897
- span.end();
11984
+ try {
11985
+ span.end();
11986
+ } catch (error) {
11987
+ debugLogger.error(
11988
+ `Error ending span for ${channelName}:`,
11989
+ error
11990
+ );
11991
+ }
11898
11992
  states.delete(event);
11899
11993
  }
11994
+ if (completion2) {
11995
+ runStreamingCompletionHook({
11996
+ channelName,
11997
+ chunks,
11998
+ config,
11999
+ endEvent: asyncEndEvent,
12000
+ ...completion2.metadata !== void 0 ? { metadata: completion2.metadata } : {},
12001
+ metrics: completion2.metrics,
12002
+ output: completion2.output,
12003
+ result: asyncEndEvent.result,
12004
+ span,
12005
+ startTime
12006
+ });
12007
+ }
11900
12008
  },
11901
12009
  onError: (error) => {
12010
+ try {
12011
+ span.log({ error });
12012
+ } catch (loggingError) {
12013
+ debugLogger.error(
12014
+ `Error logging failure for ${channelName}:`,
12015
+ loggingError
12016
+ );
12017
+ }
12018
+ try {
12019
+ span.end();
12020
+ } catch (endingError) {
12021
+ debugLogger.error(
12022
+ `Error ending span for ${channelName}:`,
12023
+ endingError
12024
+ );
12025
+ }
12026
+ states.delete(event);
11902
12027
  runStreamingErrorHook({
11903
12028
  channelName,
11904
12029
  config,
@@ -11907,11 +12032,6 @@ function traceStreamingChannel(channel2, config) {
11907
12032
  span,
11908
12033
  startTime
11909
12034
  });
11910
- span.log({
11911
- error: error.message
11912
- });
11913
- span.end();
11914
- states.delete(event);
11915
12035
  }
11916
12036
  });
11917
12037
  return;
@@ -11926,6 +12046,7 @@ function traceStreamingChannel(channel2, config) {
11926
12046
  states.delete(event);
11927
12047
  return;
11928
12048
  }
12049
+ let completion;
11929
12050
  try {
11930
12051
  const output = config.extractOutput(
11931
12052
  asyncEndEvent.result,
@@ -11940,17 +12061,11 @@ function traceStreamingChannel(channel2, config) {
11940
12061
  asyncEndEvent.result,
11941
12062
  asyncEndEvent
11942
12063
  );
11943
- runStreamingCompletionHook({
11944
- channelName,
11945
- config,
11946
- endEvent: asyncEndEvent,
12064
+ completion = {
11947
12065
  ...normalizeMetadata(metadata) !== void 0 ? { metadata: normalizeMetadata(metadata) } : {},
11948
12066
  metrics,
11949
- output,
11950
- result: asyncEndEvent.result,
11951
- span,
11952
- startTime
11953
- });
12067
+ output
12068
+ };
11954
12069
  span.log({
11955
12070
  output,
11956
12071
  ...normalizeMetadata(metadata) !== void 0 ? { metadata: normalizeMetadata(metadata) } : {},
@@ -11959,12 +12074,30 @@ function traceStreamingChannel(channel2, config) {
11959
12074
  } catch (error) {
11960
12075
  debugLogger.error(`Error extracting output for ${channelName}:`, error);
11961
12076
  } finally {
11962
- span.end();
12077
+ try {
12078
+ span.end();
12079
+ } catch (error) {
12080
+ debugLogger.error(`Error ending span for ${channelName}:`, error);
12081
+ }
11963
12082
  states.delete(event);
11964
12083
  }
12084
+ if (completion) {
12085
+ runStreamingCompletionHook({
12086
+ channelName,
12087
+ config,
12088
+ endEvent: asyncEndEvent,
12089
+ ...completion.metadata !== void 0 ? { metadata: completion.metadata } : {},
12090
+ metrics: completion.metrics,
12091
+ output: completion.output,
12092
+ result: asyncEndEvent.result,
12093
+ span,
12094
+ startTime
12095
+ });
12096
+ }
11965
12097
  },
11966
12098
  error: (event) => {
11967
12099
  const spanData = states.get(event);
12100
+ logErrorAndEnd(states, event, channelName);
11968
12101
  if (spanData) {
11969
12102
  runStreamingErrorHook({
11970
12103
  channelName,
@@ -11975,7 +12108,6 @@ function traceStreamingChannel(channel2, config) {
11975
12108
  startTime: spanData.startTime
11976
12109
  });
11977
12110
  }
11978
- logErrorAndEnd(states, event);
11979
12111
  }
11980
12112
  };
11981
12113
  tracingChannel2.subscribe(handlers);
@@ -11992,7 +12124,8 @@ function traceSyncStreamChannel(channel2, config) {
11992
12124
  tracingChannel2,
11993
12125
  states,
11994
12126
  config,
11995
- channelName
12127
+ channelName,
12128
+ channel2.instrumentationName
11996
12129
  );
11997
12130
  const handlers = {
11998
12131
  start: (event) => {
@@ -12003,7 +12136,8 @@ function traceSyncStreamChannel(channel2, config) {
12003
12136
  states,
12004
12137
  config,
12005
12138
  event,
12006
- channelName
12139
+ channelName,
12140
+ channel2.instrumentationName
12007
12141
  );
12008
12142
  },
12009
12143
  end: (event) => {
@@ -12097,7 +12231,7 @@ function traceSyncStreamChannel(channel2, config) {
12097
12231
  handleResolvedResult(endEvent.result);
12098
12232
  },
12099
12233
  error: (event) => {
12100
- logErrorAndEnd(states, event);
12234
+ logErrorAndEnd(states, event, channelName);
12101
12235
  }
12102
12236
  };
12103
12237
  tracingChannel2.subscribe(handlers);
@@ -12276,7 +12410,8 @@ function processInputAttachments(input) {
12276
12410
  function channel(spec) {
12277
12411
  return spec;
12278
12412
  }
12279
- function defineChannels(pkg, channels) {
12413
+ function defineChannels(pkg, channels, options) {
12414
+ const { instrumentationName } = options;
12280
12415
  return Object.fromEntries(
12281
12416
  Object.entries(channels).map(([key, spec]) => {
12282
12417
  const fullChannelName = `orchestrion:${pkg}:${spec.channelName}`;
@@ -12289,6 +12424,7 @@ function defineChannels(pkg, channels) {
12289
12424
  key,
12290
12425
  {
12291
12426
  ...asyncSpec,
12427
+ instrumentationName,
12292
12428
  tracingChannel: tracingChannel3,
12293
12429
  tracePromise: (fn, context) => tracingChannel3().tracePromise(
12294
12430
  fn,
@@ -12306,6 +12442,7 @@ function defineChannels(pkg, channels) {
12306
12442
  key,
12307
12443
  {
12308
12444
  ...syncSpec,
12445
+ instrumentationName,
12309
12446
  tracingChannel: tracingChannel2,
12310
12447
  traceSync: (fn, context) => tracingChannel2().traceSync(
12311
12448
  fn,
@@ -12319,44 +12456,48 @@ function defineChannels(pkg, channels) {
12319
12456
  }
12320
12457
 
12321
12458
  // src/instrumentation/plugins/openai-channels.ts
12322
- var openAIChannels = defineChannels("openai", {
12323
- chatCompletionsCreate: channel({
12324
- channelName: "chat.completions.create",
12325
- kind: "async"
12326
- }),
12327
- embeddingsCreate: channel({
12328
- channelName: "embeddings.create",
12329
- kind: "async"
12330
- }),
12331
- betaChatCompletionsParse: channel({
12332
- channelName: "beta.chat.completions.parse",
12333
- kind: "async"
12334
- }),
12335
- betaChatCompletionsStream: channel({
12336
- channelName: "beta.chat.completions.stream",
12337
- kind: "sync-stream"
12338
- }),
12339
- moderationsCreate: channel({
12340
- channelName: "moderations.create",
12341
- kind: "async"
12342
- }),
12343
- responsesCreate: channel({
12344
- channelName: "responses.create",
12345
- kind: "async"
12346
- }),
12347
- responsesStream: channel({
12348
- channelName: "responses.stream",
12349
- kind: "sync-stream"
12350
- }),
12351
- responsesParse: channel({
12352
- channelName: "responses.parse",
12353
- kind: "async"
12354
- }),
12355
- responsesCompact: channel({
12356
- channelName: "responses.compact",
12357
- kind: "async"
12358
- })
12359
- });
12459
+ var openAIChannels = defineChannels(
12460
+ "openai",
12461
+ {
12462
+ chatCompletionsCreate: channel({
12463
+ channelName: "chat.completions.create",
12464
+ kind: "async"
12465
+ }),
12466
+ embeddingsCreate: channel({
12467
+ channelName: "embeddings.create",
12468
+ kind: "async"
12469
+ }),
12470
+ betaChatCompletionsParse: channel({
12471
+ channelName: "beta.chat.completions.parse",
12472
+ kind: "async"
12473
+ }),
12474
+ betaChatCompletionsStream: channel({
12475
+ channelName: "beta.chat.completions.stream",
12476
+ kind: "sync-stream"
12477
+ }),
12478
+ moderationsCreate: channel({
12479
+ channelName: "moderations.create",
12480
+ kind: "async"
12481
+ }),
12482
+ responsesCreate: channel({
12483
+ channelName: "responses.create",
12484
+ kind: "async"
12485
+ }),
12486
+ responsesStream: channel({
12487
+ channelName: "responses.stream",
12488
+ kind: "sync-stream"
12489
+ }),
12490
+ responsesParse: channel({
12491
+ channelName: "responses.parse",
12492
+ kind: "async"
12493
+ }),
12494
+ responsesCompact: channel({
12495
+ channelName: "responses.compact",
12496
+ kind: "async"
12497
+ })
12498
+ },
12499
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENAI }
12500
+ );
12360
12501
 
12361
12502
  // src/openai-utils.ts
12362
12503
  var BRAINTRUST_CACHED_STREAM_METRIC = "__braintrust_cached_metric";
@@ -12871,16 +13012,20 @@ function aggregateResponseStreamEvents(chunks, _streamResult, endEvent) {
12871
13012
  }
12872
13013
 
12873
13014
  // src/instrumentation/plugins/openai-codex-channels.ts
12874
- var openAICodexChannels = defineChannels("@openai/codex-sdk", {
12875
- run: channel({
12876
- channelName: "Thread.run",
12877
- kind: "async"
12878
- }),
12879
- runStreamed: channel({
12880
- channelName: "Thread.runStreamed",
12881
- kind: "async"
12882
- })
12883
- });
13015
+ var openAICodexChannels = defineChannels(
13016
+ "@openai/codex-sdk",
13017
+ {
13018
+ run: channel({
13019
+ channelName: "Thread.run",
13020
+ kind: "async"
13021
+ }),
13022
+ runStreamed: channel({
13023
+ channelName: "Thread.runStreamed",
13024
+ kind: "async"
13025
+ })
13026
+ },
13027
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENAI_CODEX }
13028
+ );
12884
13029
 
12885
13030
  // src/instrumentation/plugins/openai-codex-plugin.ts
12886
13031
  var PATCHED_STREAMED_TURN = /* @__PURE__ */ Symbol.for(
@@ -12968,10 +13113,15 @@ function startCodexRun(event, operation) {
12968
13113
  provider: "openai",
12969
13114
  ...event.moduleVersion ? { "openai_codex.version": event.moduleVersion } : {}
12970
13115
  };
12971
- const span = startSpan({
12972
- name: "OpenAI Codex",
12973
- spanAttributes: { type: "task" /* TASK */ }
12974
- });
13116
+ const span = startSpan(
13117
+ withSpanInstrumentationName(
13118
+ {
13119
+ name: "OpenAI Codex",
13120
+ spanAttributes: { type: "task" /* TASK */ }
13121
+ },
13122
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
13123
+ )
13124
+ );
12975
13125
  const startTime = getCurrentUnixTimestamp();
12976
13126
  safeLog(span, {
12977
13127
  input: sanitizedInput,
@@ -13120,7 +13270,12 @@ async function createCompletedItemSpan(state, item) {
13120
13270
  if (!spanArgs) {
13121
13271
  return;
13122
13272
  }
13123
- const span = startSpan(spanArgs.start);
13273
+ const span = startSpan(
13274
+ withSpanInstrumentationName(
13275
+ spanArgs.start,
13276
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
13277
+ )
13278
+ );
13124
13279
  safeLog(span, spanArgs.end);
13125
13280
  span.end();
13126
13281
  }
@@ -13162,15 +13317,20 @@ async function ensureActiveLlmSpan(state) {
13162
13317
  ...state.metadata["openai_codex.thread_id"] ? { "openai_codex.thread_id": state.metadata["openai_codex.thread_id"] } : {},
13163
13318
  "openai_codex.llm_sequence": sequence
13164
13319
  };
13165
- const span = startSpan({
13166
- event: {
13167
- ...sequence === 1 ? { input: state.input } : {},
13168
- metadata
13169
- },
13170
- name: "OpenAI Codex LLM",
13171
- parent: await state.span.export(),
13172
- spanAttributes: { type: "llm" /* LLM */ }
13173
- });
13320
+ const span = startSpan(
13321
+ withSpanInstrumentationName(
13322
+ {
13323
+ event: {
13324
+ ...sequence === 1 ? { input: state.input } : {},
13325
+ metadata
13326
+ },
13327
+ name: "OpenAI Codex LLM",
13328
+ parent: await state.span.export(),
13329
+ spanAttributes: { type: "llm" /* LLM */ }
13330
+ },
13331
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
13332
+ )
13333
+ );
13174
13334
  state.activeLlmSpan = {
13175
13335
  anonymousMessages: [],
13176
13336
  anonymousReasoning: [],
@@ -13216,7 +13376,15 @@ async function startCodexItemSpan(state, item) {
13216
13376
  if (!spanArgs) {
13217
13377
  return;
13218
13378
  }
13219
- state.activeItemSpans.set(itemId, startSpan(spanArgs.start));
13379
+ state.activeItemSpans.set(
13380
+ itemId,
13381
+ startSpan(
13382
+ withSpanInstrumentationName(
13383
+ spanArgs.start,
13384
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
13385
+ )
13386
+ )
13387
+ );
13220
13388
  }
13221
13389
  function updateCodexItem(state, item) {
13222
13390
  if (item.type === "agent_message" && typeof item.text === "string") {
@@ -13526,20 +13694,24 @@ function extractAnthropicCacheTokens(cacheReadTokens = 0, cacheCreationTokens =
13526
13694
  }
13527
13695
 
13528
13696
  // src/instrumentation/plugins/anthropic-channels.ts
13529
- var anthropicChannels = defineChannels("@anthropic-ai/sdk", {
13530
- messagesCreate: channel({
13531
- channelName: "messages.create",
13532
- kind: "async"
13533
- }),
13534
- betaMessagesCreate: channel({
13535
- channelName: "beta.messages.create",
13536
- kind: "async"
13537
- }),
13538
- betaMessagesToolRunner: channel({
13539
- channelName: "beta.messages.toolRunner",
13540
- kind: "sync-stream"
13541
- })
13542
- });
13697
+ var anthropicChannels = defineChannels(
13698
+ "@anthropic-ai/sdk",
13699
+ {
13700
+ messagesCreate: channel({
13701
+ channelName: "messages.create",
13702
+ kind: "async"
13703
+ }),
13704
+ betaMessagesCreate: channel({
13705
+ channelName: "beta.messages.create",
13706
+ kind: "async"
13707
+ }),
13708
+ betaMessagesToolRunner: channel({
13709
+ channelName: "beta.messages.toolRunner",
13710
+ kind: "sync-stream"
13711
+ })
13712
+ },
13713
+ { instrumentationName: INSTRUMENTATION_NAMES.ANTHROPIC }
13714
+ );
13543
13715
 
13544
13716
  // src/instrumentation/plugins/anthropic-plugin.ts
13545
13717
  var ANTHROPIC_TOOL_RUNNER_TOOL_WRAPPED = /* @__PURE__ */ Symbol.for(
@@ -13612,12 +13784,17 @@ var AnthropicPlugin = class extends BasePlugin {
13612
13784
  return;
13613
13785
  }
13614
13786
  const params = event.arguments[0] ?? {};
13615
- const span = startSpan({
13616
- name: "anthropic.beta.messages.toolRunner",
13617
- spanAttributes: {
13618
- type: "task" /* TASK */
13619
- }
13620
- });
13787
+ const span = startSpan(
13788
+ withSpanInstrumentationName(
13789
+ {
13790
+ name: "anthropic.beta.messages.toolRunner",
13791
+ spanAttributes: {
13792
+ type: "task" /* TASK */
13793
+ }
13794
+ },
13795
+ INSTRUMENTATION_NAMES.ANTHROPIC
13796
+ )
13797
+ );
13621
13798
  span.log({
13622
13799
  input: processAttachmentsInInput(
13623
13800
  coalesceInput(params.messages ?? [], params.system)
@@ -13758,19 +13935,22 @@ function wrapAnthropicToolRunnerTool(tool, index, state) {
13758
13935
  return finalizeError(error);
13759
13936
  }
13760
13937
  },
13761
- {
13762
- event: {
13763
- input: getAnthropicToolRunnerInput(args),
13764
- metadata: {
13765
- "gen_ai.tool.name": toolName,
13766
- provider: "anthropic"
13938
+ withSpanInstrumentationName(
13939
+ {
13940
+ event: {
13941
+ input: getAnthropicToolRunnerInput(args),
13942
+ metadata: {
13943
+ "gen_ai.tool.name": toolName,
13944
+ provider: "anthropic"
13945
+ }
13946
+ },
13947
+ name: `tool: ${toolName}`,
13948
+ spanAttributes: {
13949
+ type: "tool" /* TOOL */
13767
13950
  }
13768
13951
  },
13769
- name: `tool: ${toolName}`,
13770
- spanAttributes: {
13771
- type: "tool" /* TOOL */
13772
- }
13773
- }
13952
+ INSTRUMENTATION_NAMES.ANTHROPIC
13953
+ )
13774
13954
  );
13775
13955
  },
13776
13956
  writable: runDescriptor?.writable ?? true
@@ -14365,6 +14545,267 @@ function currentWorkflowAgentWrapperSpan() {
14365
14545
  return void 0;
14366
14546
  }
14367
14547
 
14548
+ // src/wrappers/ai-sdk/harness-agent-context.ts
14549
+ var BRAINTRUST_TURN_CONTEXT_KEY = "__braintrust_trace_context";
14550
+ var sessionTurnParents = /* @__PURE__ */ new WeakMap();
14551
+ var wrapperTurnParents = /* @__PURE__ */ new WeakMap();
14552
+ var patchedLifecycleMethods = /* @__PURE__ */ new WeakMap();
14553
+ var harnessTurnParentStore;
14554
+ function serializedTurnContext(value) {
14555
+ if (!isObject(value)) {
14556
+ return void 0;
14557
+ }
14558
+ const context = value[BRAINTRUST_TURN_CONTEXT_KEY];
14559
+ if (!isObject(context) || typeof context.parent !== "string" || typeof context.sessionId !== "string" || typeof context.signature !== "string") {
14560
+ return void 0;
14561
+ }
14562
+ const expectedSignature = signTurnContext({
14563
+ parent: context.parent,
14564
+ sessionId: context.sessionId
14565
+ });
14566
+ if (!expectedSignature || !isomorph_default.timingSafeEqual?.(context.signature, expectedSignature)) {
14567
+ return void 0;
14568
+ }
14569
+ const parent = SpanComponentsV4.fromStr(context.parent);
14570
+ if (!parent.data.row_id || !parent.data.root_span_id || !parent.data.span_id) {
14571
+ return void 0;
14572
+ }
14573
+ return {
14574
+ parent: context.parent,
14575
+ sessionId: context.sessionId
14576
+ };
14577
+ }
14578
+ function signTurnContext(context) {
14579
+ const secret = _internalGetGlobalState()._internalGetTraceContextSigningSecret();
14580
+ return secret ? isomorph_default.hmacSha256?.(
14581
+ secret,
14582
+ JSON.stringify([BRAINTRUST_TURN_CONTEXT_KEY, context])
14583
+ ) : void 0;
14584
+ }
14585
+ function continuationParentFromCreateSessionParams(params) {
14586
+ if (!isObject(params)) {
14587
+ return void 0;
14588
+ }
14589
+ const continuation = params.continueFrom ?? (isObject(params.resumeFrom) ? params.resumeFrom.continueFrom : void 0);
14590
+ const context = serializedTurnContext(continuation);
14591
+ if (!context) {
14592
+ return void 0;
14593
+ }
14594
+ if (params.sessionId !== context.sessionId) {
14595
+ return void 0;
14596
+ }
14597
+ return context.parent;
14598
+ }
14599
+ function exportSpanSynchronously(span) {
14600
+ const parentInfo = span.getParentInfo();
14601
+ if (!parentInfo) {
14602
+ return void 0;
14603
+ }
14604
+ const objectId = parentInfo.objectId.getSync().value;
14605
+ if (!objectId && !parentInfo.computeObjectMetadataArgs) {
14606
+ return void 0;
14607
+ }
14608
+ return new SpanComponentsV4({
14609
+ object_type: parentInfo.objectType,
14610
+ ...objectId ? { object_id: objectId } : {
14611
+ compute_object_metadata_args: parentInfo.computeObjectMetadataArgs ?? {}
14612
+ },
14613
+ row_id: span.id,
14614
+ root_span_id: span.rootSpanId,
14615
+ span_id: span.spanId
14616
+ }).toStr();
14617
+ }
14618
+ function exportedParent(parent) {
14619
+ return typeof parent === "string" ? parent : exportSpanSynchronously(parent);
14620
+ }
14621
+ function addSerializedContext(args) {
14622
+ if (!isObject(args.continuation) || args.sessionId === void 0) {
14623
+ return;
14624
+ }
14625
+ const parent = exportedParent(args.parent);
14626
+ if (!parent) {
14627
+ return;
14628
+ }
14629
+ const context = {
14630
+ parent,
14631
+ sessionId: args.sessionId
14632
+ };
14633
+ const signature = signTurnContext(context);
14634
+ if (!signature) {
14635
+ return;
14636
+ }
14637
+ Object.defineProperty(args.continuation, BRAINTRUST_TURN_CONTEXT_KEY, {
14638
+ configurable: true,
14639
+ enumerable: true,
14640
+ value: {
14641
+ ...context,
14642
+ signature
14643
+ },
14644
+ writable: true
14645
+ });
14646
+ }
14647
+ function lifecycleMethodDescriptor(session, method) {
14648
+ let owner = session;
14649
+ while (owner) {
14650
+ const descriptor = Object.getOwnPropertyDescriptor(owner, method);
14651
+ if (descriptor) {
14652
+ return { descriptor, owner };
14653
+ }
14654
+ owner = Object.getPrototypeOf(owner);
14655
+ }
14656
+ return void 0;
14657
+ }
14658
+ function patchLifecycleMethod(session, method) {
14659
+ let resolvedDescriptor;
14660
+ try {
14661
+ resolvedDescriptor = lifecycleMethodDescriptor(session, method);
14662
+ } catch {
14663
+ return;
14664
+ }
14665
+ if (!resolvedDescriptor || !("value" in resolvedDescriptor.descriptor) || typeof resolvedDescriptor.descriptor.value !== "function") {
14666
+ return;
14667
+ }
14668
+ const { descriptor, owner } = resolvedDescriptor;
14669
+ const patched = patchedLifecycleMethods.get(owner);
14670
+ if (patched?.has(method)) {
14671
+ return;
14672
+ }
14673
+ const original = descriptor.value;
14674
+ const replacement = function(...args) {
14675
+ const result = Reflect.apply(original, this, args);
14676
+ const addContext = (state) => {
14677
+ try {
14678
+ const parent = sessionTurnParents.get(this);
14679
+ if (!parent) {
14680
+ return;
14681
+ }
14682
+ const continuation = method === "suspendTurn" ? state : isObject(state) ? state.continueFrom : void 0;
14683
+ addSerializedContext({
14684
+ continuation,
14685
+ parent,
14686
+ sessionId: typeof this.sessionId === "string" ? this.sessionId : void 0
14687
+ });
14688
+ } catch {
14689
+ }
14690
+ };
14691
+ try {
14692
+ if (isObject(result) && typeof result.then === "function") {
14693
+ void Promise.resolve(result).then(addContext, () => {
14694
+ });
14695
+ } else {
14696
+ addContext(result);
14697
+ }
14698
+ } catch {
14699
+ }
14700
+ return result;
14701
+ };
14702
+ try {
14703
+ Object.defineProperty(owner, method, {
14704
+ ...descriptor,
14705
+ value: replacement
14706
+ });
14707
+ const ownerMethods = patched ?? /* @__PURE__ */ new Set();
14708
+ ownerMethods.add(method);
14709
+ if (!patched) {
14710
+ patchedLifecycleMethods.set(owner, ownerMethods);
14711
+ }
14712
+ } catch {
14713
+ }
14714
+ }
14715
+ function patchLifecycleMethods(session) {
14716
+ patchLifecycleMethod(session, "suspendTurn");
14717
+ patchLifecycleMethod(session, "detach");
14718
+ patchLifecycleMethod(session, "stop");
14719
+ }
14720
+ function registerHarnessTurnSpan(args) {
14721
+ if (!isObject(args.session)) {
14722
+ return;
14723
+ }
14724
+ const session = args.session;
14725
+ sessionTurnParents.set(session, args.span);
14726
+ wrapperTurnParents.set(args.span, args.span);
14727
+ patchLifecycleMethods(session);
14728
+ }
14729
+ function harnessContinuationParent(session) {
14730
+ return isObject(session) ? sessionTurnParents.get(session) : void 0;
14731
+ }
14732
+ function captureHarnessCreateSessionParent(params) {
14733
+ try {
14734
+ return continuationParentFromCreateSessionParams(params);
14735
+ } catch {
14736
+ return void 0;
14737
+ }
14738
+ }
14739
+ function registerHarnessSessionParent(session, parent) {
14740
+ if (!parent || !isObject(session)) {
14741
+ return;
14742
+ }
14743
+ const harnessSession = session;
14744
+ sessionTurnParents.set(harnessSession, parent);
14745
+ patchLifecycleMethods(harnessSession);
14746
+ }
14747
+ function currentHarnessTurnParent() {
14748
+ return harnessTurnParentStore?.getStore() ?? wrapperTurnParents.get(currentSpan());
14749
+ }
14750
+ function bindHarnessTurnParentToStart(tracingChannel2, parentFromEvent) {
14751
+ const startChannel = tracingChannel2.start;
14752
+ if (!startChannel) {
14753
+ return () => {
14754
+ };
14755
+ }
14756
+ harnessTurnParentStore ??= isomorph_default.newAsyncLocalStorage();
14757
+ const store = harnessTurnParentStore;
14758
+ startChannel.bindStore(
14759
+ store,
14760
+ (event) => parentFromEvent(event) ?? store.getStore()
14761
+ );
14762
+ return () => {
14763
+ startChannel.unbindStore(store);
14764
+ };
14765
+ }
14766
+ function startHarnessTurnChildSpan(parent, args) {
14767
+ const spanArgs = withSpanInstrumentationName(
14768
+ args,
14769
+ INSTRUMENTATION_NAMES.AI_SDK
14770
+ );
14771
+ return typeof parent === "string" ? startSpan({ ...spanArgs, parent }) : parent.startSpan(spanArgs);
14772
+ }
14773
+ function updateHarnessTurn(parent, update = {}) {
14774
+ if (!parent) {
14775
+ return;
14776
+ }
14777
+ const log3 = (event) => {
14778
+ if (typeof parent === "string") {
14779
+ updateSpan({ exported: parent, ...event });
14780
+ } else {
14781
+ parent.log(event);
14782
+ }
14783
+ };
14784
+ try {
14785
+ if (Object.prototype.hasOwnProperty.call(update, "output")) {
14786
+ log3({ output: null });
14787
+ }
14788
+ log3(update);
14789
+ } catch {
14790
+ }
14791
+ }
14792
+ function endHarnessTurn(parent) {
14793
+ const endTime = getCurrentUnixTimestamp();
14794
+ if (!parent) {
14795
+ return endTime;
14796
+ }
14797
+ try {
14798
+ const event = { metrics: { end: endTime } };
14799
+ if (typeof parent === "string") {
14800
+ updateSpan({ exported: parent, ...event });
14801
+ } else {
14802
+ parent.log(event);
14803
+ }
14804
+ } catch {
14805
+ }
14806
+ return endTime;
14807
+ }
14808
+
14368
14809
  // src/wrappers/ai-sdk/telemetry.ts
14369
14810
  function braintrustAISDKTelemetry() {
14370
14811
  const operations = /* @__PURE__ */ new Map();
@@ -14383,14 +14824,17 @@ function braintrustAISDKTelemetry() {
14383
14824
  console.error(`Error in Braintrust AI SDK telemetry ${name}:`, error);
14384
14825
  }
14385
14826
  };
14386
- const startChildSpan = (operationKey, name, type, event) => {
14827
+ const startChildSpan = (operationKey, name, type, event, parentOverride) => {
14387
14828
  const parent = operations.get(operationKey)?.span;
14388
- const spanArgs = {
14389
- name,
14390
- spanAttributes: { type },
14391
- ...event ? { event } : {}
14392
- };
14393
- const span = parent ? parent.startSpan(spanArgs) : startSpan(spanArgs);
14829
+ const spanArgs = withSpanInstrumentationName(
14830
+ {
14831
+ name,
14832
+ spanAttributes: { type },
14833
+ ...event ? { event } : {}
14834
+ },
14835
+ INSTRUMENTATION_NAMES.AI_SDK
14836
+ );
14837
+ const span = parentOverride ? startHarnessTurnChildSpan(parentOverride, spanArgs) : parent ? parent.startSpan(spanArgs) : startSpan(spanArgs);
14394
14838
  const state = operations.get(operationKey);
14395
14839
  if (state && type === "llm" /* LLM */) {
14396
14840
  state.hadModelChild = true;
@@ -14670,14 +15114,30 @@ function braintrustAISDKTelemetry() {
14670
15114
  const workflowAgent = operationName === "WorkflowAgent.stream";
14671
15115
  const wrapperSpan = workflowAgent ? currentWorkflowAgentWrapperSpan() : void 0;
14672
15116
  const ownsSpan = !wrapperSpan;
14673
- const span = ownsSpan ? startSpan({
14674
- name: operationName,
14675
- spanAttributes: { type: "function" /* FUNCTION */ }
14676
- }) : wrapperSpan;
15117
+ const harnessTurnParent = currentHarnessTurnParent();
15118
+ const span = ownsSpan ? harnessTurnParent ? startHarnessTurnChildSpan(
15119
+ harnessTurnParent,
15120
+ withSpanInstrumentationName(
15121
+ {
15122
+ name: operationName,
15123
+ spanAttributes: { type: "function" /* FUNCTION */ }
15124
+ },
15125
+ INSTRUMENTATION_NAMES.AI_SDK
15126
+ )
15127
+ ) : startSpan(
15128
+ withSpanInstrumentationName(
15129
+ {
15130
+ name: operationName,
15131
+ spanAttributes: { type: "function" /* FUNCTION */ }
15132
+ },
15133
+ INSTRUMENTATION_NAMES.AI_SDK
15134
+ )
15135
+ ) : wrapperSpan;
14677
15136
  const operationKey = createOperationKey(event, operationName);
14678
15137
  registerOperation({
14679
15138
  callId: event.callId,
14680
15139
  hadModelChild: false,
15140
+ harnessTurnParent,
14681
15141
  loggedInput: false,
14682
15142
  operationName,
14683
15143
  operationKey,
@@ -14918,7 +15378,8 @@ function braintrustAISDKTelemetry() {
14918
15378
  toolCallId,
14919
15379
  ...typeof event.toolCall.toolName === "string" ? { toolName: event.toolCall.toolName } : {}
14920
15380
  }
14921
- }
15381
+ },
15382
+ state?.harnessTurnParent
14922
15383
  );
14923
15384
  toolSpans.set(toolCallId, { operationKey, span });
14924
15385
  });
@@ -15154,92 +15615,102 @@ function finishOutput(result, operationName) {
15154
15615
  }
15155
15616
 
15156
15617
  // src/instrumentation/plugins/ai-sdk-channels.ts
15157
- var aiSDKChannels = defineChannels("ai", {
15158
- generateText: channel({
15159
- channelName: "generateText",
15160
- kind: "async"
15161
- }),
15162
- streamText: channel({
15163
- channelName: "streamText",
15164
- kind: "async"
15165
- }),
15166
- streamTextSync: channel({
15167
- channelName: "streamText.sync",
15168
- kind: "sync-stream"
15169
- }),
15170
- generateObject: channel({
15171
- channelName: "generateObject",
15172
- kind: "async"
15173
- }),
15174
- streamObject: channel({
15175
- channelName: "streamObject",
15176
- kind: "async"
15177
- }),
15178
- streamObjectSync: channel({
15179
- channelName: "streamObject.sync",
15180
- kind: "sync-stream"
15181
- }),
15182
- embed: channel(
15183
- {
15618
+ var aiSDKChannels = defineChannels(
15619
+ "ai",
15620
+ {
15621
+ generateText: channel({
15622
+ channelName: "generateText",
15623
+ kind: "async"
15624
+ }),
15625
+ streamText: channel({
15626
+ channelName: "streamText",
15627
+ kind: "async"
15628
+ }),
15629
+ streamTextSync: channel({
15630
+ channelName: "streamText.sync",
15631
+ kind: "sync-stream"
15632
+ }),
15633
+ generateObject: channel({
15634
+ channelName: "generateObject",
15635
+ kind: "async"
15636
+ }),
15637
+ streamObject: channel({
15638
+ channelName: "streamObject",
15639
+ kind: "async"
15640
+ }),
15641
+ streamObjectSync: channel({
15642
+ channelName: "streamObject.sync",
15643
+ kind: "sync-stream"
15644
+ }),
15645
+ embed: channel({
15184
15646
  channelName: "embed",
15185
15647
  kind: "async"
15186
- }
15187
- ),
15188
- embedMany: channel({
15189
- channelName: "embedMany",
15190
- kind: "async"
15191
- }),
15192
- rerank: channel({
15193
- channelName: "rerank",
15194
- kind: "async"
15195
- }),
15196
- agentGenerate: channel({
15197
- channelName: "Agent.generate",
15198
- kind: "async"
15199
- }),
15200
- agentStream: channel({
15201
- channelName: "Agent.stream",
15202
- kind: "async"
15203
- }),
15204
- agentStreamSync: channel({
15205
- channelName: "Agent.stream.sync",
15206
- kind: "sync-stream"
15207
- }),
15208
- toolLoopAgentGenerate: channel({
15209
- channelName: "ToolLoopAgent.generate",
15210
- kind: "async"
15211
- }),
15212
- toolLoopAgentStream: channel({
15213
- channelName: "ToolLoopAgent.stream",
15214
- kind: "async"
15215
- }),
15216
- workflowAgentStream: channel({
15217
- channelName: "WorkflowAgent.stream",
15218
- kind: "async"
15219
- }),
15220
- v7CreateTelemetryDispatcher: channel({
15221
- channelName: "createTelemetryDispatcher",
15222
- kind: "sync-stream"
15223
- })
15224
- });
15225
- var harnessAgentChannels = defineChannels("@ai-sdk/harness", {
15226
- generate: channel({
15227
- channelName: "HarnessAgent.generate",
15228
- kind: "async"
15229
- }),
15230
- stream: channel({
15231
- channelName: "HarnessAgent.stream",
15232
- kind: "async"
15233
- }),
15234
- continueGenerate: channel({
15235
- channelName: "HarnessAgent.continueGenerate",
15236
- kind: "async"
15237
- }),
15238
- continueStream: channel({
15239
- channelName: "HarnessAgent.continueStream",
15240
- kind: "async"
15241
- })
15242
- });
15648
+ }),
15649
+ embedMany: channel({
15650
+ channelName: "embedMany",
15651
+ kind: "async"
15652
+ }),
15653
+ rerank: channel({
15654
+ channelName: "rerank",
15655
+ kind: "async"
15656
+ }),
15657
+ agentGenerate: channel({
15658
+ channelName: "Agent.generate",
15659
+ kind: "async"
15660
+ }),
15661
+ agentStream: channel({
15662
+ channelName: "Agent.stream",
15663
+ kind: "async"
15664
+ }),
15665
+ agentStreamSync: channel({
15666
+ channelName: "Agent.stream.sync",
15667
+ kind: "sync-stream"
15668
+ }),
15669
+ toolLoopAgentGenerate: channel({
15670
+ channelName: "ToolLoopAgent.generate",
15671
+ kind: "async"
15672
+ }),
15673
+ toolLoopAgentStream: channel({
15674
+ channelName: "ToolLoopAgent.stream",
15675
+ kind: "async"
15676
+ }),
15677
+ workflowAgentStream: channel({
15678
+ channelName: "WorkflowAgent.stream",
15679
+ kind: "async"
15680
+ }),
15681
+ v7CreateTelemetryDispatcher: channel({
15682
+ channelName: "createTelemetryDispatcher",
15683
+ kind: "sync-stream"
15684
+ })
15685
+ },
15686
+ { instrumentationName: INSTRUMENTATION_NAMES.AI_SDK }
15687
+ );
15688
+ var harnessAgentChannels = defineChannels(
15689
+ "@ai-sdk/harness",
15690
+ {
15691
+ createSession: channel({
15692
+ channelName: "HarnessAgent.createSession",
15693
+ kind: "async"
15694
+ }),
15695
+ generate: channel({
15696
+ channelName: "HarnessAgent.generate",
15697
+ kind: "async"
15698
+ }),
15699
+ stream: channel({
15700
+ channelName: "HarnessAgent.stream",
15701
+ kind: "async"
15702
+ }),
15703
+ continueGenerate: channel({
15704
+ channelName: "HarnessAgent.continueGenerate",
15705
+ kind: "async"
15706
+ }),
15707
+ continueStream: channel({
15708
+ channelName: "HarnessAgent.continueStream",
15709
+ kind: "async"
15710
+ })
15711
+ },
15712
+ { instrumentationName: INSTRUMENTATION_NAMES.AI_SDK }
15713
+ );
15243
15714
 
15244
15715
  // src/instrumentation/plugins/ai-sdk-plugin.ts
15245
15716
  var DEFAULT_DENY_OUTPUT_PATHS = [
@@ -15316,6 +15787,17 @@ var AISDKPlugin = class extends BasePlugin {
15316
15787
  subscribeToAISDK() {
15317
15788
  const denyOutputPaths = this.config.denyOutputPaths || DEFAULT_DENY_OUTPUT_PATHS;
15318
15789
  this.unsubscribers.push(subscribeToAISDKV7TelemetryDispatcher());
15790
+ this.unsubscribers.push(subscribeToHarnessAgentCreateSession());
15791
+ this.unsubscribers.push(
15792
+ subscribeToHarnessContinuation(
15793
+ harnessAgentChannels.continueGenerate,
15794
+ denyOutputPaths
15795
+ ),
15796
+ subscribeToHarnessContinuation(
15797
+ harnessAgentChannels.continueStream,
15798
+ denyOutputPaths
15799
+ )
15800
+ );
15319
15801
  this.unsubscribers.push(
15320
15802
  traceStreamingChannel(aiSDKChannels.generateText, {
15321
15803
  name: "generateText",
@@ -15511,8 +15993,9 @@ var AISDKPlugin = class extends BasePlugin {
15511
15993
  this.unsubscribers.push(
15512
15994
  traceStreamingChannel(harnessAgentChannels.generate, {
15513
15995
  name: "HarnessAgent.generate",
15996
+ startSpan: _internalStartSpanWithInitialMerge,
15514
15997
  type: "task" /* TASK */,
15515
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
15998
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
15516
15999
  extractOutput: (result, endEvent) => processAISDKOutput(
15517
16000
  result,
15518
16001
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -15524,8 +16007,9 @@ var AISDKPlugin = class extends BasePlugin {
15524
16007
  this.unsubscribers.push(
15525
16008
  traceStreamingChannel(harnessAgentChannels.stream, {
15526
16009
  name: "HarnessAgent.stream",
16010
+ startSpan: _internalStartSpanWithInitialMerge,
15527
16011
  type: "task" /* TASK */,
15528
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
16012
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
15529
16013
  extractOutput: (result, endEvent) => processAISDKOutput(
15530
16014
  result,
15531
16015
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -15550,8 +16034,10 @@ var AISDKPlugin = class extends BasePlugin {
15550
16034
  this.unsubscribers.push(
15551
16035
  traceStreamingChannel(harnessAgentChannels.continueGenerate, {
15552
16036
  name: "HarnessAgent.continueGenerate",
16037
+ shouldTrace: (args) => !harnessContinuationParent(harnessSessionFromArguments(args)),
16038
+ startSpan: _internalStartSpanWithInitialMerge,
15553
16039
  type: "task" /* TASK */,
15554
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
16040
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
15555
16041
  extractOutput: (result, endEvent) => processAISDKOutput(
15556
16042
  result,
15557
16043
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -15563,8 +16049,10 @@ var AISDKPlugin = class extends BasePlugin {
15563
16049
  this.unsubscribers.push(
15564
16050
  traceStreamingChannel(harnessAgentChannels.continueStream, {
15565
16051
  name: "HarnessAgent.continueStream",
16052
+ shouldTrace: (args) => !harnessContinuationParent(harnessSessionFromArguments(args)),
16053
+ startSpan: _internalStartSpanWithInitialMerge,
15566
16054
  type: "task" /* TASK */,
15567
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
16055
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
15568
16056
  extractOutput: (result, endEvent) => processAISDKOutput(
15569
16057
  result,
15570
16058
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -15656,6 +16144,8 @@ var AISDKPlugin = class extends BasePlugin {
15656
16144
  defaultDenyOutputPaths: denyOutputPaths,
15657
16145
  endEvent,
15658
16146
  onComplete: () => unregisterWorkflowAgentWrapperSpan(span),
16147
+ onCancel: () => unregisterWorkflowAgentWrapperSpan(span),
16148
+ onError: () => unregisterWorkflowAgentWrapperSpan(span),
15659
16149
  result,
15660
16150
  span,
15661
16151
  startTime
@@ -15664,6 +16154,153 @@ var AISDKPlugin = class extends BasePlugin {
15664
16154
  );
15665
16155
  }
15666
16156
  };
16157
+ function subscribeToHarnessAgentCreateSession() {
16158
+ const channel2 = harnessAgentChannels.createSession.tracingChannel();
16159
+ const parents = /* @__PURE__ */ new WeakMap();
16160
+ const handlers = {
16161
+ start: (event) => {
16162
+ const parent = captureHarnessCreateSessionParent(event.arguments?.[0]);
16163
+ if (parent) {
16164
+ parents.set(event, parent);
16165
+ }
16166
+ },
16167
+ asyncEnd: (event) => {
16168
+ registerHarnessSessionParent(event.result, parents.get(event));
16169
+ parents.delete(event);
16170
+ },
16171
+ error: (event) => {
16172
+ parents.delete(event);
16173
+ }
16174
+ };
16175
+ channel2.subscribe(handlers);
16176
+ return () => channel2.unsubscribe(handlers);
16177
+ }
16178
+ function harnessContinuationParentFromEvent(event) {
16179
+ try {
16180
+ return harnessContinuationParent(event.arguments?.[0]?.session);
16181
+ } catch {
16182
+ return void 0;
16183
+ }
16184
+ }
16185
+ function subscribeToHarnessContinuation(continuationChannel, defaultDenyOutputPaths) {
16186
+ const channel2 = continuationChannel.tracingChannel();
16187
+ const parents = /* @__PURE__ */ new WeakMap();
16188
+ const startTimes = /* @__PURE__ */ new WeakMap();
16189
+ const unbindParentStore = bindHarnessTurnParentToStart(
16190
+ channel2,
16191
+ harnessContinuationParentFromEvent
16192
+ );
16193
+ const handlers = {
16194
+ start: (event) => {
16195
+ const parent = harnessContinuationParentFromEvent(event);
16196
+ if (!parent) {
16197
+ return;
16198
+ }
16199
+ parents.set(event, parent);
16200
+ startTimes.set(event, getCurrentUnixTimestamp());
16201
+ try {
16202
+ const params = event.arguments?.[0];
16203
+ if (params) {
16204
+ prepareAISDKHarnessAgentInput(params, event.self);
16205
+ }
16206
+ } catch (error) {
16207
+ debugLogger.error(
16208
+ "Error preparing Harness continuation telemetry:",
16209
+ error
16210
+ );
16211
+ }
16212
+ },
16213
+ asyncEnd: (event) => {
16214
+ const parent = parents.get(event);
16215
+ const startTime = startTimes.get(event) ?? getCurrentUnixTimestamp();
16216
+ parents.delete(event);
16217
+ startTimes.delete(event);
16218
+ if (!parent) {
16219
+ return;
16220
+ }
16221
+ const endEvent = event;
16222
+ const span = {
16223
+ end: () => endHarnessTurn(parent),
16224
+ log: (update) => updateHarnessTurn(
16225
+ parent,
16226
+ Object.prototype.hasOwnProperty.call(update, "error") && !Object.prototype.hasOwnProperty.call(update, "output") ? { ...update, output: null } : update
16227
+ )
16228
+ };
16229
+ try {
16230
+ if (isAsyncIterable(endEvent.result)) {
16231
+ patchStreamIfNeeded(endEvent.result, {
16232
+ onComplete: (chunks) => {
16233
+ try {
16234
+ const { metadata, metrics, output } = aggregateAISDKChunks(
16235
+ chunks,
16236
+ endEvent.result,
16237
+ endEvent
16238
+ );
16239
+ span.log({
16240
+ ...metadata ? { metadata } : {},
16241
+ metrics,
16242
+ output
16243
+ });
16244
+ } catch (error) {
16245
+ debugLogger.error(
16246
+ "Error aggregating Harness continuation stream:",
16247
+ error
16248
+ );
16249
+ } finally {
16250
+ span.end();
16251
+ }
16252
+ },
16253
+ onError: (error) => {
16254
+ span.log({ error: toLoggedError(error), output: null });
16255
+ span.end();
16256
+ }
16257
+ });
16258
+ return;
16259
+ }
16260
+ if (patchAISDKStreamingResult({
16261
+ defaultDenyOutputPaths,
16262
+ endEvent,
16263
+ result: endEvent.result,
16264
+ resolvePromiseUsage: true,
16265
+ span,
16266
+ startTime
16267
+ })) {
16268
+ return;
16269
+ }
16270
+ finalizeAISDKChildTracing(endEvent);
16271
+ span.log({
16272
+ metrics: extractTokenMetrics(endEvent.result),
16273
+ output: processAISDKOutput(
16274
+ endEvent.result,
16275
+ resolveDenyOutputPaths(endEvent, defaultDenyOutputPaths)
16276
+ )
16277
+ });
16278
+ span.end();
16279
+ } catch (error) {
16280
+ debugLogger.error("Error tracing Harness continuation:", error);
16281
+ span.end();
16282
+ }
16283
+ },
16284
+ error: (event) => {
16285
+ const parent = parents.get(event);
16286
+ parents.delete(event);
16287
+ startTimes.delete(event);
16288
+ if (!parent) {
16289
+ return;
16290
+ }
16291
+ updateHarnessTurn(parent, {
16292
+ error: toLoggedError(event.error),
16293
+ output: null
16294
+ });
16295
+ endHarnessTurn(parent);
16296
+ }
16297
+ };
16298
+ channel2.subscribe(handlers);
16299
+ return () => {
16300
+ unbindParentStore();
16301
+ channel2.unsubscribe(handlers);
16302
+ };
16303
+ }
15667
16304
  function subscribeToAISDKV7TelemetryDispatcher() {
15668
16305
  const channel2 = aiSDKChannels.v7CreateTelemetryDispatcher.tracingChannel();
15669
16306
  const telemetry = braintrustAISDKTelemetry();
@@ -16116,7 +16753,13 @@ function prepareAISDKCallInput(params, event, span, defaultDenyOutputPaths, chil
16116
16753
  metadata
16117
16754
  };
16118
16755
  }
16119
- function prepareAISDKHarnessAgentInput(params, self) {
16756
+ function prepareAISDKHarnessAgentInput(params, self, span) {
16757
+ if (span) {
16758
+ registerHarnessTurnSpan({
16759
+ session: params.session,
16760
+ span
16761
+ });
16762
+ }
16120
16763
  if (isObject(self)) {
16121
16764
  try {
16122
16765
  if (isObject(self.settings)) {
@@ -16155,6 +16798,10 @@ function prepareAISDKHarnessAgentInput(params, self) {
16155
16798
  metadata
16156
16799
  };
16157
16800
  }
16801
+ function harnessSessionFromArguments(args) {
16802
+ const params = args[0];
16803
+ return isObject(params) ? params.session : void 0;
16804
+ }
16158
16805
  function prepareAISDKWorkflowAgentStreamInput(params, event, span, defaultDenyOutputPaths) {
16159
16806
  registerWorkflowAgentWrapperSpan(span);
16160
16807
  const { input } = processAISDKWorkflowAgentCallInput(params);
@@ -16602,19 +17249,22 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
16602
17249
  activeEntry.openSpans.delete(span);
16603
17250
  }
16604
17251
  },
16605
- {
16606
- name: "doGenerate",
16607
- spanAttributes: {
16608
- type: "llm" /* LLM */
17252
+ withSpanInstrumentationName(
17253
+ {
17254
+ name: "doGenerate",
17255
+ spanAttributes: {
17256
+ type: "llm" /* LLM */
17257
+ },
17258
+ event: buildAISDKModelStartEvent(
17259
+ callOptions,
17260
+ activeEntry.baseMetadata,
17261
+ {
17262
+ workflowAgent: activeEntry.childTracingOptions.workflowAgent
17263
+ }
17264
+ )
16609
17265
  },
16610
- event: buildAISDKModelStartEvent(
16611
- callOptions,
16612
- activeEntry.baseMetadata,
16613
- {
16614
- workflowAgent: activeEntry.childTracingOptions.workflowAgent
16615
- }
16616
- )
16617
- }
17266
+ INSTRUMENTATION_NAMES.AI_SDK
17267
+ )
16618
17268
  );
16619
17269
  };
16620
17270
  if (originalDoStream) {
@@ -16624,19 +17274,24 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
16624
17274
  return Reflect.apply(originalDoStream, resolvedModel, [callOptions]);
16625
17275
  }
16626
17276
  closeOpenAISDKModelPatchSpans(activeEntry);
16627
- const span = activeEntry.parentSpan.startSpan({
16628
- name: "doStream",
16629
- spanAttributes: {
16630
- type: "llm" /* LLM */
16631
- },
16632
- event: buildAISDKModelStartEvent(
16633
- callOptions,
16634
- activeEntry.baseMetadata,
17277
+ const span = activeEntry.parentSpan.startSpan(
17278
+ withSpanInstrumentationName(
16635
17279
  {
16636
- workflowAgent: activeEntry.childTracingOptions.workflowAgent
16637
- }
17280
+ name: "doStream",
17281
+ spanAttributes: {
17282
+ type: "llm" /* LLM */
17283
+ },
17284
+ event: buildAISDKModelStartEvent(
17285
+ callOptions,
17286
+ activeEntry.baseMetadata,
17287
+ {
17288
+ workflowAgent: activeEntry.childTracingOptions.workflowAgent
17289
+ }
17290
+ )
17291
+ },
17292
+ INSTRUMENTATION_NAMES.AI_SDK
16638
17293
  )
16639
- });
17294
+ );
16640
17295
  activeEntry.openSpans.add(span);
16641
17296
  const streamStartTime = getCurrentUnixTimestamp();
16642
17297
  const result = await withCurrent(
@@ -16808,12 +17463,17 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
16808
17463
  }
16809
17464
  if (isAsyncGenerator(result)) {
16810
17465
  return (async function* () {
16811
- const span = activeEntry.parentSpan.startSpan({
16812
- name: activeEntry.name,
16813
- spanAttributes: {
16814
- type: "tool" /* TOOL */
16815
- }
16816
- });
17466
+ const span = activeEntry.parentSpan.startSpan(
17467
+ withSpanInstrumentationName(
17468
+ {
17469
+ name: activeEntry.name,
17470
+ spanAttributes: {
17471
+ type: "tool" /* TOOL */
17472
+ }
17473
+ },
17474
+ INSTRUMENTATION_NAMES.AI_SDK
17475
+ )
17476
+ );
16817
17477
  span.log({ input: serializeToolExecutionInput(args) });
16818
17478
  try {
16819
17479
  let lastValue;
@@ -16837,12 +17497,15 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
16837
17497
  span.log({ output: awaitedResult });
16838
17498
  return awaitedResult;
16839
17499
  },
16840
- {
16841
- name: activeEntry.name,
16842
- spanAttributes: {
16843
- type: "tool" /* TOOL */
16844
- }
16845
- }
17500
+ withSpanInstrumentationName(
17501
+ {
17502
+ name: activeEntry.name,
17503
+ spanAttributes: {
17504
+ type: "tool" /* TOOL */
17505
+ }
17506
+ },
17507
+ INSTRUMENTATION_NAMES.AI_SDK
17508
+ )
16846
17509
  );
16847
17510
  };
16848
17511
  cleanup.push(() => {
@@ -17001,6 +17664,8 @@ function patchAISDKStreamingResult(args) {
17001
17664
  defaultDenyOutputPaths,
17002
17665
  endEvent,
17003
17666
  onComplete,
17667
+ onCancel,
17668
+ onError,
17004
17669
  result,
17005
17670
  resolvePromiseUsage,
17006
17671
  span,
@@ -17012,14 +17677,43 @@ function patchAISDKStreamingResult(args) {
17012
17677
  const resultRecord = result;
17013
17678
  attachKnownResultPromiseHandlers(resultRecord);
17014
17679
  let finalized = false;
17015
- const finalize = () => {
17680
+ const finalize = (outcome) => {
17016
17681
  if (finalized) {
17017
17682
  return;
17018
17683
  }
17019
17684
  finalized = true;
17020
- finalizeAISDKChildTracing(endEvent);
17021
- span.end();
17022
- onComplete?.();
17685
+ try {
17686
+ finalizeAISDKChildTracing(endEvent);
17687
+ } catch (error) {
17688
+ debugLogger.error("Error finalizing AI SDK child tracing:", error);
17689
+ }
17690
+ try {
17691
+ span.end();
17692
+ } catch (error) {
17693
+ debugLogger.error("Error ending AI SDK streaming span:", error);
17694
+ }
17695
+ if (outcome && "error" in outcome) {
17696
+ try {
17697
+ onError?.(outcome.error);
17698
+ } catch (error) {
17699
+ debugLogger.error("Error in AI SDK streaming error hook:", error);
17700
+ }
17701
+ } else if (outcome) {
17702
+ try {
17703
+ onComplete?.(outcome);
17704
+ } catch (error) {
17705
+ debugLogger.error("Error in AI SDK streaming completion hook:", error);
17706
+ }
17707
+ } else {
17708
+ try {
17709
+ onCancel?.();
17710
+ } catch (error) {
17711
+ debugLogger.error(
17712
+ "Error in AI SDK streaming cancellation hook:",
17713
+ error
17714
+ );
17715
+ }
17716
+ }
17023
17717
  };
17024
17718
  let outputLogged = false;
17025
17719
  const logStreamingOutput = async (firstChunkTime) => {
@@ -17053,15 +17747,29 @@ function patchAISDKStreamingResult(args) {
17053
17747
  resolveDenyOutputPaths(endEvent, defaultDenyOutputPaths)
17054
17748
  );
17055
17749
  const metadata = buildResolvedMetadataPayload(result).metadata;
17056
- span.log({
17057
- output,
17058
- ...metadata ? { metadata } : {},
17059
- metrics
17060
- });
17750
+ try {
17751
+ span.log({
17752
+ output,
17753
+ ...metadata ? { metadata } : {},
17754
+ metrics
17755
+ });
17756
+ } catch (error) {
17757
+ debugLogger.error("Error logging AI SDK streaming output:", error);
17758
+ }
17759
+ finalize({ metrics, output });
17061
17760
  } catch (error) {
17062
- span.log({ error: toLoggedError(error) });
17063
- } finally {
17064
- finalize();
17761
+ const loggedError = toLoggedError(error);
17762
+ try {
17763
+ span.log({ error: loggedError });
17764
+ } catch (loggingError) {
17765
+ debugLogger.error(
17766
+ "Error logging AI SDK streaming failure:",
17767
+ loggingError
17768
+ );
17769
+ }
17770
+ finalize({
17771
+ error: error instanceof Error ? error : new Error(String(loggedError))
17772
+ });
17065
17773
  }
17066
17774
  };
17067
17775
  const createAsyncIterableHooks = () => {
@@ -17078,11 +17786,16 @@ function patchAISDKStreamingResult(args) {
17078
17786
  onError: (error) => {
17079
17787
  if (!outputLogged) {
17080
17788
  outputLogged = true;
17081
- span.log({
17082
- error: error.message
17083
- });
17789
+ try {
17790
+ span.log({ error });
17791
+ } catch (loggingError) {
17792
+ debugLogger.error(
17793
+ "Error logging AI SDK stream failure:",
17794
+ loggingError
17795
+ );
17796
+ }
17084
17797
  }
17085
- finalize();
17798
+ finalize({ error });
17086
17799
  },
17087
17800
  onCancel: finalize
17088
17801
  };
@@ -17168,8 +17881,18 @@ function patchAISDKStreamingResult(args) {
17168
17881
  }
17169
17882
  controller.enqueue(value);
17170
17883
  } catch (error) {
17171
- span.log({ error: toLoggedError(error) });
17172
- finalize();
17884
+ const loggedError = toLoggedError(error);
17885
+ try {
17886
+ span.log({ error: loggedError });
17887
+ } catch (loggingError) {
17888
+ debugLogger.error(
17889
+ "Error logging AI SDK base stream failure:",
17890
+ loggingError
17891
+ );
17892
+ }
17893
+ finalize({
17894
+ error: error instanceof Error ? error : new Error(String(loggedError))
17895
+ });
17173
17896
  controller.error(error);
17174
17897
  }
17175
17898
  },
@@ -17958,7 +18681,8 @@ var claudeAgentSDKChannels = defineChannels(
17958
18681
  channelName: "query",
17959
18682
  kind: "sync-stream"
17960
18683
  })
17961
- }
18684
+ },
18685
+ { instrumentationName: INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK }
17962
18686
  );
17963
18687
 
17964
18688
  // src/instrumentation/plugins/claude-agent-sdk-instrumentation-constants.ts
@@ -18106,22 +18830,27 @@ function wrapLocalClaudeToolHandler(handler, getMetadata) {
18106
18830
  const spanName = metadata.serverName ? `tool: ${metadata.serverName}/${metadata.toolName}` : `tool: ${metadata.toolName}`;
18107
18831
  const runWithResolvedParent = async () => {
18108
18832
  const parent = toolUseId && localToolParentResolver ? await localToolParentResolver(toolUseId).catch(() => void 0) : void 0;
18109
- const span = startSpan({
18110
- event: {
18111
- input: handlerArgs[0],
18112
- metadata: {
18113
- "claude_agent_sdk.raw_tool_name": rawToolName,
18114
- "gen_ai.tool.name": metadata.toolName,
18115
- ...toolUseId && { "gen_ai.tool.call.id": toolUseId },
18116
- ...metadata.serverName && {
18117
- "mcp.server": metadata.serverName
18118
- }
18119
- }
18120
- },
18121
- name: spanName,
18122
- ...parent && { parent },
18123
- spanAttributes: { type: "tool" /* TOOL */ }
18124
- });
18833
+ const span = startSpan(
18834
+ withSpanInstrumentationName(
18835
+ {
18836
+ event: {
18837
+ input: handlerArgs[0],
18838
+ metadata: {
18839
+ "claude_agent_sdk.raw_tool_name": rawToolName,
18840
+ "gen_ai.tool.name": metadata.toolName,
18841
+ ...toolUseId && { "gen_ai.tool.call.id": toolUseId },
18842
+ ...metadata.serverName && {
18843
+ "mcp.server": metadata.serverName
18844
+ }
18845
+ }
18846
+ },
18847
+ name: spanName,
18848
+ ...parent && { parent },
18849
+ spanAttributes: { type: "tool" /* TOOL */ }
18850
+ },
18851
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
18852
+ )
18853
+ );
18125
18854
  const runHandler = () => Reflect.apply(handler, this, handlerArgs);
18126
18855
  const finalizeSuccess = (result) => {
18127
18856
  span.log({ output: result });
@@ -18446,14 +19175,19 @@ async function createLLMSpanForMessages(messages, promptMessages, conversationHi
18446
19175
  ).filter(
18447
19176
  (c) => c !== void 0
18448
19177
  );
18449
- const span = existingSpan ?? startSpan({
18450
- name: "anthropic.messages.create",
18451
- parent: parentSpan,
18452
- spanAttributes: {
18453
- type: "llm" /* LLM */
18454
- },
18455
- startTime
18456
- });
19178
+ const span = existingSpan ?? startSpan(
19179
+ withSpanInstrumentationName(
19180
+ {
19181
+ name: "anthropic.messages.create",
19182
+ parent: parentSpan,
19183
+ spanAttributes: {
19184
+ type: "llm" /* LLM */
19185
+ },
19186
+ startTime
19187
+ },
19188
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
19189
+ )
19190
+ );
18457
19191
  span.log({
18458
19192
  input,
18459
19193
  metadata: model ? { model } : void 0,
@@ -18556,25 +19290,30 @@ function createToolTracingHooks(resolveParentSpan, activeToolSpans, mcpServers,
18556
19290
  return {};
18557
19291
  }
18558
19292
  const parsed = parseToolName(input.tool_name);
18559
- const toolSpan = startSpan({
18560
- event: {
18561
- input: input.tool_input,
18562
- metadata: {
18563
- "claude_agent_sdk.cwd": input.cwd,
18564
- "claude_agent_sdk.raw_tool_name": parsed.rawToolName,
18565
- "claude_agent_sdk.session_id": input.session_id,
18566
- "gen_ai.tool.call.id": toolUseID,
18567
- "gen_ai.tool.name": parsed.toolName,
18568
- ...parsed.mcpServer && { "mcp.server": parsed.mcpServer },
18569
- ...getMcpServerMetadata(parsed.mcpServer, mcpServers)
18570
- }
18571
- },
18572
- name: parsed.displayName,
18573
- parent: await resolveParentSpan(toolUseID, {
18574
- agentId: input.agent_id
18575
- }),
18576
- spanAttributes: { type: "tool" /* TOOL */ }
18577
- });
19293
+ const toolSpan = startSpan(
19294
+ withSpanInstrumentationName(
19295
+ {
19296
+ event: {
19297
+ input: input.tool_input,
19298
+ metadata: {
19299
+ "claude_agent_sdk.cwd": input.cwd,
19300
+ "claude_agent_sdk.raw_tool_name": parsed.rawToolName,
19301
+ "claude_agent_sdk.session_id": input.session_id,
19302
+ "gen_ai.tool.call.id": toolUseID,
19303
+ "gen_ai.tool.name": parsed.toolName,
19304
+ ...parsed.mcpServer && { "mcp.server": parsed.mcpServer },
19305
+ ...getMcpServerMetadata(parsed.mcpServer, mcpServers)
19306
+ }
19307
+ },
19308
+ name: parsed.displayName,
19309
+ parent: await resolveParentSpan(toolUseID, {
19310
+ agentId: input.agent_id
19311
+ }),
19312
+ spanAttributes: { type: "tool" /* TOOL */ }
19313
+ },
19314
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
19315
+ )
19316
+ );
18578
19317
  activeToolSpans.set(toolUseID, toolSpan);
18579
19318
  return {};
18580
19319
  };
@@ -18940,14 +19679,19 @@ async function ensureSubAgentSpan(subAgentDetailsByToolUseId, rootSpan, activeTo
18940
19679
  const spanName = formatSubAgentSpanName(details);
18941
19680
  const parentToolSpan = activeToolSpans.get(parentToolUseId);
18942
19681
  const parentSpan = parentToolSpan ? await parentToolSpan.export() : await rootSpan.export();
18943
- const subAgentSpan = startSpan({
18944
- event: {
18945
- metadata: subAgentDetailsToMetadata(details)
18946
- },
18947
- name: spanName,
18948
- parent: parentSpan,
18949
- spanAttributes: { type: "task" /* TASK */ }
18950
- });
19682
+ const subAgentSpan = startSpan(
19683
+ withSpanInstrumentationName(
19684
+ {
19685
+ event: {
19686
+ metadata: subAgentDetailsToMetadata(details)
19687
+ },
19688
+ name: spanName,
19689
+ parent: parentSpan,
19690
+ spanAttributes: { type: "task" /* TASK */ }
19691
+ },
19692
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
19693
+ )
19694
+ );
18951
19695
  subAgentSpans.set(parentToolUseId, subAgentSpan);
18952
19696
  return subAgentSpan;
18953
19697
  }
@@ -18968,14 +19712,19 @@ async function ensureActiveLlmSpanForParentToolUse(rootSpan, activeLlmSpansByPar
18968
19712
  );
18969
19713
  llmParentSpan = await subAgentSpan.export();
18970
19714
  }
18971
- const llmSpan = startSpan({
18972
- name: "anthropic.messages.create",
18973
- parent: llmParentSpan,
18974
- spanAttributes: {
18975
- type: "llm" /* LLM */
18976
- },
18977
- startTime
18978
- });
19715
+ const llmSpan = startSpan(
19716
+ withSpanInstrumentationName(
19717
+ {
19718
+ name: "anthropic.messages.create",
19719
+ parent: llmParentSpan,
19720
+ spanAttributes: {
19721
+ type: "llm" /* LLM */
19722
+ },
19723
+ startTime
19724
+ },
19725
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
19726
+ )
19727
+ );
18979
19728
  activeLlmSpansByParentToolUse.set(parentKey, llmSpan);
18980
19729
  return llmSpan;
18981
19730
  }
@@ -19244,12 +19993,17 @@ var ClaudeAgentSDKPlugin = class extends BasePlugin {
19244
19993
  }
19245
19994
  })();
19246
19995
  }
19247
- const span = startSpan({
19248
- name: "Claude Agent",
19249
- spanAttributes: {
19250
- type: "task" /* TASK */
19251
- }
19252
- });
19996
+ const span = startSpan(
19997
+ withSpanInstrumentationName(
19998
+ {
19999
+ name: "Claude Agent",
20000
+ spanAttributes: {
20001
+ type: "task" /* TASK */
20002
+ }
20003
+ },
20004
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
20005
+ )
20006
+ );
19253
20007
  const startTime = getCurrentUnixTimestamp();
19254
20008
  try {
19255
20009
  span.log({
@@ -19414,24 +20168,28 @@ var ClaudeAgentSDKPlugin = class extends BasePlugin {
19414
20168
  };
19415
20169
 
19416
20170
  // src/instrumentation/plugins/cursor-sdk-channels.ts
19417
- var cursorSDKChannels = defineChannels("@cursor/sdk", {
19418
- create: channel({
19419
- channelName: "Agent.create",
19420
- kind: "async"
19421
- }),
19422
- resume: channel({
19423
- channelName: "Agent.resume",
19424
- kind: "async"
19425
- }),
19426
- prompt: channel({
19427
- channelName: "Agent.prompt",
19428
- kind: "async"
19429
- }),
19430
- send: channel({
19431
- channelName: "agent.send",
19432
- kind: "async"
19433
- })
19434
- });
20171
+ var cursorSDKChannels = defineChannels(
20172
+ "@cursor/sdk",
20173
+ {
20174
+ create: channel({
20175
+ channelName: "Agent.create",
20176
+ kind: "async"
20177
+ }),
20178
+ resume: channel({
20179
+ channelName: "Agent.resume",
20180
+ kind: "async"
20181
+ }),
20182
+ prompt: channel({
20183
+ channelName: "Agent.prompt",
20184
+ kind: "async"
20185
+ }),
20186
+ send: channel({
20187
+ channelName: "agent.send",
20188
+ kind: "async"
20189
+ })
20190
+ },
20191
+ { instrumentationName: INSTRUMENTATION_NAMES.CURSOR_SDK }
20192
+ );
19435
20193
 
19436
20194
  // src/instrumentation/plugins/cursor-sdk-plugin.ts
19437
20195
  var PATCHED_AGENT = /* @__PURE__ */ Symbol.for("braintrust.cursor-sdk.auto-patched-agent");
@@ -19483,10 +20241,15 @@ var CursorSDKPlugin = class extends BasePlugin {
19483
20241
  provider: "cursor",
19484
20242
  ...event.moduleVersion ? { "cursor_sdk.version": event.moduleVersion } : {}
19485
20243
  };
19486
- const span = startSpan({
19487
- name: "Cursor Agent",
19488
- spanAttributes: { type: "task" /* TASK */ }
19489
- });
20244
+ const span = startSpan(
20245
+ withSpanInstrumentationName(
20246
+ {
20247
+ name: "Cursor Agent",
20248
+ spanAttributes: { type: "task" /* TASK */ }
20249
+ },
20250
+ INSTRUMENTATION_NAMES.CURSOR_SDK
20251
+ )
20252
+ );
19490
20253
  const startTime = getCurrentUnixTimestamp();
19491
20254
  safeLog2(span, {
19492
20255
  input: sanitizeUserMessage(message),
@@ -19548,10 +20311,15 @@ var CursorSDKPlugin = class extends BasePlugin {
19548
20311
  provider: "cursor",
19549
20312
  ...event.moduleVersion ? { "cursor_sdk.version": event.moduleVersion } : {}
19550
20313
  };
19551
- const span = startSpan({
19552
- name: "Cursor Agent",
19553
- spanAttributes: { type: "task" /* TASK */ }
19554
- });
20314
+ const span = startSpan(
20315
+ withSpanInstrumentationName(
20316
+ {
20317
+ name: "Cursor Agent",
20318
+ spanAttributes: { type: "task" /* TASK */ }
20319
+ },
20320
+ INSTRUMENTATION_NAMES.CURSOR_SDK
20321
+ )
20322
+ );
19555
20323
  const startTime = getCurrentUnixTimestamp();
19556
20324
  safeLog2(span, {
19557
20325
  input: sanitizeUserMessage(message),
@@ -19998,29 +20766,39 @@ async function startToolSpan(state, args) {
19998
20766
  if (args.truncated?.result !== void 0) {
19999
20767
  metadata["cursor_sdk.tool.result_truncated"] = args.truncated.result;
20000
20768
  }
20001
- const span = startSpan({
20002
- event: {
20003
- input: args.args,
20004
- metadata
20005
- },
20006
- name: `tool: ${name}`,
20007
- parent: await state.span.export(),
20008
- spanAttributes: { type: "tool" /* TOOL */ }
20009
- });
20769
+ const span = startSpan(
20770
+ withSpanInstrumentationName(
20771
+ {
20772
+ event: {
20773
+ input: args.args,
20774
+ metadata
20775
+ },
20776
+ name: `tool: ${name}`,
20777
+ parent: await state.span.export(),
20778
+ spanAttributes: { type: "tool" /* TOOL */ }
20779
+ },
20780
+ INSTRUMENTATION_NAMES.CURSOR_SDK
20781
+ )
20782
+ );
20010
20783
  let subAgentSpan;
20011
20784
  if (isSubAgentToolName(name)) {
20012
- subAgentSpan = startSpan({
20013
- event: {
20014
- input: args.args,
20015
- metadata: {
20016
- "cursor_sdk.subagent.tool_call_id": args.callId,
20017
- "gen_ai.tool.name": name
20018
- }
20019
- },
20020
- name: formatSubAgentSpanName2(args.toolCall, args.args),
20021
- parent: await span.export(),
20022
- spanAttributes: { type: "task" /* TASK */ }
20023
- });
20785
+ subAgentSpan = startSpan(
20786
+ withSpanInstrumentationName(
20787
+ {
20788
+ event: {
20789
+ input: args.args,
20790
+ metadata: {
20791
+ "cursor_sdk.subagent.tool_call_id": args.callId,
20792
+ "gen_ai.tool.name": name
20793
+ }
20794
+ },
20795
+ name: formatSubAgentSpanName2(args.toolCall, args.args),
20796
+ parent: await span.export(),
20797
+ spanAttributes: { type: "task" /* TASK */ }
20798
+ },
20799
+ INSTRUMENTATION_NAMES.CURSOR_SDK
20800
+ )
20801
+ );
20024
20802
  }
20025
20803
  return { span, subAgentSpan };
20026
20804
  }
@@ -20279,24 +21057,28 @@ function cleanMetrics2(metrics) {
20279
21057
  }
20280
21058
 
20281
21059
  // src/instrumentation/plugins/openai-agents-channels.ts
20282
- var openAIAgentsCoreChannels = defineChannels("@openai/agents-core", {
20283
- onTraceStart: channel({
20284
- channelName: "tracing.processor.onTraceStart",
20285
- kind: "async"
20286
- }),
20287
- onTraceEnd: channel({
20288
- channelName: "tracing.processor.onTraceEnd",
20289
- kind: "async"
20290
- }),
20291
- onSpanStart: channel({
20292
- channelName: "tracing.processor.onSpanStart",
20293
- kind: "async"
20294
- }),
20295
- onSpanEnd: channel({
20296
- channelName: "tracing.processor.onSpanEnd",
20297
- kind: "async"
20298
- })
20299
- });
21060
+ var openAIAgentsCoreChannels = defineChannels(
21061
+ "@openai/agents-core",
21062
+ {
21063
+ onTraceStart: channel({
21064
+ channelName: "tracing.processor.onTraceStart",
21065
+ kind: "async"
21066
+ }),
21067
+ onTraceEnd: channel({
21068
+ channelName: "tracing.processor.onTraceEnd",
21069
+ kind: "async"
21070
+ }),
21071
+ onSpanStart: channel({
21072
+ channelName: "tracing.processor.onSpanStart",
21073
+ kind: "async"
21074
+ }),
21075
+ onSpanEnd: channel({
21076
+ channelName: "tracing.processor.onSpanEnd",
21077
+ kind: "async"
21078
+ })
21079
+ },
21080
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENAI_AGENTS }
21081
+ );
20300
21082
 
20301
21083
  // src/instrumentation/plugins/openai-agents-trace-processor.ts
20302
21084
  function isSpanData(spanData, type) {
@@ -20412,16 +21194,19 @@ var OpenAIAgentsTraceProcessor = class _OpenAIAgentsTraceProcessor {
20412
21194
  this.evictOldestTrace();
20413
21195
  }
20414
21196
  const current = currentSpan();
20415
- const span = current && current !== NOOP_SPAN ? current.startSpan({
20416
- name: trace.name,
20417
- type: "task" /* TASK */
20418
- }) : this.logger ? this.logger.startSpan({
20419
- name: trace.name,
20420
- type: "task" /* TASK */
20421
- }) : startSpan({
20422
- name: trace.name,
20423
- type: "task" /* TASK */
20424
- });
21197
+ const spanArgs = withSpanInstrumentationName(
21198
+ {
21199
+ name: trace.name,
21200
+ type: "task" /* TASK */
21201
+ },
21202
+ INSTRUMENTATION_NAMES.OPENAI_AGENTS
21203
+ );
21204
+ const span = current && current !== NOOP_SPAN ? current.startSpan(spanArgs) : this.logger ? this.logger.startSpan(spanArgs) : startSpan(
21205
+ withSpanInstrumentationName(
21206
+ spanArgs,
21207
+ INSTRUMENTATION_NAMES.OPENAI_AGENTS
21208
+ )
21209
+ );
20425
21210
  span.log({
20426
21211
  input: "Agent workflow started",
20427
21212
  metadata: {
@@ -20472,10 +21257,15 @@ var OpenAIAgentsTraceProcessor = class _OpenAIAgentsTraceProcessor {
20472
21257
  if (!parentSpan) {
20473
21258
  return Promise.resolve();
20474
21259
  }
20475
- const childSpan = parentSpan.startSpan({
20476
- name: spanNameFromAgents(span),
20477
- type: spanTypeFromAgents(span)
20478
- });
21260
+ const childSpan = parentSpan.startSpan(
21261
+ withSpanInstrumentationName(
21262
+ {
21263
+ name: spanNameFromAgents(span),
21264
+ type: spanTypeFromAgents(span)
21265
+ },
21266
+ INSTRUMENTATION_NAMES.OPENAI_AGENTS
21267
+ )
21268
+ );
20479
21269
  traceData.childSpans.set(span.spanId, childSpan);
20480
21270
  return Promise.resolve();
20481
21271
  }
@@ -20740,24 +21530,28 @@ var OpenAIAgentsPlugin = class extends BasePlugin {
20740
21530
  };
20741
21531
 
20742
21532
  // src/instrumentation/plugins/google-genai-channels.ts
20743
- var googleGenAIChannels = defineChannels("@google/genai", {
20744
- generateContent: channel({
20745
- channelName: "models.generateContent",
20746
- kind: "async"
20747
- }),
20748
- generateContentStream: channel({
20749
- channelName: "models.generateContentStream",
20750
- kind: "async"
20751
- }),
20752
- embedContent: channel({
20753
- channelName: "models.embedContent",
20754
- kind: "async"
20755
- }),
20756
- interactionsCreate: channel({
20757
- channelName: "interactions.create",
20758
- kind: "async"
20759
- })
20760
- });
21533
+ var googleGenAIChannels = defineChannels(
21534
+ "@google/genai",
21535
+ {
21536
+ generateContent: channel({
21537
+ channelName: "models.generateContent",
21538
+ kind: "async"
21539
+ }),
21540
+ generateContentStream: channel({
21541
+ channelName: "models.generateContentStream",
21542
+ kind: "async"
21543
+ }),
21544
+ embedContent: channel({
21545
+ channelName: "models.embedContent",
21546
+ kind: "async"
21547
+ }),
21548
+ interactionsCreate: channel({
21549
+ channelName: "interactions.create",
21550
+ kind: "async"
21551
+ })
21552
+ },
21553
+ { instrumentationName: INSTRUMENTATION_NAMES.GOOGLE_GENAI }
21554
+ );
20761
21555
 
20762
21556
  // src/instrumentation/plugins/google-genai-plugin.ts
20763
21557
  var GOOGLE_GENAI_INTERNAL_CONTEXT = {
@@ -20795,13 +21589,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
20795
21589
  const params = event.arguments[0];
20796
21590
  const input = serializeGenerateContentInput(params);
20797
21591
  const metadata = extractGenerateContentMetadata(params);
20798
- const span = startSpan({
20799
- name: "generate_content",
20800
- spanAttributes: {
20801
- type: "llm" /* LLM */
20802
- },
20803
- event: createWrapperParityEvent({ input, metadata })
20804
- });
21592
+ const span = startSpan(
21593
+ withSpanInstrumentationName(
21594
+ {
21595
+ name: "generate_content",
21596
+ spanAttributes: {
21597
+ type: "llm" /* LLM */
21598
+ },
21599
+ event: createWrapperParityEvent({ input, metadata })
21600
+ },
21601
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
21602
+ )
21603
+ );
20805
21604
  return {
20806
21605
  span,
20807
21606
  startTime: getCurrentUnixTimestamp()
@@ -20814,13 +21613,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
20814
21613
  const params = event.arguments[0];
20815
21614
  const input = serializeGenerateContentInput(params);
20816
21615
  const metadata = extractGenerateContentMetadata(params);
20817
- const span = startSpan({
20818
- name: "generate_content",
20819
- spanAttributes: {
20820
- type: "llm" /* LLM */
20821
- },
20822
- event: createWrapperParityEvent({ input, metadata })
20823
- });
21616
+ const span = startSpan(
21617
+ withSpanInstrumentationName(
21618
+ {
21619
+ name: "generate_content",
21620
+ spanAttributes: {
21621
+ type: "llm" /* LLM */
21622
+ },
21623
+ event: createWrapperParityEvent({ input, metadata })
21624
+ },
21625
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
21626
+ )
21627
+ );
20824
21628
  return {
20825
21629
  span,
20826
21630
  startTime: getCurrentUnixTimestamp()
@@ -20896,13 +21700,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
20896
21700
  const params = event.arguments[0];
20897
21701
  const input = serializeEmbedContentInput(params);
20898
21702
  const metadata = extractEmbedContentMetadata(params);
20899
- const span = startSpan({
20900
- name: "embed_content",
20901
- spanAttributes: {
20902
- type: "llm" /* LLM */
20903
- },
20904
- event: createWrapperParityEvent({ input, metadata })
20905
- });
21703
+ const span = startSpan(
21704
+ withSpanInstrumentationName(
21705
+ {
21706
+ name: "embed_content",
21707
+ spanAttributes: {
21708
+ type: "llm" /* LLM */
21709
+ },
21710
+ event: createWrapperParityEvent({ input, metadata })
21711
+ },
21712
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
21713
+ )
21714
+ );
20906
21715
  return {
20907
21716
  span,
20908
21717
  startTime: getCurrentUnixTimestamp()
@@ -20915,13 +21724,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
20915
21724
  const params = event.arguments[0];
20916
21725
  const input = serializeEmbedContentInput(params);
20917
21726
  const metadata = extractEmbedContentMetadata(params);
20918
- const span = startSpan({
20919
- name: "embed_content",
20920
- spanAttributes: {
20921
- type: "llm" /* LLM */
20922
- },
20923
- event: createWrapperParityEvent({ input, metadata })
20924
- });
21727
+ const span = startSpan(
21728
+ withSpanInstrumentationName(
21729
+ {
21730
+ name: "embed_content",
21731
+ spanAttributes: {
21732
+ type: "llm" /* LLM */
21733
+ },
21734
+ event: createWrapperParityEvent({ input, metadata })
21735
+ },
21736
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
21737
+ )
21738
+ );
20925
21739
  return {
20926
21740
  span,
20927
21741
  startTime: getCurrentUnixTimestamp()
@@ -21032,16 +21846,21 @@ function patchGoogleGenAIStreamingResult(args) {
21032
21846
  const requestStartTime = startTime ?? getCurrentUnixTimestamp();
21033
21847
  const ensureSpan = () => {
21034
21848
  if (!span) {
21035
- span = startSpan({
21036
- name: "generate_content_stream",
21037
- spanAttributes: {
21038
- type: "llm" /* LLM */
21039
- },
21040
- event: {
21041
- input,
21042
- metadata
21043
- }
21044
- });
21849
+ span = startSpan(
21850
+ withSpanInstrumentationName(
21851
+ {
21852
+ name: "generate_content_stream",
21853
+ spanAttributes: {
21854
+ type: "llm" /* LLM */
21855
+ },
21856
+ event: {
21857
+ input,
21858
+ metadata
21859
+ }
21860
+ },
21861
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
21862
+ )
21863
+ );
21045
21864
  }
21046
21865
  return span;
21047
21866
  };
@@ -21809,28 +22628,32 @@ function tryToDict(obj) {
21809
22628
  }
21810
22629
 
21811
22630
  // src/instrumentation/plugins/huggingface-channels.ts
21812
- var huggingFaceChannels = defineChannels("@huggingface/inference", {
21813
- chatCompletion: channel({
21814
- channelName: "chatCompletion",
21815
- kind: "async"
21816
- }),
21817
- chatCompletionStream: channel({
21818
- channelName: "chatCompletionStream",
21819
- kind: "sync-stream"
21820
- }),
21821
- textGeneration: channel({
21822
- channelName: "textGeneration",
21823
- kind: "async"
21824
- }),
21825
- textGenerationStream: channel({
21826
- channelName: "textGenerationStream",
21827
- kind: "sync-stream"
21828
- }),
21829
- featureExtraction: channel({
21830
- channelName: "featureExtraction",
21831
- kind: "async"
21832
- })
21833
- });
22631
+ var huggingFaceChannels = defineChannels(
22632
+ "@huggingface/inference",
22633
+ {
22634
+ chatCompletion: channel({
22635
+ channelName: "chatCompletion",
22636
+ kind: "async"
22637
+ }),
22638
+ chatCompletionStream: channel({
22639
+ channelName: "chatCompletionStream",
22640
+ kind: "sync-stream"
22641
+ }),
22642
+ textGeneration: channel({
22643
+ channelName: "textGeneration",
22644
+ kind: "async"
22645
+ }),
22646
+ textGenerationStream: channel({
22647
+ channelName: "textGenerationStream",
22648
+ kind: "sync-stream"
22649
+ }),
22650
+ featureExtraction: channel({
22651
+ channelName: "featureExtraction",
22652
+ kind: "async"
22653
+ })
22654
+ },
22655
+ { instrumentationName: INSTRUMENTATION_NAMES.HUGGINGFACE }
22656
+ );
21834
22657
 
21835
22658
  // src/instrumentation/plugins/huggingface-plugin.ts
21836
22659
  var REQUEST_METADATA_ALLOWLIST = /* @__PURE__ */ new Set([
@@ -22257,20 +23080,24 @@ function extractTextGenerationStreamMetadata(chunks) {
22257
23080
  }
22258
23081
 
22259
23082
  // src/instrumentation/plugins/openrouter-agent-channels.ts
22260
- var openRouterAgentChannels = defineChannels("@openrouter/agent", {
22261
- callModel: channel({
22262
- channelName: "callModel",
22263
- kind: "sync-stream"
22264
- }),
22265
- callModelTurn: channel({
22266
- channelName: "callModel.turn",
22267
- kind: "async"
22268
- }),
22269
- toolExecute: channel({
22270
- channelName: "tool.execute",
22271
- kind: "async"
22272
- })
22273
- });
23083
+ var openRouterAgentChannels = defineChannels(
23084
+ "@openrouter/agent",
23085
+ {
23086
+ callModel: channel({
23087
+ channelName: "callModel",
23088
+ kind: "sync-stream"
23089
+ }),
23090
+ callModelTurn: channel({
23091
+ channelName: "callModel.turn",
23092
+ kind: "async"
23093
+ }),
23094
+ toolExecute: channel({
23095
+ channelName: "tool.execute",
23096
+ kind: "async"
23097
+ })
23098
+ },
23099
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENROUTER_AGENT }
23100
+ );
22274
23101
 
22275
23102
  // src/instrumentation/plugins/openrouter-agent-plugin.ts
22276
23103
  var OpenRouterAgentPlugin = class extends BasePlugin {
@@ -23040,38 +23867,40 @@ function normalizeError(error) {
23040
23867
  }
23041
23868
 
23042
23869
  // src/instrumentation/plugins/openrouter-channels.ts
23043
- var openRouterChannels = defineChannels("@openrouter/sdk", {
23044
- chatSend: channel({
23045
- channelName: "chat.send",
23046
- kind: "async"
23047
- }),
23048
- embeddingsGenerate: channel({
23049
- channelName: "embeddings.generate",
23050
- kind: "async"
23051
- }),
23052
- rerankRerank: channel(
23053
- {
23870
+ var openRouterChannels = defineChannels(
23871
+ "@openrouter/sdk",
23872
+ {
23873
+ chatSend: channel({
23874
+ channelName: "chat.send",
23875
+ kind: "async"
23876
+ }),
23877
+ embeddingsGenerate: channel({
23878
+ channelName: "embeddings.generate",
23879
+ kind: "async"
23880
+ }),
23881
+ rerankRerank: channel({
23054
23882
  channelName: "rerank.rerank",
23055
23883
  kind: "async"
23056
- }
23057
- ),
23058
- betaResponsesSend: channel({
23059
- channelName: "beta.responses.send",
23060
- kind: "async"
23061
- }),
23062
- callModel: channel({
23063
- channelName: "callModel",
23064
- kind: "sync-stream"
23065
- }),
23066
- callModelTurn: channel({
23067
- channelName: "callModel.turn",
23068
- kind: "async"
23069
- }),
23070
- toolExecute: channel({
23071
- channelName: "tool.execute",
23072
- kind: "async"
23073
- })
23074
- });
23884
+ }),
23885
+ betaResponsesSend: channel({
23886
+ channelName: "beta.responses.send",
23887
+ kind: "async"
23888
+ }),
23889
+ callModel: channel({
23890
+ channelName: "callModel",
23891
+ kind: "sync-stream"
23892
+ }),
23893
+ callModelTurn: channel({
23894
+ channelName: "callModel.turn",
23895
+ kind: "async"
23896
+ }),
23897
+ toolExecute: channel({
23898
+ channelName: "tool.execute",
23899
+ kind: "async"
23900
+ })
23901
+ },
23902
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENROUTER }
23903
+ );
23075
23904
 
23076
23905
  // src/instrumentation/plugins/openrouter-plugin.ts
23077
23906
  var OpenRouterPlugin = class extends BasePlugin {
@@ -24111,52 +24940,56 @@ function normalizeError2(error) {
24111
24940
  }
24112
24941
 
24113
24942
  // src/instrumentation/plugins/mistral-channels.ts
24114
- var mistralChannels = defineChannels("@mistralai/mistralai", {
24115
- chatComplete: channel({
24116
- channelName: "chat.complete",
24117
- kind: "async"
24118
- }),
24119
- chatStream: channel({
24120
- channelName: "chat.stream",
24121
- kind: "async"
24122
- }),
24123
- embeddingsCreate: channel({
24124
- channelName: "embeddings.create",
24125
- kind: "async"
24126
- }),
24127
- classifiersModerate: channel({
24128
- channelName: "classifiers.moderate",
24129
- kind: "async"
24130
- }),
24131
- classifiersModerateChat: channel({
24132
- channelName: "classifiers.moderateChat",
24133
- kind: "async"
24134
- }),
24135
- classifiersClassify: channel({
24136
- channelName: "classifiers.classify",
24137
- kind: "async"
24138
- }),
24139
- classifiersClassifyChat: channel({
24140
- channelName: "classifiers.classifyChat",
24141
- kind: "async"
24142
- }),
24143
- fimComplete: channel({
24144
- channelName: "fim.complete",
24145
- kind: "async"
24146
- }),
24147
- fimStream: channel({
24148
- channelName: "fim.stream",
24149
- kind: "async"
24150
- }),
24151
- agentsComplete: channel({
24152
- channelName: "agents.complete",
24153
- kind: "async"
24154
- }),
24155
- agentsStream: channel({
24156
- channelName: "agents.stream",
24157
- kind: "async"
24158
- })
24159
- });
24943
+ var mistralChannels = defineChannels(
24944
+ "@mistralai/mistralai",
24945
+ {
24946
+ chatComplete: channel({
24947
+ channelName: "chat.complete",
24948
+ kind: "async"
24949
+ }),
24950
+ chatStream: channel({
24951
+ channelName: "chat.stream",
24952
+ kind: "async"
24953
+ }),
24954
+ embeddingsCreate: channel({
24955
+ channelName: "embeddings.create",
24956
+ kind: "async"
24957
+ }),
24958
+ classifiersModerate: channel({
24959
+ channelName: "classifiers.moderate",
24960
+ kind: "async"
24961
+ }),
24962
+ classifiersModerateChat: channel({
24963
+ channelName: "classifiers.moderateChat",
24964
+ kind: "async"
24965
+ }),
24966
+ classifiersClassify: channel({
24967
+ channelName: "classifiers.classify",
24968
+ kind: "async"
24969
+ }),
24970
+ classifiersClassifyChat: channel({
24971
+ channelName: "classifiers.classifyChat",
24972
+ kind: "async"
24973
+ }),
24974
+ fimComplete: channel({
24975
+ channelName: "fim.complete",
24976
+ kind: "async"
24977
+ }),
24978
+ fimStream: channel({
24979
+ channelName: "fim.stream",
24980
+ kind: "async"
24981
+ }),
24982
+ agentsComplete: channel({
24983
+ channelName: "agents.complete",
24984
+ kind: "async"
24985
+ }),
24986
+ agentsStream: channel({
24987
+ channelName: "agents.stream",
24988
+ kind: "async"
24989
+ })
24990
+ },
24991
+ { instrumentationName: INSTRUMENTATION_NAMES.MISTRAL }
24992
+ );
24160
24993
 
24161
24994
  // src/instrumentation/plugins/mistral-plugin.ts
24162
24995
  var MistralPlugin = class extends BasePlugin {
@@ -24776,20 +25609,24 @@ function aggregateMistralStreamChunks(chunks) {
24776
25609
  }
24777
25610
 
24778
25611
  // src/instrumentation/plugins/google-adk-channels.ts
24779
- var googleADKChannels = defineChannels("@google/adk", {
24780
- runnerRunAsync: channel({
24781
- channelName: "runner.runAsync",
24782
- kind: "sync-stream"
24783
- }),
24784
- agentRunAsync: channel({
24785
- channelName: "agent.runAsync",
24786
- kind: "sync-stream"
24787
- }),
24788
- toolRunAsync: channel({
24789
- channelName: "tool.runAsync",
24790
- kind: "async"
24791
- })
24792
- });
25612
+ var googleADKChannels = defineChannels(
25613
+ "@google/adk",
25614
+ {
25615
+ runnerRunAsync: channel({
25616
+ channelName: "runner.runAsync",
25617
+ kind: "sync-stream"
25618
+ }),
25619
+ agentRunAsync: channel({
25620
+ channelName: "agent.runAsync",
25621
+ kind: "sync-stream"
25622
+ }),
25623
+ toolRunAsync: channel({
25624
+ channelName: "tool.runAsync",
25625
+ kind: "async"
25626
+ })
25627
+ },
25628
+ { instrumentationName: INSTRUMENTATION_NAMES.GOOGLE_ADK }
25629
+ );
24793
25630
 
24794
25631
  // src/instrumentation/plugins/google-adk-plugin.ts
24795
25632
  var GoogleADKPlugin = class extends BasePlugin {
@@ -24814,12 +25651,17 @@ var GoogleADKPlugin = class extends BasePlugin {
24814
25651
  const createState = (event) => {
24815
25652
  const params = event.arguments[0] ?? {};
24816
25653
  const contextKey = extractRunnerContextKey(params);
24817
- const span = startSpan({
24818
- name: "Google ADK Runner",
24819
- spanAttributes: {
24820
- type: "task" /* TASK */
24821
- }
24822
- });
25654
+ const span = startSpan(
25655
+ withSpanInstrumentationName(
25656
+ {
25657
+ name: "Google ADK Runner",
25658
+ spanAttributes: {
25659
+ type: "task" /* TASK */
25660
+ }
25661
+ },
25662
+ INSTRUMENTATION_NAMES.GOOGLE_ADK
25663
+ )
25664
+ );
24823
25665
  const startTime = getCurrentUnixTimestamp();
24824
25666
  try {
24825
25667
  const metadata = extractRunnerMetadata(params);
@@ -24905,18 +25747,23 @@ var GoogleADKPlugin = class extends BasePlugin {
24905
25747
  this.activeRunnerSpans
24906
25748
  );
24907
25749
  const contextKey = extractInvocationContextKey(parentContext);
24908
- const span = startSpan({
24909
- name: agentName ? `Agent: ${agentName}` : "Google ADK Agent",
24910
- spanAttributes: {
24911
- type: "task" /* TASK */
24912
- },
24913
- ...runnerParentSpan ? {
24914
- parentSpanIds: {
24915
- spanId: runnerParentSpan.spanId,
24916
- rootSpanId: runnerParentSpan.rootSpanId
24917
- }
24918
- } : {}
24919
- });
25750
+ const span = startSpan(
25751
+ withSpanInstrumentationName(
25752
+ {
25753
+ name: agentName ? `Agent: ${agentName}` : "Google ADK Agent",
25754
+ spanAttributes: {
25755
+ type: "task" /* TASK */
25756
+ },
25757
+ ...runnerParentSpan ? {
25758
+ parentSpanIds: {
25759
+ spanId: runnerParentSpan.spanId,
25760
+ rootSpanId: runnerParentSpan.rootSpanId
25761
+ }
25762
+ } : {}
25763
+ },
25764
+ INSTRUMENTATION_NAMES.GOOGLE_ADK
25765
+ )
25766
+ );
24920
25767
  const startTime = getCurrentUnixTimestamp();
24921
25768
  try {
24922
25769
  const metadata = {
@@ -25009,22 +25856,27 @@ var GoogleADKPlugin = class extends BasePlugin {
25009
25856
  this.activeAgentSpans,
25010
25857
  this.activeRunnerSpans
25011
25858
  );
25012
- const createSpan = () => startSpan({
25013
- name: toolName ? `tool: ${toolName}` : "Google ADK Tool",
25014
- spanAttributes: {
25015
- type: "tool" /* TOOL */
25016
- },
25017
- event: {
25018
- input: req.args,
25019
- metadata: {
25020
- provider: "google-adk",
25021
- ...toolName && { "google_adk.tool_name": toolName },
25022
- ...extractToolCallId(req) && {
25023
- "google_adk.tool_call_id": extractToolCallId(req)
25859
+ const createSpan = () => startSpan(
25860
+ withSpanInstrumentationName(
25861
+ {
25862
+ name: toolName ? `tool: ${toolName}` : "Google ADK Tool",
25863
+ spanAttributes: {
25864
+ type: "tool" /* TOOL */
25865
+ },
25866
+ event: {
25867
+ input: req.args,
25868
+ metadata: {
25869
+ provider: "google-adk",
25870
+ ...toolName && { "google_adk.tool_name": toolName },
25871
+ ...extractToolCallId(req) && {
25872
+ "google_adk.tool_call_id": extractToolCallId(req)
25873
+ }
25874
+ }
25024
25875
  }
25025
- }
25026
- }
25027
- });
25876
+ },
25877
+ INSTRUMENTATION_NAMES.GOOGLE_ADK
25878
+ )
25879
+ );
25028
25880
  const span = parentSpan ? withCurrent(parentSpan, () => createSpan()) : createSpan();
25029
25881
  const startTime = getCurrentUnixTimestamp();
25030
25882
  states.set(event, { span, startTime });
@@ -25423,24 +26275,28 @@ function cleanMetrics4(metrics) {
25423
26275
  }
25424
26276
 
25425
26277
  // src/instrumentation/plugins/cohere-channels.ts
25426
- var cohereChannels = defineChannels("cohere-ai", {
25427
- chat: channel({
25428
- channelName: "chat",
25429
- kind: "async"
25430
- }),
25431
- chatStream: channel({
25432
- channelName: "chatStream",
25433
- kind: "async"
25434
- }),
25435
- embed: channel({
25436
- channelName: "embed",
25437
- kind: "async"
25438
- }),
25439
- rerank: channel({
25440
- channelName: "rerank",
25441
- kind: "async"
25442
- })
25443
- });
26278
+ var cohereChannels = defineChannels(
26279
+ "cohere-ai",
26280
+ {
26281
+ chat: channel({
26282
+ channelName: "chat",
26283
+ kind: "async"
26284
+ }),
26285
+ chatStream: channel({
26286
+ channelName: "chatStream",
26287
+ kind: "async"
26288
+ }),
26289
+ embed: channel({
26290
+ channelName: "embed",
26291
+ kind: "async"
26292
+ }),
26293
+ rerank: channel({
26294
+ channelName: "rerank",
26295
+ kind: "async"
26296
+ })
26297
+ },
26298
+ { instrumentationName: INSTRUMENTATION_NAMES.COHERE }
26299
+ );
25444
26300
 
25445
26301
  // src/instrumentation/plugins/cohere-plugin.ts
25446
26302
  var CoherePlugin = class extends BasePlugin {
@@ -26109,18 +26965,20 @@ function aggregateCohereChatStreamChunks(chunks) {
26109
26965
  }
26110
26966
 
26111
26967
  // src/instrumentation/plugins/groq-channels.ts
26112
- var groqChannels = defineChannels("groq-sdk", {
26113
- chatCompletionsCreate: channel({
26114
- channelName: "chat.completions.create",
26115
- kind: "async"
26116
- }),
26117
- embeddingsCreate: channel(
26118
- {
26968
+ var groqChannels = defineChannels(
26969
+ "groq-sdk",
26970
+ {
26971
+ chatCompletionsCreate: channel({
26972
+ channelName: "chat.completions.create",
26973
+ kind: "async"
26974
+ }),
26975
+ embeddingsCreate: channel({
26119
26976
  channelName: "embeddings.create",
26120
26977
  kind: "async"
26121
- }
26122
- )
26123
- });
26978
+ })
26979
+ },
26980
+ { instrumentationName: INSTRUMENTATION_NAMES.GROQ }
26981
+ );
26124
26982
 
26125
26983
  // src/instrumentation/plugins/groq-plugin.ts
26126
26984
  var GroqPlugin = class extends BasePlugin {
@@ -26223,15 +27081,27 @@ var clientSendChannel = channel({
26223
27081
  channelName: "client.send",
26224
27082
  kind: "async"
26225
27083
  });
26226
- var bedrockRuntimeChannels = defineChannels("aws-bedrock-runtime", {
26227
- clientSend: clientSendChannel
26228
- });
26229
- var smithyCoreChannels = defineChannels("@smithy/core", {
26230
- clientSend: clientSendChannel
26231
- });
26232
- var smithyClientChannels = defineChannels("@smithy/smithy-client", {
26233
- clientSend: clientSendChannel
26234
- });
27084
+ var bedrockRuntimeChannels = defineChannels(
27085
+ "aws-bedrock-runtime",
27086
+ {
27087
+ clientSend: clientSendChannel
27088
+ },
27089
+ { instrumentationName: INSTRUMENTATION_NAMES.BEDROCK_RUNTIME }
27090
+ );
27091
+ var smithyCoreChannels = defineChannels(
27092
+ "@smithy/core",
27093
+ {
27094
+ clientSend: clientSendChannel
27095
+ },
27096
+ { instrumentationName: INSTRUMENTATION_NAMES.BEDROCK_RUNTIME }
27097
+ );
27098
+ var smithyClientChannels = defineChannels(
27099
+ "@smithy/smithy-client",
27100
+ {
27101
+ clientSend: clientSendChannel
27102
+ },
27103
+ { instrumentationName: INSTRUMENTATION_NAMES.BEDROCK_RUNTIME }
27104
+ );
26235
27105
 
26236
27106
  // src/instrumentation/plugins/bedrock-runtime-common.ts
26237
27107
  var BEDROCK_RUNTIME_COMMAND_OPERATIONS = {
@@ -26865,38 +27735,46 @@ function extractTextFromJsonLike(value) {
26865
27735
  }
26866
27736
 
26867
27737
  // src/instrumentation/plugins/genkit-channels.ts
26868
- var genkitChannels = defineChannels("@genkit-ai/ai", {
26869
- generate: channel({
26870
- channelName: "generate",
26871
- kind: "async"
26872
- }),
26873
- generateStream: channel({
26874
- channelName: "generateStream",
26875
- kind: "sync-stream"
26876
- }),
26877
- embed: channel({
26878
- channelName: "embed",
26879
- kind: "async"
26880
- }),
26881
- embedMany: channel({
26882
- channelName: "embedMany",
26883
- kind: "async"
26884
- }),
26885
- actionRun: channel({
26886
- channelName: "action.run",
26887
- kind: "async"
26888
- }),
26889
- actionStream: channel({
26890
- channelName: "action.stream",
26891
- kind: "sync-stream"
26892
- })
26893
- });
26894
- var genkitCoreChannels = defineChannels("@genkit-ai/core", {
26895
- actionSpan: channel({
26896
- channelName: "action.span",
26897
- kind: "async"
26898
- })
26899
- });
27738
+ var genkitChannels = defineChannels(
27739
+ "@genkit-ai/ai",
27740
+ {
27741
+ generate: channel({
27742
+ channelName: "generate",
27743
+ kind: "async"
27744
+ }),
27745
+ generateStream: channel({
27746
+ channelName: "generateStream",
27747
+ kind: "sync-stream"
27748
+ }),
27749
+ embed: channel({
27750
+ channelName: "embed",
27751
+ kind: "async"
27752
+ }),
27753
+ embedMany: channel({
27754
+ channelName: "embedMany",
27755
+ kind: "async"
27756
+ }),
27757
+ actionRun: channel({
27758
+ channelName: "action.run",
27759
+ kind: "async"
27760
+ }),
27761
+ actionStream: channel({
27762
+ channelName: "action.stream",
27763
+ kind: "sync-stream"
27764
+ })
27765
+ },
27766
+ { instrumentationName: INSTRUMENTATION_NAMES.GENKIT }
27767
+ );
27768
+ var genkitCoreChannels = defineChannels(
27769
+ "@genkit-ai/core",
27770
+ {
27771
+ actionSpan: channel({
27772
+ channelName: "action.span",
27773
+ kind: "async"
27774
+ })
27775
+ },
27776
+ { instrumentationName: INSTRUMENTATION_NAMES.GENKIT }
27777
+ );
26900
27778
 
26901
27779
  // src/instrumentation/plugins/genkit-plugin.ts
26902
27780
  var GenkitPlugin = class extends BasePlugin {
@@ -27081,12 +27959,17 @@ function startActionSpanState(args) {
27081
27959
  if (!shouldTraceAction(args.metadata, args.runStepName)) {
27082
27960
  return void 0;
27083
27961
  }
27084
- const span = startSpan({
27085
- name: actionSpanName(args.metadata, args.runStepName),
27086
- spanAttributes: {
27087
- type: actionSpanType(args.metadata)
27088
- }
27089
- });
27962
+ const span = startSpan(
27963
+ withSpanInstrumentationName(
27964
+ {
27965
+ name: actionSpanName(args.metadata, args.runStepName),
27966
+ spanAttributes: {
27967
+ type: actionSpanType(args.metadata)
27968
+ }
27969
+ },
27970
+ INSTRUMENTATION_NAMES.GENKIT
27971
+ )
27972
+ );
27090
27973
  const startTime = getCurrentUnixTimestamp();
27091
27974
  span.log({
27092
27975
  input: args.input,
@@ -27447,20 +28330,24 @@ function stringValue(value) {
27447
28330
  }
27448
28331
 
27449
28332
  // src/instrumentation/plugins/github-copilot-channels.ts
27450
- var gitHubCopilotChannels = defineChannels("@github/copilot-sdk", {
27451
- createSession: channel({
27452
- channelName: "client.createSession",
27453
- kind: "async"
27454
- }),
27455
- resumeSession: channel({
27456
- channelName: "client.resumeSession",
27457
- kind: "async"
27458
- }),
27459
- sendAndWait: channel({
27460
- channelName: "session.sendAndWait",
27461
- kind: "async"
27462
- })
27463
- });
28333
+ var gitHubCopilotChannels = defineChannels(
28334
+ "@github/copilot-sdk",
28335
+ {
28336
+ createSession: channel({
28337
+ channelName: "client.createSession",
28338
+ kind: "async"
28339
+ }),
28340
+ resumeSession: channel({
28341
+ channelName: "client.resumeSession",
28342
+ kind: "async"
28343
+ }),
28344
+ sendAndWait: channel({
28345
+ channelName: "session.sendAndWait",
28346
+ kind: "async"
28347
+ })
28348
+ },
28349
+ { instrumentationName: INSTRUMENTATION_NAMES.GITHUB_COPILOT }
28350
+ );
27464
28351
 
27465
28352
  // src/instrumentation/plugins/github-copilot-plugin.ts
27466
28353
  var ROOT_AGENT_KEY = "__root__";
@@ -27551,11 +28438,16 @@ async function handleTurnStart(state, agentId) {
27551
28438
  return;
27552
28439
  }
27553
28440
  const parentId = await getParentIdForAgent(state, agentId);
27554
- const span = startSpan({
27555
- name: "Copilot Turn",
27556
- parent: parentId,
27557
- spanAttributes: { type: "task" /* TASK */ }
27558
- });
28441
+ const span = startSpan(
28442
+ withSpanInstrumentationName(
28443
+ {
28444
+ name: "Copilot Turn",
28445
+ parent: parentId,
28446
+ spanAttributes: { type: "task" /* TASK */ }
28447
+ },
28448
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
28449
+ )
28450
+ );
27559
28451
  const pendingUserMessage = state.pendingUserMessages.get(key);
27560
28452
  if (pendingUserMessage) {
27561
28453
  span.log({ input: pendingUserMessage });
@@ -27586,11 +28478,16 @@ async function handleUsage(state, agentId, usage) {
27586
28478
  const parentId = turn ? await turn.id : await state.session.id;
27587
28479
  const content = state.currentMessageContent.get(key);
27588
28480
  const { metrics, metadata } = extractMetricsFromUsage(usage);
27589
- const llmSpan = startSpan({
27590
- name: "github.copilot.llm",
27591
- parent: parentId,
27592
- spanAttributes: { type: "llm" /* LLM */ }
27593
- });
28481
+ const llmSpan = startSpan(
28482
+ withSpanInstrumentationName(
28483
+ {
28484
+ name: "github.copilot.llm",
28485
+ parent: parentId,
28486
+ spanAttributes: { type: "llm" /* LLM */ }
28487
+ },
28488
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
28489
+ )
28490
+ );
27594
28491
  llmSpan.log({
27595
28492
  output: content ?? void 0,
27596
28493
  metadata,
@@ -27616,11 +28513,16 @@ async function handleToolStart(state, agentId, toolCallId, toolName, args, mcpSe
27616
28513
  }
27617
28514
  const parentId = await getToolParentId(state, agentId);
27618
28515
  const displayName = mcpServerName ? `tool: ${mcpServerName}/${toolName}` : `tool: ${toolName}`;
27619
- const span = startSpan({
27620
- name: displayName,
27621
- parent: parentId,
27622
- spanAttributes: { type: "tool" /* TOOL */ }
27623
- });
28516
+ const span = startSpan(
28517
+ withSpanInstrumentationName(
28518
+ {
28519
+ name: displayName,
28520
+ parent: parentId,
28521
+ spanAttributes: { type: "tool" /* TOOL */ }
28522
+ },
28523
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
28524
+ )
28525
+ );
27624
28526
  const metadata = {
27625
28527
  "gen_ai.tool.name": toolName,
27626
28528
  "gen_ai.tool.call.id": toolCallId
@@ -27656,11 +28558,16 @@ async function handleSubagentStarted(state, agentId, toolCallId, agentDisplayNam
27656
28558
  }
27657
28559
  const tool = state.activeTools.get(toolCallId);
27658
28560
  const parentId = tool ? await tool.id : await state.session.id;
27659
- const span = startSpan({
27660
- name: `Agent: ${agentDisplayName}`,
27661
- parent: parentId,
27662
- spanAttributes: { type: "task" /* TASK */ }
27663
- });
28561
+ const span = startSpan(
28562
+ withSpanInstrumentationName(
28563
+ {
28564
+ name: `Agent: ${agentDisplayName}`,
28565
+ parent: parentId,
28566
+ spanAttributes: { type: "task" /* TASK */ }
28567
+ },
28568
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
28569
+ )
28570
+ );
27664
28571
  span.log({
27665
28572
  metadata: {
27666
28573
  "github_copilot.agent_name": agentDisplayName,
@@ -27886,10 +28793,15 @@ function makeSessionHandlers(sessionStates, configArgIndex, includeProviderMetad
27886
28793
  if (!config || typeof config !== "object") {
27887
28794
  return;
27888
28795
  }
27889
- const sessionSpan = startSpan({
27890
- name: "Copilot Session",
27891
- spanAttributes: { type: "task" /* TASK */ }
27892
- });
28796
+ const sessionSpan = startSpan(
28797
+ withSpanInstrumentationName(
28798
+ {
28799
+ name: "Copilot Session",
28800
+ spanAttributes: { type: "task" /* TASK */ }
28801
+ },
28802
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
28803
+ )
28804
+ );
27893
28805
  const metadata = {};
27894
28806
  if (config.model) {
27895
28807
  metadata["github_copilot.model"] = config.model;
@@ -27977,12 +28889,16 @@ var GitHubCopilotPlugin = class extends BasePlugin {
27977
28889
  };
27978
28890
 
27979
28891
  // src/instrumentation/plugins/flue-channels.ts
27980
- var flueChannels = defineChannels("@flue/runtime", {
27981
- createContext: channel({
27982
- channelName: "createFlueContext",
27983
- kind: "sync-stream"
27984
- })
27985
- });
28892
+ var flueChannels = defineChannels(
28893
+ "@flue/runtime",
28894
+ {
28895
+ createContext: channel({
28896
+ channelName: "createFlueContext",
28897
+ kind: "sync-stream"
28898
+ })
28899
+ },
28900
+ { instrumentationName: INSTRUMENTATION_NAMES.FLUE }
28901
+ );
27986
28902
 
27987
28903
  // src/instrumentation/plugins/flue-plugin.ts
27988
28904
  var FLUE_AUTO_STATE = /* @__PURE__ */ Symbol.for("braintrust.flue.auto-state");
@@ -28325,15 +29241,20 @@ var FlueObserveBridge = class {
28325
29241
  safeLog3(existing.span, { input, metadata });
28326
29242
  return;
28327
29243
  }
28328
- const span = startSpan({
28329
- name: `workflow:${workflowName}`,
28330
- spanAttributes: { type: "task" /* TASK */ },
28331
- startTime: eventTime(event.startedAt ?? event.timestamp),
28332
- event: {
28333
- input,
28334
- metadata
28335
- }
28336
- });
29244
+ const span = startSpan(
29245
+ withSpanInstrumentationName(
29246
+ {
29247
+ name: `workflow:${workflowName}`,
29248
+ spanAttributes: { type: "task" /* TASK */ },
29249
+ startTime: eventTime(event.startedAt ?? event.timestamp),
29250
+ event: {
29251
+ input,
29252
+ metadata
29253
+ }
29254
+ },
29255
+ INSTRUMENTATION_NAMES.FLUE
29256
+ )
29257
+ );
28337
29258
  this.runsById.set(event.runId, { metadata, span });
28338
29259
  }
28339
29260
  handleRunResume(event, ctx) {
@@ -28353,12 +29274,17 @@ var FlueObserveBridge = class {
28353
29274
  safeLog3(existing.span, { metadata });
28354
29275
  return;
28355
29276
  }
28356
- const span = startSpan({
28357
- name: `workflow:${workflowName}`,
28358
- spanAttributes: { type: "task" /* TASK */ },
28359
- startTime: eventTime(event.startedAt ?? event.timestamp),
28360
- event: { metadata }
28361
- });
29277
+ const span = startSpan(
29278
+ withSpanInstrumentationName(
29279
+ {
29280
+ name: `workflow:${workflowName}`,
29281
+ spanAttributes: { type: "task" /* TASK */ },
29282
+ startTime: eventTime(event.startedAt ?? event.timestamp),
29283
+ event: { metadata }
29284
+ },
29285
+ INSTRUMENTATION_NAMES.FLUE
29286
+ )
29287
+ );
28362
29288
  this.runsById.set(event.runId, { metadata, span });
28363
29289
  }
28364
29290
  handleRunEnd(event) {
@@ -28997,7 +29923,14 @@ function stateMatchesRun(state, runId) {
28997
29923
  return state.metadata["flue.run_id"] === runId;
28998
29924
  }
28999
29925
  function startFlueSpan(parent, args) {
29000
- return parent ? withCurrent(parent, () => startSpan(args)) : startSpan(args);
29926
+ return parent ? withCurrent(
29927
+ parent,
29928
+ () => startSpan(
29929
+ withSpanInstrumentationName(args, INSTRUMENTATION_NAMES.FLUE)
29930
+ )
29931
+ ) : startSpan(
29932
+ withSpanInstrumentationName(args, INSTRUMENTATION_NAMES.FLUE)
29933
+ );
29001
29934
  }
29002
29935
  function runWithCurrentSpanStore(span, next) {
29003
29936
  const state = _internalGetGlobalState();
@@ -29087,9 +30020,13 @@ var BraintrustLangChainCallbackHandler = class {
29087
30020
  ...this.options.debug ? { runId, parentRunId } : {}
29088
30021
  }
29089
30022
  };
29090
- let span = parentSpan.startSpan(args);
30023
+ const spanArgs = withSpanInstrumentationName(
30024
+ args,
30025
+ INSTRUMENTATION_NAMES.LANGCHAIN
30026
+ );
30027
+ let span = parentSpan.startSpan(spanArgs);
29091
30028
  if (!Object.is(this.options.logger, NOOP_SPAN) && Object.is(span, NOOP_SPAN)) {
29092
- span = initLogger().startSpan(args);
30029
+ span = initLogger().startSpan(spanArgs);
29093
30030
  }
29094
30031
  this.spans.set(runId, span);
29095
30032
  }
@@ -29386,16 +30323,20 @@ function isRecord(value) {
29386
30323
  }
29387
30324
 
29388
30325
  // src/instrumentation/plugins/langchain-channels.ts
29389
- var langChainChannels = defineChannels("@langchain/core", {
29390
- configure: channel({
29391
- channelName: "CallbackManager.configure",
29392
- kind: "sync-stream"
29393
- }),
29394
- configureSync: channel({
29395
- channelName: "CallbackManager._configureSync",
29396
- kind: "sync-stream"
29397
- })
29398
- });
30326
+ var langChainChannels = defineChannels(
30327
+ "@langchain/core",
30328
+ {
30329
+ configure: channel({
30330
+ channelName: "CallbackManager.configure",
30331
+ kind: "sync-stream"
30332
+ }),
30333
+ configureSync: channel({
30334
+ channelName: "CallbackManager._configureSync",
30335
+ kind: "sync-stream"
30336
+ })
30337
+ },
30338
+ { instrumentationName: INSTRUMENTATION_NAMES.LANGCHAIN }
30339
+ );
29399
30340
 
29400
30341
  // src/instrumentation/plugins/langchain-plugin.ts
29401
30342
  var LangChainPlugin = class extends BasePlugin {
@@ -29483,20 +30424,24 @@ function isBraintrustHandler(handler) {
29483
30424
  }
29484
30425
 
29485
30426
  // src/instrumentation/plugins/langsmith-channels.ts
29486
- var langSmithChannels = defineChannels("langsmith", {
29487
- createRun: channel({
29488
- channelName: "Client.createRun",
29489
- kind: "async"
29490
- }),
29491
- updateRun: channel({
29492
- channelName: "Client.updateRun",
29493
- kind: "async"
29494
- }),
29495
- batchIngestRuns: channel({
29496
- channelName: "Client.batchIngestRuns",
29497
- kind: "async"
29498
- })
29499
- });
30427
+ var langSmithChannels = defineChannels(
30428
+ "langsmith",
30429
+ {
30430
+ createRun: channel({
30431
+ channelName: "Client.createRun",
30432
+ kind: "async"
30433
+ }),
30434
+ updateRun: channel({
30435
+ channelName: "Client.updateRun",
30436
+ kind: "async"
30437
+ }),
30438
+ batchIngestRuns: channel({
30439
+ channelName: "Client.batchIngestRuns",
30440
+ kind: "async"
30441
+ })
30442
+ },
30443
+ { instrumentationName: INSTRUMENTATION_NAMES.LANGSMITH }
30444
+ );
29500
30445
 
29501
30446
  // src/instrumentation/plugins/langsmith-plugin.ts
29502
30447
  var MAX_COMPLETED_RUNS = 1e4;
@@ -29660,19 +30605,24 @@ var LangSmithPlugin = class extends BasePlugin {
29660
30605
  const traceId = stringValue2(ownValue(run, "trace_id")) ?? id;
29661
30606
  const parentId = stringValue2(ownValue(run, "parent_run_id")) ?? stringValue2(ownValue(ownValue(run, "parent_run"), "id"));
29662
30607
  const startTime = timestampSeconds(ownValue(run, "start_time"));
29663
- return startSpan({
29664
- name: stringValue2(ownValue(run, "name")) ?? "LangSmith run",
29665
- spanId: id,
29666
- parentSpanIds: {
29667
- parentSpanIds: parentId ? [parentId] : [],
29668
- rootSpanId: traceId
29669
- },
29670
- spanAttributes: {
29671
- type: mapRunType(ownValue(run, "run_type"))
29672
- },
29673
- ...startTime === void 0 ? {} : { startTime },
29674
- event: { id }
29675
- });
30608
+ return startSpan(
30609
+ withSpanInstrumentationName(
30610
+ {
30611
+ name: stringValue2(ownValue(run, "name")) ?? "LangSmith run",
30612
+ spanId: id,
30613
+ parentSpanIds: {
30614
+ parentSpanIds: parentId ? [parentId] : [],
30615
+ rootSpanId: traceId
30616
+ },
30617
+ spanAttributes: {
30618
+ type: mapRunType(ownValue(run, "run_type"))
30619
+ },
30620
+ ...startTime === void 0 ? {} : { startTime },
30621
+ event: { id }
30622
+ },
30623
+ INSTRUMENTATION_NAMES.LANGSMITH
30624
+ )
30625
+ );
29676
30626
  }
29677
30627
  logRun(span, run, previous, includeOutput) {
29678
30628
  const inputs = preferOwnValue(run, previous, "inputs");
@@ -29930,7 +30880,8 @@ var piCodingAgentChannels = defineChannels(
29930
30880
  channelName: "AgentSession.prompt",
29931
30881
  kind: "async"
29932
30882
  })
29933
- }
30883
+ },
30884
+ { instrumentationName: INSTRUMENTATION_NAMES.PI_CODING_AGENT }
29934
30885
  );
29935
30886
 
29936
30887
  // src/instrumentation/plugins/pi-coding-agent-plugin.ts
@@ -30014,14 +30965,19 @@ function startPiPromptRun(event, onFinalize) {
30014
30965
  ...session.model?.id || agent.state?.model?.id ? { model: session.model?.id ?? agent.state?.model?.id } : {},
30015
30966
  ...event.moduleVersion ? { "pi_coding_agent.version": event.moduleVersion } : {}
30016
30967
  };
30017
- const span = startSpan({
30018
- event: {
30019
- input: extractPromptInput(event.arguments[0], event.arguments[1]),
30020
- metadata
30021
- },
30022
- name: "AgentSession.prompt",
30023
- spanAttributes: { type: "task" /* TASK */ }
30024
- });
30968
+ const span = startSpan(
30969
+ withSpanInstrumentationName(
30970
+ {
30971
+ event: {
30972
+ input: extractPromptInput(event.arguments[0], event.arguments[1]),
30973
+ metadata
30974
+ },
30975
+ name: "AgentSession.prompt",
30976
+ spanAttributes: { type: "task" /* TASK */ }
30977
+ },
30978
+ INSTRUMENTATION_NAMES.PI_CODING_AGENT
30979
+ )
30980
+ );
30025
30981
  const streamPatchState = installPiStreamPatch(agent);
30026
30982
  const options = event.arguments[1];
30027
30983
  const promptText = event.arguments[0];
@@ -30191,15 +31147,20 @@ async function startPiLlmSpan(state, model, context, options) {
30191
31147
  ...extractToolMetadata(context.tools),
30192
31148
  "pi_coding_agent.operation": "agent.streamFn"
30193
31149
  };
30194
- const span = startSpan({
30195
- event: {
30196
- input: processInputAttachments(normalizePiContextInput(context)),
30197
- metadata
30198
- },
30199
- name: getLlmSpanName(model),
30200
- parent: await state.span.export(),
30201
- spanAttributes: { type: "llm" /* LLM */ }
30202
- });
31150
+ const span = startSpan(
31151
+ withSpanInstrumentationName(
31152
+ {
31153
+ event: {
31154
+ input: processInputAttachments(normalizePiContextInput(context)),
31155
+ metadata
31156
+ },
31157
+ name: getLlmSpanName(model),
31158
+ parent: await state.span.export(),
31159
+ spanAttributes: { type: "llm" /* LLM */ }
31160
+ },
31161
+ INSTRUMENTATION_NAMES.PI_CODING_AGENT
31162
+ )
31163
+ );
30203
31164
  const llmState = {
30204
31165
  finalized: false,
30205
31166
  metadata,
@@ -30367,15 +31328,20 @@ async function startPiToolSpan(state, event) {
30367
31328
  "pi_coding_agent.tool.name": event.toolName
30368
31329
  };
30369
31330
  try {
30370
- const span = startSpan({
30371
- event: {
30372
- input: event.args,
30373
- metadata
30374
- },
30375
- name: event.toolName || "tool",
30376
- parent: await state.span.export(),
30377
- spanAttributes: { type: "tool" /* TOOL */ }
30378
- });
31331
+ const span = startSpan(
31332
+ withSpanInstrumentationName(
31333
+ {
31334
+ event: {
31335
+ input: event.args,
31336
+ metadata
31337
+ },
31338
+ name: event.toolName || "tool",
31339
+ parent: await state.span.export(),
31340
+ spanAttributes: { type: "tool" /* TOOL */ }
31341
+ },
31342
+ INSTRUMENTATION_NAMES.PI_CODING_AGENT
31343
+ )
31344
+ );
30379
31345
  state.activeToolSpans.set(event.toolCallId, {
30380
31346
  restoreAutoInstrumentation,
30381
31347
  span
@@ -30807,20 +31773,24 @@ function logInstrumentationError4(context, error) {
30807
31773
  }
30808
31774
 
30809
31775
  // src/instrumentation/plugins/strands-agent-sdk-channels.ts
30810
- var strandsAgentSDKChannels = defineChannels("@strands-agents/sdk", {
30811
- agentStream: channel({
30812
- channelName: "Agent.stream",
30813
- kind: "sync-stream"
30814
- }),
30815
- graphStream: channel({
30816
- channelName: "Graph.stream",
30817
- kind: "sync-stream"
30818
- }),
30819
- swarmStream: channel({
30820
- channelName: "Swarm.stream",
30821
- kind: "sync-stream"
30822
- })
30823
- });
31776
+ var strandsAgentSDKChannels = defineChannels(
31777
+ "@strands-agents/sdk",
31778
+ {
31779
+ agentStream: channel({
31780
+ channelName: "Agent.stream",
31781
+ kind: "sync-stream"
31782
+ }),
31783
+ graphStream: channel({
31784
+ channelName: "Graph.stream",
31785
+ kind: "sync-stream"
31786
+ }),
31787
+ swarmStream: channel({
31788
+ channelName: "Swarm.stream",
31789
+ kind: "sync-stream"
31790
+ })
31791
+ },
31792
+ { instrumentationName: INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK }
31793
+ );
30824
31794
 
30825
31795
  // src/instrumentation/plugins/strands-agent-sdk-plugin.ts
30826
31796
  var MAX_STRANDS_STRING_ATTACHMENT_CACHE_ENTRIES = 32;
@@ -30975,22 +31945,32 @@ function startAgentStream(event, activeChildParents) {
30975
31945
  );
30976
31946
  const span = parentSpan ? withCurrent(
30977
31947
  parentSpan,
30978
- () => startSpan({
30979
- event: {
30980
- input,
30981
- metadata
31948
+ () => startSpan(
31949
+ withSpanInstrumentationName(
31950
+ {
31951
+ event: {
31952
+ input,
31953
+ metadata
31954
+ },
31955
+ name: formatAgentSpanName(agent),
31956
+ spanAttributes: { type: "task" /* TASK */ }
31957
+ },
31958
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
31959
+ )
31960
+ )
31961
+ ) : startSpan(
31962
+ withSpanInstrumentationName(
31963
+ {
31964
+ event: {
31965
+ input,
31966
+ metadata
31967
+ },
31968
+ name: formatAgentSpanName(agent),
31969
+ spanAttributes: { type: "task" /* TASK */ }
30982
31970
  },
30983
- name: formatAgentSpanName(agent),
30984
- spanAttributes: { type: "task" /* TASK */ }
30985
- })
30986
- ) : startSpan({
30987
- event: {
30988
- input,
30989
- metadata
30990
- },
30991
- name: formatAgentSpanName(agent),
30992
- spanAttributes: { type: "task" /* TASK */ }
30993
- });
31971
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
31972
+ )
31973
+ );
30994
31974
  return {
30995
31975
  activeTools: /* @__PURE__ */ new Map(),
30996
31976
  attachmentCache,
@@ -31012,22 +31992,32 @@ function startMultiAgentStream(event, operation, activeChildParents) {
31012
31992
  const input = processStrandsInputAttachments(event.arguments[0]);
31013
31993
  const span = parentSpan ? withCurrent(
31014
31994
  parentSpan,
31015
- () => startSpan({
31016
- event: {
31017
- input,
31018
- metadata
31995
+ () => startSpan(
31996
+ withSpanInstrumentationName(
31997
+ {
31998
+ event: {
31999
+ input,
32000
+ metadata
32001
+ },
32002
+ name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
32003
+ spanAttributes: { type: "task" /* TASK */ }
32004
+ },
32005
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
32006
+ )
32007
+ )
32008
+ ) : startSpan(
32009
+ withSpanInstrumentationName(
32010
+ {
32011
+ event: {
32012
+ input,
32013
+ metadata
32014
+ },
32015
+ name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
32016
+ spanAttributes: { type: "task" /* TASK */ }
31019
32017
  },
31020
- name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
31021
- spanAttributes: { type: "task" /* TASK */ }
31022
- })
31023
- ) : startSpan({
31024
- event: {
31025
- input,
31026
- metadata
31027
- },
31028
- name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
31029
- spanAttributes: { type: "task" /* TASK */ }
31030
- });
32018
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
32019
+ )
32020
+ );
31031
32021
  return {
31032
32022
  activeNodes: /* @__PURE__ */ new Map(),
31033
32023
  finalized: false,
@@ -31129,17 +32119,22 @@ function startModelSpan(state, event) {
31129
32119
  };
31130
32120
  const span = withCurrent(
31131
32121
  state.span,
31132
- () => startSpan({
31133
- event: {
31134
- input: Array.isArray(event.agent?.messages) ? processStrandsInputAttachments(
31135
- event.agent.messages,
31136
- state.attachmentCache
31137
- ) : void 0,
31138
- metadata
31139
- },
31140
- name: formatModelSpanName(model),
31141
- spanAttributes: { type: "llm" /* LLM */ }
31142
- })
32122
+ () => startSpan(
32123
+ withSpanInstrumentationName(
32124
+ {
32125
+ event: {
32126
+ input: Array.isArray(event.agent?.messages) ? processStrandsInputAttachments(
32127
+ event.agent.messages,
32128
+ state.attachmentCache
32129
+ ) : void 0,
32130
+ metadata
32131
+ },
32132
+ name: formatModelSpanName(model),
32133
+ spanAttributes: { type: "llm" /* LLM */ }
32134
+ },
32135
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
32136
+ )
32137
+ )
31143
32138
  );
31144
32139
  state.activeModel = {
31145
32140
  metadata,
@@ -31191,20 +32186,25 @@ function startToolSpan2(state, event) {
31191
32186
  const name = extractToolName3(toolUse, event.tool);
31192
32187
  const span = withCurrent(
31193
32188
  state.span,
31194
- () => startSpan({
31195
- event: {
31196
- input: toolUse?.input,
31197
- metadata: {
31198
- "gen_ai.tool.call.id": toolUse?.toolUseId,
31199
- "gen_ai.tool.name": name,
31200
- "strands.operation": "tool.call",
31201
- "strands.tool.name": name,
31202
- provider: "strands"
31203
- }
31204
- },
31205
- name: `tool: ${name}`,
31206
- spanAttributes: { type: "tool" /* TOOL */ }
31207
- })
32189
+ () => startSpan(
32190
+ withSpanInstrumentationName(
32191
+ {
32192
+ event: {
32193
+ input: toolUse?.input,
32194
+ metadata: {
32195
+ "gen_ai.tool.call.id": toolUse?.toolUseId,
32196
+ "gen_ai.tool.name": name,
32197
+ "strands.operation": "tool.call",
32198
+ "strands.tool.name": name,
32199
+ provider: "strands"
32200
+ }
32201
+ },
32202
+ name: `tool: ${name}`,
32203
+ spanAttributes: { type: "tool" /* TOOL */ }
32204
+ },
32205
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
32206
+ )
32207
+ )
31208
32208
  );
31209
32209
  state.activeTools.set(key, {
31210
32210
  span,
@@ -31275,11 +32275,16 @@ function startNodeSpan(state, event, activeChildParents) {
31275
32275
  };
31276
32276
  const span = withCurrent(
31277
32277
  state.span,
31278
- () => startSpan({
31279
- event: { metadata },
31280
- name: `node: ${nodeId}`,
31281
- spanAttributes: { type: "task" /* TASK */ }
31282
- })
32278
+ () => startSpan(
32279
+ withSpanInstrumentationName(
32280
+ {
32281
+ event: { metadata },
32282
+ name: `node: ${nodeId}`,
32283
+ spanAttributes: { type: "task" /* TASK */ }
32284
+ },
32285
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
32286
+ )
32287
+ )
31283
32288
  );
31284
32289
  const nodeState = {
31285
32290
  ...child ? { child } : {},
@@ -33092,6 +34097,12 @@ var wrapAgentClass = (AgentClass, options = {}) => {
33092
34097
  const original = Reflect.get(instanceTarget, prop, instanceTarget);
33093
34098
  if (harnessAgent && typeof original === "function") {
33094
34099
  switch (prop) {
34100
+ case "createSession":
34101
+ return wrapHarnessAgentCreateSession(
34102
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
34103
+ original,
34104
+ harnessAgent
34105
+ );
33095
34106
  case "generate":
33096
34107
  return wrapHarnessAgentGenerate(
33097
34108
  original,
@@ -33141,6 +34152,19 @@ var wrapAgentClass = (AgentClass, options = {}) => {
33141
34152
  }
33142
34153
  });
33143
34154
  };
34155
+ var wrapHarnessAgentCreateSession = (createSession, instance) => {
34156
+ const wrapper = function(params) {
34157
+ return harnessAgentChannels.createSession.tracePromise(
34158
+ () => params === void 0 ? createSession.call(instance) : createSession.call(instance, params),
34159
+ createAISDKChannelContext(params ?? {}, { self: instance })
34160
+ );
34161
+ };
34162
+ Object.defineProperty(wrapper, "name", {
34163
+ value: "HarnessAgent.createSession",
34164
+ writable: false
34165
+ });
34166
+ return wrapper;
34167
+ };
33144
34168
  var wrapHarnessAgentGenerate = (generate, instance, channel2, name, options) => makeGenerateTextWrapper(
33145
34169
  channel2,
33146
34170
  name,
@@ -33410,12 +34434,17 @@ var BraintrustLanguageModelWrapper = class {
33410
34434
  // For the first cut, do not support custom span_info arguments. We can
33411
34435
  // propagate those via async local storage
33412
34436
  async doGenerate(options) {
33413
- const span = startSpan({
33414
- name: "Chat Completion",
33415
- spanAttributes: {
33416
- type: "llm"
33417
- }
33418
- });
34437
+ const span = startSpan(
34438
+ withSpanInstrumentationName(
34439
+ {
34440
+ name: "Chat Completion",
34441
+ spanAttributes: {
34442
+ type: "llm"
34443
+ }
34444
+ },
34445
+ INSTRUMENTATION_NAMES.AI_SDK
34446
+ )
34447
+ );
33419
34448
  const { prompt, mode, ...rest } = options;
33420
34449
  const startTime = getCurrentUnixTimestamp();
33421
34450
  try {
@@ -33446,12 +34475,17 @@ var BraintrustLanguageModelWrapper = class {
33446
34475
  async doStream(options) {
33447
34476
  const { prompt, mode, ...rest } = options;
33448
34477
  const startTime = getCurrentUnixTimestamp();
33449
- const span = startSpan({
33450
- name: "Chat Completion",
33451
- spanAttributes: {
33452
- type: "llm"
33453
- }
33454
- });
34478
+ const span = startSpan(
34479
+ withSpanInstrumentationName(
34480
+ {
34481
+ name: "Chat Completion",
34482
+ spanAttributes: {
34483
+ type: "llm"
34484
+ }
34485
+ },
34486
+ INSTRUMENTATION_NAMES.AI_SDK
34487
+ )
34488
+ );
33455
34489
  span.log({
33456
34490
  input: postProcessPrompt(prompt),
33457
34491
  metadata: {
@@ -33806,7 +34840,9 @@ function BraintrustMiddleware(config = {}) {
33806
34840
  }
33807
34841
  }
33808
34842
  };
33809
- const span = startSpan(spanArgs);
34843
+ const span = startSpan(
34844
+ withSpanInstrumentationName(spanArgs, INSTRUMENTATION_NAMES.AI_SDK)
34845
+ );
33810
34846
  try {
33811
34847
  const result = await doGenerate();
33812
34848
  const metadata = {};
@@ -33868,7 +34904,9 @@ function BraintrustMiddleware(config = {}) {
33868
34904
  }
33869
34905
  }
33870
34906
  };
33871
- const span = startSpan(spanArgs);
34907
+ const span = startSpan(
34908
+ withSpanInstrumentationName(spanArgs, INSTRUMENTATION_NAMES.AI_SDK)
34909
+ );
33872
34910
  try {
33873
34911
  const { stream, ...rest } = await doStream();
33874
34912
  const textChunks = [];
@@ -34075,7 +35113,12 @@ var EveBridge = class {
34075
35113
  };
34076
35114
  const span = withCurrent(
34077
35115
  NOOP_SPAN,
34078
- () => _internalStartSpanWithInitialMerge({ ...args, startTime })
35116
+ () => _internalStartSpanWithInitialMerge(
35117
+ withSpanInstrumentationName(
35118
+ { ...args, startTime },
35119
+ INSTRUMENTATION_NAMES.EVE
35120
+ )
35121
+ )
34079
35122
  );
34080
35123
  if (typeof rowId !== "string") {
34081
35124
  return span;
@@ -35849,17 +36892,20 @@ var BraintrustObservabilityExporter = class {
35849
36892
  }
35850
36893
  onStart(exported) {
35851
36894
  if (this.spans.has(exported.id)) return;
35852
- const args = {
35853
- name: exported.name,
35854
- spanAttributes: { type: spanTypeFor(exported.type) },
35855
- startTime: epochSeconds(exported.startTime),
35856
- // Use the Mastra span id as the Braintrust row id so that
35857
- // `logFeedback({ id: <mastra span id> })` (and Mastra's score events)
35858
- // attach to the right row. Without this, `SpanImpl` auto-generates a
35859
- // row id (`this._id = eventId ?? idGenerator.getSpanId()`) that no
35860
- // external caller could know.
35861
- event: { id: exported.id }
35862
- };
36895
+ const args = withSpanInstrumentationName(
36896
+ {
36897
+ name: exported.name,
36898
+ spanAttributes: { type: spanTypeFor(exported.type) },
36899
+ startTime: epochSeconds(exported.startTime),
36900
+ // Use the Mastra span id as the Braintrust row id so that
36901
+ // `logFeedback({ id: <mastra span id> })` (and Mastra's score events)
36902
+ // attach to the right row. Without this, `SpanImpl` auto-generates a
36903
+ // row id (`this._id = eventId ?? idGenerator.getSpanId()`) that no
36904
+ // external caller could know.
36905
+ event: { id: exported.id }
36906
+ },
36907
+ INSTRUMENTATION_NAMES.MASTRA
36908
+ );
35863
36909
  const parentRecord = exported.parentSpanId ? this.spans.get(exported.parentSpanId) : void 0;
35864
36910
  if (!this.capturedParent) {
35865
36911
  const probe = currentSpan();
@@ -41245,26 +42291,30 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
41245
42291
  }
41246
42292
  }
41247
42293
  })();
42294
+ let timeoutId;
42295
+ let abortHandler;
42296
+ const cleanupCancellation = () => {
42297
+ if (timeoutId !== void 0) {
42298
+ clearTimeout(timeoutId);
42299
+ timeoutId = void 0;
42300
+ }
42301
+ if (abortHandler && evaluator.signal) {
42302
+ evaluator.signal.removeEventListener("abort", abortHandler);
42303
+ abortHandler = void 0;
42304
+ }
42305
+ };
41248
42306
  const cancel = async () => {
41249
42307
  await new Promise((_, reject2) => {
41250
42308
  if (cancelled) {
41251
42309
  reject2(new InternalAbortError("Evaluator already cancelled"));
41252
42310
  return;
41253
42311
  }
41254
- let timeoutId;
41255
- let abortHandler;
41256
42312
  const rejectOnce = (error) => {
41257
42313
  if (cancelled) {
41258
42314
  return;
41259
42315
  }
41260
42316
  cancelled = true;
41261
- if (timeoutId) {
41262
- clearTimeout(timeoutId);
41263
- timeoutId = void 0;
41264
- }
41265
- if (abortHandler && evaluator.signal) {
41266
- evaluator.signal.removeEventListener("abort", abortHandler);
41267
- }
42317
+ cleanupCancellation();
41268
42318
  reject2(error);
41269
42319
  };
41270
42320
  if (evaluator.timeout) {
@@ -41304,6 +42354,7 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
41304
42354
  }
41305
42355
  throw e;
41306
42356
  } finally {
42357
+ cleanupCancellation();
41307
42358
  if (!collectResults) {
41308
42359
  collectedResults.length = 0;
41309
42360
  }