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
@@ -4876,7 +4876,51 @@ var SpanCache = class {
4876
4876
  };
4877
4877
 
4878
4878
  // src/span-origin.ts
4879
- var SDK_VERSION = true ? "3.24.0" : "0.0.0";
4879
+ var INSTRUMENTATION_NAMES = {
4880
+ AI_SDK: "ai-sdk",
4881
+ ANTHROPIC: "anthropic",
4882
+ BEDROCK_RUNTIME: "bedrock-runtime",
4883
+ BRAINTRUST_JS_LOGGER: "braintrust-js-logger",
4884
+ CLAUDE_AGENT_SDK: "claude-agent-sdk",
4885
+ COHERE: "cohere",
4886
+ CURSOR_SDK: "cursor-sdk",
4887
+ EVE: "eve",
4888
+ FLUE: "flue",
4889
+ GENKIT: "genkit",
4890
+ GITHUB_COPILOT: "github-copilot",
4891
+ GOOGLE_ADK: "google-adk",
4892
+ GOOGLE_GENAI: "google-genai",
4893
+ GROQ: "groq",
4894
+ HUGGINGFACE: "huggingface",
4895
+ LANGCHAIN: "langchain",
4896
+ LANGSMITH: "langsmith",
4897
+ MASTRA: "mastra",
4898
+ MISTRAL: "mistral",
4899
+ OPENAI: "openai",
4900
+ OPENAI_AGENTS: "openai-agents",
4901
+ OPENAI_CODEX: "openai-codex",
4902
+ OPENROUTER: "openrouter",
4903
+ OPENROUTER_AGENT: "openrouter-agent",
4904
+ PI_CODING_AGENT: "pi-coding-agent",
4905
+ STRANDS_AGENT_SDK: "strands-agent-sdk"
4906
+ };
4907
+ var INTERNAL_SPAN_INSTRUMENTATION_NAME = /* @__PURE__ */ Symbol.for(
4908
+ "braintrust.spanInstrumentationName"
4909
+ );
4910
+ var SDK_VERSION = true ? "3.25.0" : "0.0.0";
4911
+ function withSpanInstrumentationName(args, instrumentationName) {
4912
+ return {
4913
+ ...args,
4914
+ [INTERNAL_SPAN_INSTRUMENTATION_NAME]: instrumentationName
4915
+ };
4916
+ }
4917
+ function getSpanInstrumentationName(args) {
4918
+ if (typeof args !== "object" || args === null) {
4919
+ return void 0;
4920
+ }
4921
+ const value = args[INTERNAL_SPAN_INSTRUMENTATION_NAME];
4922
+ return isSpanInstrumentationName(value) ? value : void 0;
4923
+ }
4880
4924
  function detectSpanOriginEnvironment(explicit) {
4881
4925
  if (explicit) return explicit;
4882
4926
  const envType = isomorph_default.getEnv("BRAINTRUST_ENVIRONMENT_TYPE");
@@ -4948,6 +4992,9 @@ function mergeSpanOriginContext(context, instrumentationName, environment) {
4948
4992
  };
4949
4993
  return next;
4950
4994
  }
4995
+ function isSpanInstrumentationName(value) {
4996
+ return Object.values(INSTRUMENTATION_NAMES).some((name) => name === value);
4997
+ }
4951
4998
  function firstPresent(entries) {
4952
4999
  return entries.find(([key]) => Boolean(isomorph_default.getEnv(key)))?.[1];
4953
5000
  }
@@ -5242,6 +5289,7 @@ var BraintrustState = class _BraintrustState {
5242
5289
  });
5243
5290
  this.spanCache = new SpanCache({ disabled: loginParams.disableSpanCache });
5244
5291
  this.spanOriginEnvironment = detectSpanOriginEnvironment();
5292
+ this._internalSetTraceContextSigningSecret(loginParams.apiKey);
5245
5293
  }
5246
5294
  loginParams;
5247
5295
  id;
@@ -5279,6 +5327,18 @@ var BraintrustState = class _BraintrustState {
5279
5327
  _contextManager = null;
5280
5328
  _otelFlushCallback = null;
5281
5329
  spanOriginEnvironment;
5330
+ traceContextSigningSecret;
5331
+ /** @internal */
5332
+ _internalSetTraceContextSigningSecret(secret) {
5333
+ const normalizedSecret = secret?.trim();
5334
+ if (normalizedSecret) {
5335
+ this.traceContextSigningSecret = normalizedSecret;
5336
+ }
5337
+ }
5338
+ /** @internal */
5339
+ _internalGetTraceContextSigningSecret() {
5340
+ return (this.traceContextSigningSecret ?? this.loginToken ?? isomorph_default.getEnv("BRAINTRUST_API_KEY"))?.trim();
5341
+ }
5282
5342
  resetLoginInfo() {
5283
5343
  this.appUrl = null;
5284
5344
  this.appPublicUrl = null;
@@ -5339,6 +5399,7 @@ var BraintrustState = class _BraintrustState {
5339
5399
  this.gitMetadataSettings = other.gitMetadataSettings;
5340
5400
  this.debugLogLevel = other.debugLogLevel;
5341
5401
  this.debugLogLevelConfigured = other.debugLogLevelConfigured;
5402
+ this.traceContextSigningSecret = other.traceContextSigningSecret;
5342
5403
  setGlobalDebugLogLevel(
5343
5404
  this.debugLogLevelConfigured ? this.debugLogLevel ?? false : void 0
5344
5405
  );
@@ -5426,6 +5487,7 @@ var BraintrustState = class _BraintrustState {
5426
5487
  return this.debugLogLevelConfigured;
5427
5488
  }
5428
5489
  async login(loginParams) {
5490
+ this._internalSetTraceContextSigningSecret(loginParams.apiKey);
5429
5491
  this.setDebugLogLevel(loginParams.debugLogLevel);
5430
5492
  if (this.apiUrl && !loginParams.forceLogin) {
5431
5493
  return;
@@ -7212,6 +7274,7 @@ function initLogger(options = {}) {
7212
7274
  project_id: projectId
7213
7275
  };
7214
7276
  const state = stateArg ?? _globalState;
7277
+ state._internalSetTraceContextSigningSecret(apiKey);
7215
7278
  state.setDebugLogLevel(debugLogLevel);
7216
7279
  state.spanOriginEnvironment = detectSpanOriginEnvironment(environment);
7217
7280
  state.enforceQueueSizeLimit(true);
@@ -7736,7 +7799,9 @@ function deepCopyEvent(event) {
7736
7799
  const ATTACHMENT_MARKER_KEY = "_bt_internal_saved_attachment_marker";
7737
7800
  const attachmentMarker = ++deepCopyEventMarkerCounter;
7738
7801
  const serialized = JSON.stringify(event, (_k, v) => {
7739
- if (v instanceof SpanImpl || v instanceof NoopSpan) {
7802
+ if (v instanceof Error) {
7803
+ return v.message;
7804
+ } else if (v instanceof SpanImpl || v instanceof NoopSpan) {
7740
7805
  return `<span>`;
7741
7806
  } else if (v instanceof Experiment2) {
7742
7807
  return `<experiment>`;
@@ -8348,6 +8413,7 @@ var SpanImpl = class _SpanImpl {
8348
8413
  constructor(args) {
8349
8414
  this._state = args.state;
8350
8415
  this._propagatedState = args.propagatedState;
8416
+ const instrumentationName = getSpanInstrumentationName(args) ?? INSTRUMENTATION_NAMES.BRAINTRUST_JS_LOGGER;
8351
8417
  const spanAttributes = args.spanAttributes ?? {};
8352
8418
  const rawEvent = args.event ?? {};
8353
8419
  const type = args.type ?? (args.parentSpanIds ? void 0 : args.defaultRootType);
@@ -8379,7 +8445,7 @@ var SpanImpl = class _SpanImpl {
8379
8445
  },
8380
8446
  context: mergeSpanOriginContext(
8381
8447
  { ...callerLocation },
8382
- "braintrust-js-logger",
8448
+ instrumentationName,
8383
8449
  this._state.spanOriginEnvironment
8384
8450
  ),
8385
8451
  span_attributes: {
@@ -9604,15 +9670,25 @@ function hasChoices(value) {
9604
9670
  function normalizeMetadata(metadata) {
9605
9671
  return isObject(metadata) ? metadata : void 0;
9606
9672
  }
9607
- function startSpanForEvent(config, event, channelName) {
9673
+ function startSpanForEvent(config, event, channelName, instrumentationName) {
9608
9674
  const { name, spanAttributes, spanInfoMetadata } = buildStartSpanArgs(
9609
9675
  config,
9610
9676
  event
9611
9677
  );
9612
- const span = startSpan({
9613
- name,
9614
- spanAttributes
9615
- });
9678
+ const spanArgs = withSpanInstrumentationName(
9679
+ {
9680
+ name,
9681
+ spanAttributes
9682
+ },
9683
+ instrumentationName
9684
+ );
9685
+ let span;
9686
+ try {
9687
+ span = config.startSpan?.(spanArgs) ?? startSpan(spanArgs);
9688
+ } catch (error) {
9689
+ debugLogger.error(`Error starting span for ${channelName}:`, error);
9690
+ span = startSpan(spanArgs);
9691
+ }
9616
9692
  const startTime = getCurrentUnixTimestamp();
9617
9693
  try {
9618
9694
  const { input, metadata } = config.extractInput(
@@ -9643,7 +9719,7 @@ function shouldTraceEvent(config, event, channelName) {
9643
9719
  return true;
9644
9720
  }
9645
9721
  }
9646
- function ensureSpanStateForEvent(states, config, event, channelName) {
9722
+ function ensureSpanStateForEvent(states, config, event, channelName, instrumentationName) {
9647
9723
  const key = event;
9648
9724
  const existing = states.get(key);
9649
9725
  if (existing) {
@@ -9652,11 +9728,16 @@ function ensureSpanStateForEvent(states, config, event, channelName) {
9652
9728
  if (!shouldTraceEvent(config, event, channelName)) {
9653
9729
  return void 0;
9654
9730
  }
9655
- const created = startSpanForEvent(config, event, channelName);
9731
+ const created = startSpanForEvent(
9732
+ config,
9733
+ event,
9734
+ channelName,
9735
+ instrumentationName
9736
+ );
9656
9737
  states.set(key, created);
9657
9738
  return created;
9658
9739
  }
9659
- function bindCurrentSpanStoreToStart(tracingChannel, states, config, channelName) {
9740
+ function bindCurrentSpanStoreToStart(tracingChannel, states, config, channelName, instrumentationName) {
9660
9741
  const state = _internalGetGlobalState();
9661
9742
  const startChannel = tracingChannel.start;
9662
9743
  const contextManager = state?.contextManager;
@@ -9674,7 +9755,8 @@ function bindCurrentSpanStoreToStart(tracingChannel, states, config, channelName
9674
9755
  states,
9675
9756
  config,
9676
9757
  event,
9677
- channelName
9758
+ channelName,
9759
+ instrumentationName
9678
9760
  );
9679
9761
  return spanState ? contextManager.wrapSpanForStore(spanState.span) : currentSpanStore.getStore();
9680
9762
  }
@@ -9683,15 +9765,21 @@ function bindCurrentSpanStoreToStart(tracingChannel, states, config, channelName
9683
9765
  startChannel.unbindStore(currentSpanStore);
9684
9766
  };
9685
9767
  }
9686
- function logErrorAndEnd(states, event) {
9768
+ function logErrorAndEnd(states, event, channelName) {
9687
9769
  const spanData = states.get(event);
9688
9770
  if (!spanData) {
9689
9771
  return;
9690
9772
  }
9691
- spanData.span.log({
9692
- error: event.error.message
9693
- });
9694
- spanData.span.end();
9773
+ try {
9774
+ spanData.span.log({ error: event.error });
9775
+ } catch (error) {
9776
+ debugLogger.error(`Error logging failure for ${channelName}:`, error);
9777
+ }
9778
+ try {
9779
+ spanData.span.end();
9780
+ } catch (error) {
9781
+ debugLogger.error(`Error ending span for ${channelName}:`, error);
9782
+ }
9695
9783
  states.delete(event);
9696
9784
  }
9697
9785
  function runStreamingCompletionHook(args) {
@@ -9741,7 +9829,8 @@ function traceAsyncChannel(channel2, config) {
9741
9829
  tracingChannel,
9742
9830
  states,
9743
9831
  config,
9744
- channelName
9832
+ channelName,
9833
+ channel2.instrumentationName
9745
9834
  );
9746
9835
  const handlers = {
9747
9836
  start: (event) => {
@@ -9752,7 +9841,8 @@ function traceAsyncChannel(channel2, config) {
9752
9841
  states,
9753
9842
  config,
9754
9843
  event,
9755
- channelName
9844
+ channelName,
9845
+ channel2.instrumentationName
9756
9846
  );
9757
9847
  },
9758
9848
  asyncEnd: (event) => {
@@ -9789,7 +9879,7 @@ function traceAsyncChannel(channel2, config) {
9789
9879
  }
9790
9880
  },
9791
9881
  error: (event) => {
9792
- logErrorAndEnd(states, event);
9882
+ logErrorAndEnd(states, event, channelName);
9793
9883
  }
9794
9884
  };
9795
9885
  tracingChannel.subscribe(handlers);
@@ -9806,7 +9896,8 @@ function traceStreamingChannel(channel2, config) {
9806
9896
  tracingChannel,
9807
9897
  states,
9808
9898
  config,
9809
- channelName
9899
+ channelName,
9900
+ channel2.instrumentationName
9810
9901
  );
9811
9902
  const handlers = {
9812
9903
  start: (event) => {
@@ -9817,7 +9908,8 @@ function traceStreamingChannel(channel2, config) {
9817
9908
  states,
9818
9909
  config,
9819
9910
  event,
9820
- channelName
9911
+ channelName,
9912
+ channel2.instrumentationName
9821
9913
  );
9822
9914
  },
9823
9915
  asyncEnd: (event) => {
@@ -9836,6 +9928,7 @@ function traceStreamingChannel(channel2, config) {
9836
9928
  }
9837
9929
  },
9838
9930
  onComplete: (chunks) => {
9931
+ let completion2;
9839
9932
  try {
9840
9933
  let output;
9841
9934
  let metrics;
@@ -9866,18 +9959,11 @@ function traceStreamingChannel(channel2, config) {
9866
9959
  } else if (metrics.time_to_first_token === void 0 && chunks.length > 0) {
9867
9960
  metrics.time_to_first_token = getCurrentUnixTimestamp() - startTime;
9868
9961
  }
9869
- runStreamingCompletionHook({
9870
- channelName,
9871
- chunks,
9872
- config,
9873
- endEvent: asyncEndEvent,
9962
+ completion2 = {
9874
9963
  ...metadata !== void 0 ? { metadata } : {},
9875
9964
  metrics,
9876
- output,
9877
- result: asyncEndEvent.result,
9878
- span,
9879
- startTime
9880
- });
9965
+ output
9966
+ };
9881
9967
  span.log({
9882
9968
  output,
9883
9969
  ...metadata !== void 0 ? { metadata } : {},
@@ -9889,11 +9975,49 @@ function traceStreamingChannel(channel2, config) {
9889
9975
  error
9890
9976
  );
9891
9977
  } finally {
9892
- span.end();
9978
+ try {
9979
+ span.end();
9980
+ } catch (error) {
9981
+ debugLogger.error(
9982
+ `Error ending span for ${channelName}:`,
9983
+ error
9984
+ );
9985
+ }
9893
9986
  states.delete(event);
9894
9987
  }
9988
+ if (completion2) {
9989
+ runStreamingCompletionHook({
9990
+ channelName,
9991
+ chunks,
9992
+ config,
9993
+ endEvent: asyncEndEvent,
9994
+ ...completion2.metadata !== void 0 ? { metadata: completion2.metadata } : {},
9995
+ metrics: completion2.metrics,
9996
+ output: completion2.output,
9997
+ result: asyncEndEvent.result,
9998
+ span,
9999
+ startTime
10000
+ });
10001
+ }
9895
10002
  },
9896
10003
  onError: (error) => {
10004
+ try {
10005
+ span.log({ error });
10006
+ } catch (loggingError) {
10007
+ debugLogger.error(
10008
+ `Error logging failure for ${channelName}:`,
10009
+ loggingError
10010
+ );
10011
+ }
10012
+ try {
10013
+ span.end();
10014
+ } catch (endingError) {
10015
+ debugLogger.error(
10016
+ `Error ending span for ${channelName}:`,
10017
+ endingError
10018
+ );
10019
+ }
10020
+ states.delete(event);
9897
10021
  runStreamingErrorHook({
9898
10022
  channelName,
9899
10023
  config,
@@ -9902,11 +10026,6 @@ function traceStreamingChannel(channel2, config) {
9902
10026
  span,
9903
10027
  startTime
9904
10028
  });
9905
- span.log({
9906
- error: error.message
9907
- });
9908
- span.end();
9909
- states.delete(event);
9910
10029
  }
9911
10030
  });
9912
10031
  return;
@@ -9921,6 +10040,7 @@ function traceStreamingChannel(channel2, config) {
9921
10040
  states.delete(event);
9922
10041
  return;
9923
10042
  }
10043
+ let completion;
9924
10044
  try {
9925
10045
  const output = config.extractOutput(
9926
10046
  asyncEndEvent.result,
@@ -9935,17 +10055,11 @@ function traceStreamingChannel(channel2, config) {
9935
10055
  asyncEndEvent.result,
9936
10056
  asyncEndEvent
9937
10057
  );
9938
- runStreamingCompletionHook({
9939
- channelName,
9940
- config,
9941
- endEvent: asyncEndEvent,
10058
+ completion = {
9942
10059
  ...normalizeMetadata(metadata) !== void 0 ? { metadata: normalizeMetadata(metadata) } : {},
9943
10060
  metrics,
9944
- output,
9945
- result: asyncEndEvent.result,
9946
- span,
9947
- startTime
9948
- });
10061
+ output
10062
+ };
9949
10063
  span.log({
9950
10064
  output,
9951
10065
  ...normalizeMetadata(metadata) !== void 0 ? { metadata: normalizeMetadata(metadata) } : {},
@@ -9954,12 +10068,30 @@ function traceStreamingChannel(channel2, config) {
9954
10068
  } catch (error) {
9955
10069
  debugLogger.error(`Error extracting output for ${channelName}:`, error);
9956
10070
  } finally {
9957
- span.end();
10071
+ try {
10072
+ span.end();
10073
+ } catch (error) {
10074
+ debugLogger.error(`Error ending span for ${channelName}:`, error);
10075
+ }
9958
10076
  states.delete(event);
9959
10077
  }
10078
+ if (completion) {
10079
+ runStreamingCompletionHook({
10080
+ channelName,
10081
+ config,
10082
+ endEvent: asyncEndEvent,
10083
+ ...completion.metadata !== void 0 ? { metadata: completion.metadata } : {},
10084
+ metrics: completion.metrics,
10085
+ output: completion.output,
10086
+ result: asyncEndEvent.result,
10087
+ span,
10088
+ startTime
10089
+ });
10090
+ }
9960
10091
  },
9961
10092
  error: (event) => {
9962
10093
  const spanData = states.get(event);
10094
+ logErrorAndEnd(states, event, channelName);
9963
10095
  if (spanData) {
9964
10096
  runStreamingErrorHook({
9965
10097
  channelName,
@@ -9970,7 +10102,6 @@ function traceStreamingChannel(channel2, config) {
9970
10102
  startTime: spanData.startTime
9971
10103
  });
9972
10104
  }
9973
- logErrorAndEnd(states, event);
9974
10105
  }
9975
10106
  };
9976
10107
  tracingChannel.subscribe(handlers);
@@ -9987,7 +10118,8 @@ function traceSyncStreamChannel(channel2, config) {
9987
10118
  tracingChannel,
9988
10119
  states,
9989
10120
  config,
9990
- channelName
10121
+ channelName,
10122
+ channel2.instrumentationName
9991
10123
  );
9992
10124
  const handlers = {
9993
10125
  start: (event) => {
@@ -9998,7 +10130,8 @@ function traceSyncStreamChannel(channel2, config) {
9998
10130
  states,
9999
10131
  config,
10000
10132
  event,
10001
- channelName
10133
+ channelName,
10134
+ channel2.instrumentationName
10002
10135
  );
10003
10136
  },
10004
10137
  end: (event) => {
@@ -10092,7 +10225,7 @@ function traceSyncStreamChannel(channel2, config) {
10092
10225
  handleResolvedResult(endEvent.result);
10093
10226
  },
10094
10227
  error: (event) => {
10095
- logErrorAndEnd(states, event);
10228
+ logErrorAndEnd(states, event, channelName);
10096
10229
  }
10097
10230
  };
10098
10231
  tracingChannel.subscribe(handlers);
@@ -10271,7 +10404,8 @@ function processInputAttachments(input) {
10271
10404
  function channel(spec) {
10272
10405
  return spec;
10273
10406
  }
10274
- function defineChannels(pkg, channels) {
10407
+ function defineChannels(pkg, channels, options) {
10408
+ const { instrumentationName } = options;
10275
10409
  return Object.fromEntries(
10276
10410
  Object.entries(channels).map(([key, spec]) => {
10277
10411
  const fullChannelName = `orchestrion:${pkg}:${spec.channelName}`;
@@ -10284,6 +10418,7 @@ function defineChannels(pkg, channels) {
10284
10418
  key,
10285
10419
  {
10286
10420
  ...asyncSpec,
10421
+ instrumentationName,
10287
10422
  tracingChannel: tracingChannel2,
10288
10423
  tracePromise: (fn, context) => tracingChannel2().tracePromise(
10289
10424
  fn,
@@ -10301,6 +10436,7 @@ function defineChannels(pkg, channels) {
10301
10436
  key,
10302
10437
  {
10303
10438
  ...syncSpec,
10439
+ instrumentationName,
10304
10440
  tracingChannel,
10305
10441
  traceSync: (fn, context) => tracingChannel().traceSync(
10306
10442
  fn,
@@ -10314,44 +10450,48 @@ function defineChannels(pkg, channels) {
10314
10450
  }
10315
10451
 
10316
10452
  // src/instrumentation/plugins/openai-channels.ts
10317
- var openAIChannels = defineChannels("openai", {
10318
- chatCompletionsCreate: channel({
10319
- channelName: "chat.completions.create",
10320
- kind: "async"
10321
- }),
10322
- embeddingsCreate: channel({
10323
- channelName: "embeddings.create",
10324
- kind: "async"
10325
- }),
10326
- betaChatCompletionsParse: channel({
10327
- channelName: "beta.chat.completions.parse",
10328
- kind: "async"
10329
- }),
10330
- betaChatCompletionsStream: channel({
10331
- channelName: "beta.chat.completions.stream",
10332
- kind: "sync-stream"
10333
- }),
10334
- moderationsCreate: channel({
10335
- channelName: "moderations.create",
10336
- kind: "async"
10337
- }),
10338
- responsesCreate: channel({
10339
- channelName: "responses.create",
10340
- kind: "async"
10341
- }),
10342
- responsesStream: channel({
10343
- channelName: "responses.stream",
10344
- kind: "sync-stream"
10345
- }),
10346
- responsesParse: channel({
10347
- channelName: "responses.parse",
10348
- kind: "async"
10349
- }),
10350
- responsesCompact: channel({
10351
- channelName: "responses.compact",
10352
- kind: "async"
10353
- })
10354
- });
10453
+ var openAIChannels = defineChannels(
10454
+ "openai",
10455
+ {
10456
+ chatCompletionsCreate: channel({
10457
+ channelName: "chat.completions.create",
10458
+ kind: "async"
10459
+ }),
10460
+ embeddingsCreate: channel({
10461
+ channelName: "embeddings.create",
10462
+ kind: "async"
10463
+ }),
10464
+ betaChatCompletionsParse: channel({
10465
+ channelName: "beta.chat.completions.parse",
10466
+ kind: "async"
10467
+ }),
10468
+ betaChatCompletionsStream: channel({
10469
+ channelName: "beta.chat.completions.stream",
10470
+ kind: "sync-stream"
10471
+ }),
10472
+ moderationsCreate: channel({
10473
+ channelName: "moderations.create",
10474
+ kind: "async"
10475
+ }),
10476
+ responsesCreate: channel({
10477
+ channelName: "responses.create",
10478
+ kind: "async"
10479
+ }),
10480
+ responsesStream: channel({
10481
+ channelName: "responses.stream",
10482
+ kind: "sync-stream"
10483
+ }),
10484
+ responsesParse: channel({
10485
+ channelName: "responses.parse",
10486
+ kind: "async"
10487
+ }),
10488
+ responsesCompact: channel({
10489
+ channelName: "responses.compact",
10490
+ kind: "async"
10491
+ })
10492
+ },
10493
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENAI }
10494
+ );
10355
10495
 
10356
10496
  // src/openai-utils.ts
10357
10497
  var BRAINTRUST_CACHED_STREAM_METRIC = "__braintrust_cached_metric";
@@ -10866,16 +11006,20 @@ function aggregateResponseStreamEvents(chunks, _streamResult, endEvent) {
10866
11006
  }
10867
11007
 
10868
11008
  // src/instrumentation/plugins/openai-codex-channels.ts
10869
- var openAICodexChannels = defineChannels("@openai/codex-sdk", {
10870
- run: channel({
10871
- channelName: "Thread.run",
10872
- kind: "async"
10873
- }),
10874
- runStreamed: channel({
10875
- channelName: "Thread.runStreamed",
10876
- kind: "async"
10877
- })
10878
- });
11009
+ var openAICodexChannels = defineChannels(
11010
+ "@openai/codex-sdk",
11011
+ {
11012
+ run: channel({
11013
+ channelName: "Thread.run",
11014
+ kind: "async"
11015
+ }),
11016
+ runStreamed: channel({
11017
+ channelName: "Thread.runStreamed",
11018
+ kind: "async"
11019
+ })
11020
+ },
11021
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENAI_CODEX }
11022
+ );
10879
11023
 
10880
11024
  // src/instrumentation/plugins/openai-codex-plugin.ts
10881
11025
  var PATCHED_STREAMED_TURN = /* @__PURE__ */ Symbol.for(
@@ -10963,10 +11107,15 @@ function startCodexRun(event, operation) {
10963
11107
  provider: "openai",
10964
11108
  ...event.moduleVersion ? { "openai_codex.version": event.moduleVersion } : {}
10965
11109
  };
10966
- const span = startSpan({
10967
- name: "OpenAI Codex",
10968
- spanAttributes: { type: "task" /* TASK */ }
10969
- });
11110
+ const span = startSpan(
11111
+ withSpanInstrumentationName(
11112
+ {
11113
+ name: "OpenAI Codex",
11114
+ spanAttributes: { type: "task" /* TASK */ }
11115
+ },
11116
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
11117
+ )
11118
+ );
10970
11119
  const startTime = getCurrentUnixTimestamp();
10971
11120
  safeLog(span, {
10972
11121
  input: sanitizedInput,
@@ -11115,7 +11264,12 @@ async function createCompletedItemSpan(state, item) {
11115
11264
  if (!spanArgs) {
11116
11265
  return;
11117
11266
  }
11118
- const span = startSpan(spanArgs.start);
11267
+ const span = startSpan(
11268
+ withSpanInstrumentationName(
11269
+ spanArgs.start,
11270
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
11271
+ )
11272
+ );
11119
11273
  safeLog(span, spanArgs.end);
11120
11274
  span.end();
11121
11275
  }
@@ -11157,15 +11311,20 @@ async function ensureActiveLlmSpan(state) {
11157
11311
  ...state.metadata["openai_codex.thread_id"] ? { "openai_codex.thread_id": state.metadata["openai_codex.thread_id"] } : {},
11158
11312
  "openai_codex.llm_sequence": sequence
11159
11313
  };
11160
- const span = startSpan({
11161
- event: {
11162
- ...sequence === 1 ? { input: state.input } : {},
11163
- metadata
11164
- },
11165
- name: "OpenAI Codex LLM",
11166
- parent: await state.span.export(),
11167
- spanAttributes: { type: "llm" /* LLM */ }
11168
- });
11314
+ const span = startSpan(
11315
+ withSpanInstrumentationName(
11316
+ {
11317
+ event: {
11318
+ ...sequence === 1 ? { input: state.input } : {},
11319
+ metadata
11320
+ },
11321
+ name: "OpenAI Codex LLM",
11322
+ parent: await state.span.export(),
11323
+ spanAttributes: { type: "llm" /* LLM */ }
11324
+ },
11325
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
11326
+ )
11327
+ );
11169
11328
  state.activeLlmSpan = {
11170
11329
  anonymousMessages: [],
11171
11330
  anonymousReasoning: [],
@@ -11211,7 +11370,15 @@ async function startCodexItemSpan(state, item) {
11211
11370
  if (!spanArgs) {
11212
11371
  return;
11213
11372
  }
11214
- state.activeItemSpans.set(itemId, startSpan(spanArgs.start));
11373
+ state.activeItemSpans.set(
11374
+ itemId,
11375
+ startSpan(
11376
+ withSpanInstrumentationName(
11377
+ spanArgs.start,
11378
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
11379
+ )
11380
+ )
11381
+ );
11215
11382
  }
11216
11383
  function updateCodexItem(state, item) {
11217
11384
  if (item.type === "agent_message" && typeof item.text === "string") {
@@ -11521,20 +11688,24 @@ function extractAnthropicCacheTokens(cacheReadTokens = 0, cacheCreationTokens =
11521
11688
  }
11522
11689
 
11523
11690
  // src/instrumentation/plugins/anthropic-channels.ts
11524
- var anthropicChannels = defineChannels("@anthropic-ai/sdk", {
11525
- messagesCreate: channel({
11526
- channelName: "messages.create",
11527
- kind: "async"
11528
- }),
11529
- betaMessagesCreate: channel({
11530
- channelName: "beta.messages.create",
11531
- kind: "async"
11532
- }),
11533
- betaMessagesToolRunner: channel({
11534
- channelName: "beta.messages.toolRunner",
11535
- kind: "sync-stream"
11536
- })
11537
- });
11691
+ var anthropicChannels = defineChannels(
11692
+ "@anthropic-ai/sdk",
11693
+ {
11694
+ messagesCreate: channel({
11695
+ channelName: "messages.create",
11696
+ kind: "async"
11697
+ }),
11698
+ betaMessagesCreate: channel({
11699
+ channelName: "beta.messages.create",
11700
+ kind: "async"
11701
+ }),
11702
+ betaMessagesToolRunner: channel({
11703
+ channelName: "beta.messages.toolRunner",
11704
+ kind: "sync-stream"
11705
+ })
11706
+ },
11707
+ { instrumentationName: INSTRUMENTATION_NAMES.ANTHROPIC }
11708
+ );
11538
11709
 
11539
11710
  // src/instrumentation/plugins/anthropic-plugin.ts
11540
11711
  var ANTHROPIC_TOOL_RUNNER_TOOL_WRAPPED = /* @__PURE__ */ Symbol.for(
@@ -11607,12 +11778,17 @@ var AnthropicPlugin = class extends BasePlugin {
11607
11778
  return;
11608
11779
  }
11609
11780
  const params = event.arguments[0] ?? {};
11610
- const span = startSpan({
11611
- name: "anthropic.beta.messages.toolRunner",
11612
- spanAttributes: {
11613
- type: "task" /* TASK */
11614
- }
11615
- });
11781
+ const span = startSpan(
11782
+ withSpanInstrumentationName(
11783
+ {
11784
+ name: "anthropic.beta.messages.toolRunner",
11785
+ spanAttributes: {
11786
+ type: "task" /* TASK */
11787
+ }
11788
+ },
11789
+ INSTRUMENTATION_NAMES.ANTHROPIC
11790
+ )
11791
+ );
11616
11792
  span.log({
11617
11793
  input: processAttachmentsInInput(
11618
11794
  coalesceInput(params.messages ?? [], params.system)
@@ -11753,19 +11929,22 @@ function wrapAnthropicToolRunnerTool(tool, index, state) {
11753
11929
  return finalizeError(error);
11754
11930
  }
11755
11931
  },
11756
- {
11757
- event: {
11758
- input: getAnthropicToolRunnerInput(args),
11759
- metadata: {
11760
- "gen_ai.tool.name": toolName,
11761
- provider: "anthropic"
11932
+ withSpanInstrumentationName(
11933
+ {
11934
+ event: {
11935
+ input: getAnthropicToolRunnerInput(args),
11936
+ metadata: {
11937
+ "gen_ai.tool.name": toolName,
11938
+ provider: "anthropic"
11939
+ }
11940
+ },
11941
+ name: `tool: ${toolName}`,
11942
+ spanAttributes: {
11943
+ type: "tool" /* TOOL */
11762
11944
  }
11763
11945
  },
11764
- name: `tool: ${toolName}`,
11765
- spanAttributes: {
11766
- type: "tool" /* TOOL */
11767
- }
11768
- }
11946
+ INSTRUMENTATION_NAMES.ANTHROPIC
11947
+ )
11769
11948
  );
11770
11949
  },
11771
11950
  writable: runDescriptor?.writable ?? true
@@ -12360,57 +12539,321 @@ function currentWorkflowAgentWrapperSpan() {
12360
12539
  return void 0;
12361
12540
  }
12362
12541
 
12363
- // src/wrappers/ai-sdk/telemetry.ts
12364
- function braintrustAISDKTelemetry() {
12365
- const operations = /* @__PURE__ */ new Map();
12366
- const operationKeysByCallId = /* @__PURE__ */ new Map();
12367
- const workflowOperationKeyStore = isomorph_default.newAsyncLocalStorage();
12368
- const modelSpans = /* @__PURE__ */ new Map();
12369
- const objectSpans = /* @__PURE__ */ new Map();
12370
- const embedSpans = /* @__PURE__ */ new Map();
12371
- const rerankSpans = /* @__PURE__ */ new Map();
12372
- const toolSpans = /* @__PURE__ */ new Map();
12373
- let workflowAgentOperationCounter = 0;
12374
- const runSafely = (name, callback) => {
12375
- try {
12376
- callback();
12377
- } catch (error) {
12378
- console.error(`Error in Braintrust AI SDK telemetry ${name}:`, error);
12379
- }
12380
- };
12381
- const startChildSpan = (operationKey, name, type, event) => {
12382
- const parent = operations.get(operationKey)?.span;
12383
- const spanArgs = {
12384
- name,
12385
- spanAttributes: { type },
12386
- ...event ? { event } : {}
12387
- };
12388
- const span = parent ? parent.startSpan(spanArgs) : startSpan(spanArgs);
12389
- const state = operations.get(operationKey);
12390
- if (state && type === "llm" /* LLM */) {
12391
- state.hadModelChild = true;
12392
- }
12393
- return span;
12394
- };
12395
- const registerOperation = (state) => {
12396
- operations.set(state.operationKey, state);
12397
- const keys = operationKeysByCallId.get(state.callId) ?? [];
12398
- keys.push(state.operationKey);
12399
- operationKeysByCallId.set(state.callId, keys);
12542
+ // src/wrappers/ai-sdk/harness-agent-context.ts
12543
+ var BRAINTRUST_TURN_CONTEXT_KEY = "__braintrust_trace_context";
12544
+ var sessionTurnParents = /* @__PURE__ */ new WeakMap();
12545
+ var wrapperTurnParents = /* @__PURE__ */ new WeakMap();
12546
+ var patchedLifecycleMethods = /* @__PURE__ */ new WeakMap();
12547
+ var harnessTurnParentStore;
12548
+ function serializedTurnContext(value) {
12549
+ if (!isObject(value)) {
12550
+ return void 0;
12551
+ }
12552
+ const context = value[BRAINTRUST_TURN_CONTEXT_KEY];
12553
+ if (!isObject(context) || typeof context.parent !== "string" || typeof context.sessionId !== "string" || typeof context.signature !== "string") {
12554
+ return void 0;
12555
+ }
12556
+ const expectedSignature = signTurnContext({
12557
+ parent: context.parent,
12558
+ sessionId: context.sessionId
12559
+ });
12560
+ if (!expectedSignature || !isomorph_default.timingSafeEqual?.(context.signature, expectedSignature)) {
12561
+ return void 0;
12562
+ }
12563
+ const parent = SpanComponentsV4.fromStr(context.parent);
12564
+ if (!parent.data.row_id || !parent.data.root_span_id || !parent.data.span_id) {
12565
+ return void 0;
12566
+ }
12567
+ return {
12568
+ parent: context.parent,
12569
+ sessionId: context.sessionId
12400
12570
  };
12401
- const deleteOperation = (operationKey) => {
12402
- const state = operations.get(operationKey);
12403
- if (!state) {
12404
- return;
12405
- }
12406
- operations.delete(operationKey);
12407
- if (workflowOperationKeyStore.getStore() === operationKey) {
12408
- workflowOperationKeyStore.enterWith(void 0);
12409
- }
12410
- const keys = operationKeysByCallId.get(state.callId);
12411
- if (!keys) {
12412
- return;
12413
- }
12571
+ }
12572
+ function signTurnContext(context) {
12573
+ const secret = _internalGetGlobalState()._internalGetTraceContextSigningSecret();
12574
+ return secret ? isomorph_default.hmacSha256?.(
12575
+ secret,
12576
+ JSON.stringify([BRAINTRUST_TURN_CONTEXT_KEY, context])
12577
+ ) : void 0;
12578
+ }
12579
+ function continuationParentFromCreateSessionParams(params) {
12580
+ if (!isObject(params)) {
12581
+ return void 0;
12582
+ }
12583
+ const continuation = params.continueFrom ?? (isObject(params.resumeFrom) ? params.resumeFrom.continueFrom : void 0);
12584
+ const context = serializedTurnContext(continuation);
12585
+ if (!context) {
12586
+ return void 0;
12587
+ }
12588
+ if (params.sessionId !== context.sessionId) {
12589
+ return void 0;
12590
+ }
12591
+ return context.parent;
12592
+ }
12593
+ function exportSpanSynchronously(span) {
12594
+ const parentInfo = span.getParentInfo();
12595
+ if (!parentInfo) {
12596
+ return void 0;
12597
+ }
12598
+ const objectId = parentInfo.objectId.getSync().value;
12599
+ if (!objectId && !parentInfo.computeObjectMetadataArgs) {
12600
+ return void 0;
12601
+ }
12602
+ return new SpanComponentsV4({
12603
+ object_type: parentInfo.objectType,
12604
+ ...objectId ? { object_id: objectId } : {
12605
+ compute_object_metadata_args: parentInfo.computeObjectMetadataArgs ?? {}
12606
+ },
12607
+ row_id: span.id,
12608
+ root_span_id: span.rootSpanId,
12609
+ span_id: span.spanId
12610
+ }).toStr();
12611
+ }
12612
+ function exportedParent(parent) {
12613
+ return typeof parent === "string" ? parent : exportSpanSynchronously(parent);
12614
+ }
12615
+ function addSerializedContext(args) {
12616
+ if (!isObject(args.continuation) || args.sessionId === void 0) {
12617
+ return;
12618
+ }
12619
+ const parent = exportedParent(args.parent);
12620
+ if (!parent) {
12621
+ return;
12622
+ }
12623
+ const context = {
12624
+ parent,
12625
+ sessionId: args.sessionId
12626
+ };
12627
+ const signature = signTurnContext(context);
12628
+ if (!signature) {
12629
+ return;
12630
+ }
12631
+ Object.defineProperty(args.continuation, BRAINTRUST_TURN_CONTEXT_KEY, {
12632
+ configurable: true,
12633
+ enumerable: true,
12634
+ value: {
12635
+ ...context,
12636
+ signature
12637
+ },
12638
+ writable: true
12639
+ });
12640
+ }
12641
+ function lifecycleMethodDescriptor(session, method) {
12642
+ let owner = session;
12643
+ while (owner) {
12644
+ const descriptor = Object.getOwnPropertyDescriptor(owner, method);
12645
+ if (descriptor) {
12646
+ return { descriptor, owner };
12647
+ }
12648
+ owner = Object.getPrototypeOf(owner);
12649
+ }
12650
+ return void 0;
12651
+ }
12652
+ function patchLifecycleMethod(session, method) {
12653
+ let resolvedDescriptor;
12654
+ try {
12655
+ resolvedDescriptor = lifecycleMethodDescriptor(session, method);
12656
+ } catch {
12657
+ return;
12658
+ }
12659
+ if (!resolvedDescriptor || !("value" in resolvedDescriptor.descriptor) || typeof resolvedDescriptor.descriptor.value !== "function") {
12660
+ return;
12661
+ }
12662
+ const { descriptor, owner } = resolvedDescriptor;
12663
+ const patched = patchedLifecycleMethods.get(owner);
12664
+ if (patched?.has(method)) {
12665
+ return;
12666
+ }
12667
+ const original = descriptor.value;
12668
+ const replacement = function(...args) {
12669
+ const result = Reflect.apply(original, this, args);
12670
+ const addContext = (state) => {
12671
+ try {
12672
+ const parent = sessionTurnParents.get(this);
12673
+ if (!parent) {
12674
+ return;
12675
+ }
12676
+ const continuation = method === "suspendTurn" ? state : isObject(state) ? state.continueFrom : void 0;
12677
+ addSerializedContext({
12678
+ continuation,
12679
+ parent,
12680
+ sessionId: typeof this.sessionId === "string" ? this.sessionId : void 0
12681
+ });
12682
+ } catch {
12683
+ }
12684
+ };
12685
+ try {
12686
+ if (isObject(result) && typeof result.then === "function") {
12687
+ void Promise.resolve(result).then(addContext, () => {
12688
+ });
12689
+ } else {
12690
+ addContext(result);
12691
+ }
12692
+ } catch {
12693
+ }
12694
+ return result;
12695
+ };
12696
+ try {
12697
+ Object.defineProperty(owner, method, {
12698
+ ...descriptor,
12699
+ value: replacement
12700
+ });
12701
+ const ownerMethods = patched ?? /* @__PURE__ */ new Set();
12702
+ ownerMethods.add(method);
12703
+ if (!patched) {
12704
+ patchedLifecycleMethods.set(owner, ownerMethods);
12705
+ }
12706
+ } catch {
12707
+ }
12708
+ }
12709
+ function patchLifecycleMethods(session) {
12710
+ patchLifecycleMethod(session, "suspendTurn");
12711
+ patchLifecycleMethod(session, "detach");
12712
+ patchLifecycleMethod(session, "stop");
12713
+ }
12714
+ function registerHarnessTurnSpan(args) {
12715
+ if (!isObject(args.session)) {
12716
+ return;
12717
+ }
12718
+ const session = args.session;
12719
+ sessionTurnParents.set(session, args.span);
12720
+ wrapperTurnParents.set(args.span, args.span);
12721
+ patchLifecycleMethods(session);
12722
+ }
12723
+ function harnessContinuationParent(session) {
12724
+ return isObject(session) ? sessionTurnParents.get(session) : void 0;
12725
+ }
12726
+ function captureHarnessCreateSessionParent(params) {
12727
+ try {
12728
+ return continuationParentFromCreateSessionParams(params);
12729
+ } catch {
12730
+ return void 0;
12731
+ }
12732
+ }
12733
+ function registerHarnessSessionParent(session, parent) {
12734
+ if (!parent || !isObject(session)) {
12735
+ return;
12736
+ }
12737
+ const harnessSession = session;
12738
+ sessionTurnParents.set(harnessSession, parent);
12739
+ patchLifecycleMethods(harnessSession);
12740
+ }
12741
+ function currentHarnessTurnParent() {
12742
+ return harnessTurnParentStore?.getStore() ?? wrapperTurnParents.get(currentSpan());
12743
+ }
12744
+ function bindHarnessTurnParentToStart(tracingChannel, parentFromEvent) {
12745
+ const startChannel = tracingChannel.start;
12746
+ if (!startChannel) {
12747
+ return () => {
12748
+ };
12749
+ }
12750
+ harnessTurnParentStore ??= isomorph_default.newAsyncLocalStorage();
12751
+ const store = harnessTurnParentStore;
12752
+ startChannel.bindStore(
12753
+ store,
12754
+ (event) => parentFromEvent(event) ?? store.getStore()
12755
+ );
12756
+ return () => {
12757
+ startChannel.unbindStore(store);
12758
+ };
12759
+ }
12760
+ function startHarnessTurnChildSpan(parent, args) {
12761
+ const spanArgs = withSpanInstrumentationName(
12762
+ args,
12763
+ INSTRUMENTATION_NAMES.AI_SDK
12764
+ );
12765
+ return typeof parent === "string" ? startSpan({ ...spanArgs, parent }) : parent.startSpan(spanArgs);
12766
+ }
12767
+ function updateHarnessTurn(parent, update = {}) {
12768
+ if (!parent) {
12769
+ return;
12770
+ }
12771
+ const log = (event) => {
12772
+ if (typeof parent === "string") {
12773
+ updateSpan({ exported: parent, ...event });
12774
+ } else {
12775
+ parent.log(event);
12776
+ }
12777
+ };
12778
+ try {
12779
+ if (Object.prototype.hasOwnProperty.call(update, "output")) {
12780
+ log({ output: null });
12781
+ }
12782
+ log(update);
12783
+ } catch {
12784
+ }
12785
+ }
12786
+ function endHarnessTurn(parent) {
12787
+ const endTime = getCurrentUnixTimestamp();
12788
+ if (!parent) {
12789
+ return endTime;
12790
+ }
12791
+ try {
12792
+ const event = { metrics: { end: endTime } };
12793
+ if (typeof parent === "string") {
12794
+ updateSpan({ exported: parent, ...event });
12795
+ } else {
12796
+ parent.log(event);
12797
+ }
12798
+ } catch {
12799
+ }
12800
+ return endTime;
12801
+ }
12802
+
12803
+ // src/wrappers/ai-sdk/telemetry.ts
12804
+ function braintrustAISDKTelemetry() {
12805
+ const operations = /* @__PURE__ */ new Map();
12806
+ const operationKeysByCallId = /* @__PURE__ */ new Map();
12807
+ const workflowOperationKeyStore = isomorph_default.newAsyncLocalStorage();
12808
+ const modelSpans = /* @__PURE__ */ new Map();
12809
+ const objectSpans = /* @__PURE__ */ new Map();
12810
+ const embedSpans = /* @__PURE__ */ new Map();
12811
+ const rerankSpans = /* @__PURE__ */ new Map();
12812
+ const toolSpans = /* @__PURE__ */ new Map();
12813
+ let workflowAgentOperationCounter = 0;
12814
+ const runSafely = (name, callback) => {
12815
+ try {
12816
+ callback();
12817
+ } catch (error) {
12818
+ console.error(`Error in Braintrust AI SDK telemetry ${name}:`, error);
12819
+ }
12820
+ };
12821
+ const startChildSpan = (operationKey, name, type, event, parentOverride) => {
12822
+ const parent = operations.get(operationKey)?.span;
12823
+ const spanArgs = withSpanInstrumentationName(
12824
+ {
12825
+ name,
12826
+ spanAttributes: { type },
12827
+ ...event ? { event } : {}
12828
+ },
12829
+ INSTRUMENTATION_NAMES.AI_SDK
12830
+ );
12831
+ const span = parentOverride ? startHarnessTurnChildSpan(parentOverride, spanArgs) : parent ? parent.startSpan(spanArgs) : startSpan(spanArgs);
12832
+ const state = operations.get(operationKey);
12833
+ if (state && type === "llm" /* LLM */) {
12834
+ state.hadModelChild = true;
12835
+ }
12836
+ return span;
12837
+ };
12838
+ const registerOperation = (state) => {
12839
+ operations.set(state.operationKey, state);
12840
+ const keys = operationKeysByCallId.get(state.callId) ?? [];
12841
+ keys.push(state.operationKey);
12842
+ operationKeysByCallId.set(state.callId, keys);
12843
+ };
12844
+ const deleteOperation = (operationKey) => {
12845
+ const state = operations.get(operationKey);
12846
+ if (!state) {
12847
+ return;
12848
+ }
12849
+ operations.delete(operationKey);
12850
+ if (workflowOperationKeyStore.getStore() === operationKey) {
12851
+ workflowOperationKeyStore.enterWith(void 0);
12852
+ }
12853
+ const keys = operationKeysByCallId.get(state.callId);
12854
+ if (!keys) {
12855
+ return;
12856
+ }
12414
12857
  const index = keys.indexOf(operationKey);
12415
12858
  if (index >= 0) {
12416
12859
  keys.splice(index, 1);
@@ -12665,14 +13108,30 @@ function braintrustAISDKTelemetry() {
12665
13108
  const workflowAgent = operationName === "WorkflowAgent.stream";
12666
13109
  const wrapperSpan = workflowAgent ? currentWorkflowAgentWrapperSpan() : void 0;
12667
13110
  const ownsSpan = !wrapperSpan;
12668
- const span = ownsSpan ? startSpan({
12669
- name: operationName,
12670
- spanAttributes: { type: "function" /* FUNCTION */ }
12671
- }) : wrapperSpan;
13111
+ const harnessTurnParent = currentHarnessTurnParent();
13112
+ const span = ownsSpan ? harnessTurnParent ? startHarnessTurnChildSpan(
13113
+ harnessTurnParent,
13114
+ withSpanInstrumentationName(
13115
+ {
13116
+ name: operationName,
13117
+ spanAttributes: { type: "function" /* FUNCTION */ }
13118
+ },
13119
+ INSTRUMENTATION_NAMES.AI_SDK
13120
+ )
13121
+ ) : startSpan(
13122
+ withSpanInstrumentationName(
13123
+ {
13124
+ name: operationName,
13125
+ spanAttributes: { type: "function" /* FUNCTION */ }
13126
+ },
13127
+ INSTRUMENTATION_NAMES.AI_SDK
13128
+ )
13129
+ ) : wrapperSpan;
12672
13130
  const operationKey = createOperationKey(event, operationName);
12673
13131
  registerOperation({
12674
13132
  callId: event.callId,
12675
13133
  hadModelChild: false,
13134
+ harnessTurnParent,
12676
13135
  loggedInput: false,
12677
13136
  operationName,
12678
13137
  operationKey,
@@ -12913,7 +13372,8 @@ function braintrustAISDKTelemetry() {
12913
13372
  toolCallId,
12914
13373
  ...typeof event.toolCall.toolName === "string" ? { toolName: event.toolCall.toolName } : {}
12915
13374
  }
12916
- }
13375
+ },
13376
+ state?.harnessTurnParent
12917
13377
  );
12918
13378
  toolSpans.set(toolCallId, { operationKey, span });
12919
13379
  });
@@ -13149,92 +13609,102 @@ function finishOutput(result, operationName) {
13149
13609
  }
13150
13610
 
13151
13611
  // src/instrumentation/plugins/ai-sdk-channels.ts
13152
- var aiSDKChannels = defineChannels("ai", {
13153
- generateText: channel({
13154
- channelName: "generateText",
13155
- kind: "async"
13156
- }),
13157
- streamText: channel({
13158
- channelName: "streamText",
13159
- kind: "async"
13160
- }),
13161
- streamTextSync: channel({
13162
- channelName: "streamText.sync",
13163
- kind: "sync-stream"
13164
- }),
13165
- generateObject: channel({
13166
- channelName: "generateObject",
13167
- kind: "async"
13168
- }),
13169
- streamObject: channel({
13170
- channelName: "streamObject",
13171
- kind: "async"
13172
- }),
13173
- streamObjectSync: channel({
13174
- channelName: "streamObject.sync",
13175
- kind: "sync-stream"
13176
- }),
13177
- embed: channel(
13178
- {
13612
+ var aiSDKChannels = defineChannels(
13613
+ "ai",
13614
+ {
13615
+ generateText: channel({
13616
+ channelName: "generateText",
13617
+ kind: "async"
13618
+ }),
13619
+ streamText: channel({
13620
+ channelName: "streamText",
13621
+ kind: "async"
13622
+ }),
13623
+ streamTextSync: channel({
13624
+ channelName: "streamText.sync",
13625
+ kind: "sync-stream"
13626
+ }),
13627
+ generateObject: channel({
13628
+ channelName: "generateObject",
13629
+ kind: "async"
13630
+ }),
13631
+ streamObject: channel({
13632
+ channelName: "streamObject",
13633
+ kind: "async"
13634
+ }),
13635
+ streamObjectSync: channel({
13636
+ channelName: "streamObject.sync",
13637
+ kind: "sync-stream"
13638
+ }),
13639
+ embed: channel({
13179
13640
  channelName: "embed",
13180
13641
  kind: "async"
13181
- }
13182
- ),
13183
- embedMany: channel({
13184
- channelName: "embedMany",
13185
- kind: "async"
13186
- }),
13187
- rerank: channel({
13188
- channelName: "rerank",
13189
- kind: "async"
13190
- }),
13191
- agentGenerate: channel({
13192
- channelName: "Agent.generate",
13193
- kind: "async"
13194
- }),
13195
- agentStream: channel({
13196
- channelName: "Agent.stream",
13197
- kind: "async"
13198
- }),
13199
- agentStreamSync: channel({
13200
- channelName: "Agent.stream.sync",
13201
- kind: "sync-stream"
13202
- }),
13203
- toolLoopAgentGenerate: channel({
13204
- channelName: "ToolLoopAgent.generate",
13205
- kind: "async"
13206
- }),
13207
- toolLoopAgentStream: channel({
13208
- channelName: "ToolLoopAgent.stream",
13209
- kind: "async"
13210
- }),
13211
- workflowAgentStream: channel({
13212
- channelName: "WorkflowAgent.stream",
13213
- kind: "async"
13214
- }),
13215
- v7CreateTelemetryDispatcher: channel({
13216
- channelName: "createTelemetryDispatcher",
13217
- kind: "sync-stream"
13218
- })
13219
- });
13220
- var harnessAgentChannels = defineChannels("@ai-sdk/harness", {
13221
- generate: channel({
13222
- channelName: "HarnessAgent.generate",
13223
- kind: "async"
13224
- }),
13225
- stream: channel({
13226
- channelName: "HarnessAgent.stream",
13227
- kind: "async"
13228
- }),
13229
- continueGenerate: channel({
13230
- channelName: "HarnessAgent.continueGenerate",
13231
- kind: "async"
13232
- }),
13233
- continueStream: channel({
13234
- channelName: "HarnessAgent.continueStream",
13235
- kind: "async"
13236
- })
13237
- });
13642
+ }),
13643
+ embedMany: channel({
13644
+ channelName: "embedMany",
13645
+ kind: "async"
13646
+ }),
13647
+ rerank: channel({
13648
+ channelName: "rerank",
13649
+ kind: "async"
13650
+ }),
13651
+ agentGenerate: channel({
13652
+ channelName: "Agent.generate",
13653
+ kind: "async"
13654
+ }),
13655
+ agentStream: channel({
13656
+ channelName: "Agent.stream",
13657
+ kind: "async"
13658
+ }),
13659
+ agentStreamSync: channel({
13660
+ channelName: "Agent.stream.sync",
13661
+ kind: "sync-stream"
13662
+ }),
13663
+ toolLoopAgentGenerate: channel({
13664
+ channelName: "ToolLoopAgent.generate",
13665
+ kind: "async"
13666
+ }),
13667
+ toolLoopAgentStream: channel({
13668
+ channelName: "ToolLoopAgent.stream",
13669
+ kind: "async"
13670
+ }),
13671
+ workflowAgentStream: channel({
13672
+ channelName: "WorkflowAgent.stream",
13673
+ kind: "async"
13674
+ }),
13675
+ v7CreateTelemetryDispatcher: channel({
13676
+ channelName: "createTelemetryDispatcher",
13677
+ kind: "sync-stream"
13678
+ })
13679
+ },
13680
+ { instrumentationName: INSTRUMENTATION_NAMES.AI_SDK }
13681
+ );
13682
+ var harnessAgentChannels = defineChannels(
13683
+ "@ai-sdk/harness",
13684
+ {
13685
+ createSession: channel({
13686
+ channelName: "HarnessAgent.createSession",
13687
+ kind: "async"
13688
+ }),
13689
+ generate: channel({
13690
+ channelName: "HarnessAgent.generate",
13691
+ kind: "async"
13692
+ }),
13693
+ stream: channel({
13694
+ channelName: "HarnessAgent.stream",
13695
+ kind: "async"
13696
+ }),
13697
+ continueGenerate: channel({
13698
+ channelName: "HarnessAgent.continueGenerate",
13699
+ kind: "async"
13700
+ }),
13701
+ continueStream: channel({
13702
+ channelName: "HarnessAgent.continueStream",
13703
+ kind: "async"
13704
+ })
13705
+ },
13706
+ { instrumentationName: INSTRUMENTATION_NAMES.AI_SDK }
13707
+ );
13238
13708
 
13239
13709
  // src/instrumentation/plugins/ai-sdk-plugin.ts
13240
13710
  var DEFAULT_DENY_OUTPUT_PATHS = [
@@ -13311,6 +13781,17 @@ var AISDKPlugin = class extends BasePlugin {
13311
13781
  subscribeToAISDK() {
13312
13782
  const denyOutputPaths = this.config.denyOutputPaths || DEFAULT_DENY_OUTPUT_PATHS;
13313
13783
  this.unsubscribers.push(subscribeToAISDKV7TelemetryDispatcher());
13784
+ this.unsubscribers.push(subscribeToHarnessAgentCreateSession());
13785
+ this.unsubscribers.push(
13786
+ subscribeToHarnessContinuation(
13787
+ harnessAgentChannels.continueGenerate,
13788
+ denyOutputPaths
13789
+ ),
13790
+ subscribeToHarnessContinuation(
13791
+ harnessAgentChannels.continueStream,
13792
+ denyOutputPaths
13793
+ )
13794
+ );
13314
13795
  this.unsubscribers.push(
13315
13796
  traceStreamingChannel(aiSDKChannels.generateText, {
13316
13797
  name: "generateText",
@@ -13506,8 +13987,9 @@ var AISDKPlugin = class extends BasePlugin {
13506
13987
  this.unsubscribers.push(
13507
13988
  traceStreamingChannel(harnessAgentChannels.generate, {
13508
13989
  name: "HarnessAgent.generate",
13990
+ startSpan: _internalStartSpanWithInitialMerge,
13509
13991
  type: "task" /* TASK */,
13510
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
13992
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
13511
13993
  extractOutput: (result, endEvent) => processAISDKOutput(
13512
13994
  result,
13513
13995
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -13519,8 +14001,9 @@ var AISDKPlugin = class extends BasePlugin {
13519
14001
  this.unsubscribers.push(
13520
14002
  traceStreamingChannel(harnessAgentChannels.stream, {
13521
14003
  name: "HarnessAgent.stream",
14004
+ startSpan: _internalStartSpanWithInitialMerge,
13522
14005
  type: "task" /* TASK */,
13523
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
14006
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
13524
14007
  extractOutput: (result, endEvent) => processAISDKOutput(
13525
14008
  result,
13526
14009
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -13545,8 +14028,10 @@ var AISDKPlugin = class extends BasePlugin {
13545
14028
  this.unsubscribers.push(
13546
14029
  traceStreamingChannel(harnessAgentChannels.continueGenerate, {
13547
14030
  name: "HarnessAgent.continueGenerate",
14031
+ shouldTrace: (args) => !harnessContinuationParent(harnessSessionFromArguments(args)),
14032
+ startSpan: _internalStartSpanWithInitialMerge,
13548
14033
  type: "task" /* TASK */,
13549
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
14034
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
13550
14035
  extractOutput: (result, endEvent) => processAISDKOutput(
13551
14036
  result,
13552
14037
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -13558,8 +14043,10 @@ var AISDKPlugin = class extends BasePlugin {
13558
14043
  this.unsubscribers.push(
13559
14044
  traceStreamingChannel(harnessAgentChannels.continueStream, {
13560
14045
  name: "HarnessAgent.continueStream",
14046
+ shouldTrace: (args) => !harnessContinuationParent(harnessSessionFromArguments(args)),
14047
+ startSpan: _internalStartSpanWithInitialMerge,
13561
14048
  type: "task" /* TASK */,
13562
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
14049
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
13563
14050
  extractOutput: (result, endEvent) => processAISDKOutput(
13564
14051
  result,
13565
14052
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -13651,6 +14138,8 @@ var AISDKPlugin = class extends BasePlugin {
13651
14138
  defaultDenyOutputPaths: denyOutputPaths,
13652
14139
  endEvent,
13653
14140
  onComplete: () => unregisterWorkflowAgentWrapperSpan(span),
14141
+ onCancel: () => unregisterWorkflowAgentWrapperSpan(span),
14142
+ onError: () => unregisterWorkflowAgentWrapperSpan(span),
13654
14143
  result,
13655
14144
  span,
13656
14145
  startTime
@@ -13659,6 +14148,153 @@ var AISDKPlugin = class extends BasePlugin {
13659
14148
  );
13660
14149
  }
13661
14150
  };
14151
+ function subscribeToHarnessAgentCreateSession() {
14152
+ const channel2 = harnessAgentChannels.createSession.tracingChannel();
14153
+ const parents = /* @__PURE__ */ new WeakMap();
14154
+ const handlers = {
14155
+ start: (event) => {
14156
+ const parent = captureHarnessCreateSessionParent(event.arguments?.[0]);
14157
+ if (parent) {
14158
+ parents.set(event, parent);
14159
+ }
14160
+ },
14161
+ asyncEnd: (event) => {
14162
+ registerHarnessSessionParent(event.result, parents.get(event));
14163
+ parents.delete(event);
14164
+ },
14165
+ error: (event) => {
14166
+ parents.delete(event);
14167
+ }
14168
+ };
14169
+ channel2.subscribe(handlers);
14170
+ return () => channel2.unsubscribe(handlers);
14171
+ }
14172
+ function harnessContinuationParentFromEvent(event) {
14173
+ try {
14174
+ return harnessContinuationParent(event.arguments?.[0]?.session);
14175
+ } catch {
14176
+ return void 0;
14177
+ }
14178
+ }
14179
+ function subscribeToHarnessContinuation(continuationChannel, defaultDenyOutputPaths) {
14180
+ const channel2 = continuationChannel.tracingChannel();
14181
+ const parents = /* @__PURE__ */ new WeakMap();
14182
+ const startTimes = /* @__PURE__ */ new WeakMap();
14183
+ const unbindParentStore = bindHarnessTurnParentToStart(
14184
+ channel2,
14185
+ harnessContinuationParentFromEvent
14186
+ );
14187
+ const handlers = {
14188
+ start: (event) => {
14189
+ const parent = harnessContinuationParentFromEvent(event);
14190
+ if (!parent) {
14191
+ return;
14192
+ }
14193
+ parents.set(event, parent);
14194
+ startTimes.set(event, getCurrentUnixTimestamp());
14195
+ try {
14196
+ const params = event.arguments?.[0];
14197
+ if (params) {
14198
+ prepareAISDKHarnessAgentInput(params, event.self);
14199
+ }
14200
+ } catch (error) {
14201
+ debugLogger.error(
14202
+ "Error preparing Harness continuation telemetry:",
14203
+ error
14204
+ );
14205
+ }
14206
+ },
14207
+ asyncEnd: (event) => {
14208
+ const parent = parents.get(event);
14209
+ const startTime = startTimes.get(event) ?? getCurrentUnixTimestamp();
14210
+ parents.delete(event);
14211
+ startTimes.delete(event);
14212
+ if (!parent) {
14213
+ return;
14214
+ }
14215
+ const endEvent = event;
14216
+ const span = {
14217
+ end: () => endHarnessTurn(parent),
14218
+ log: (update) => updateHarnessTurn(
14219
+ parent,
14220
+ Object.prototype.hasOwnProperty.call(update, "error") && !Object.prototype.hasOwnProperty.call(update, "output") ? { ...update, output: null } : update
14221
+ )
14222
+ };
14223
+ try {
14224
+ if (isAsyncIterable(endEvent.result)) {
14225
+ patchStreamIfNeeded(endEvent.result, {
14226
+ onComplete: (chunks) => {
14227
+ try {
14228
+ const { metadata, metrics, output } = aggregateAISDKChunks(
14229
+ chunks,
14230
+ endEvent.result,
14231
+ endEvent
14232
+ );
14233
+ span.log({
14234
+ ...metadata ? { metadata } : {},
14235
+ metrics,
14236
+ output
14237
+ });
14238
+ } catch (error) {
14239
+ debugLogger.error(
14240
+ "Error aggregating Harness continuation stream:",
14241
+ error
14242
+ );
14243
+ } finally {
14244
+ span.end();
14245
+ }
14246
+ },
14247
+ onError: (error) => {
14248
+ span.log({ error: toLoggedError(error), output: null });
14249
+ span.end();
14250
+ }
14251
+ });
14252
+ return;
14253
+ }
14254
+ if (patchAISDKStreamingResult({
14255
+ defaultDenyOutputPaths,
14256
+ endEvent,
14257
+ result: endEvent.result,
14258
+ resolvePromiseUsage: true,
14259
+ span,
14260
+ startTime
14261
+ })) {
14262
+ return;
14263
+ }
14264
+ finalizeAISDKChildTracing(endEvent);
14265
+ span.log({
14266
+ metrics: extractTokenMetrics(endEvent.result),
14267
+ output: processAISDKOutput(
14268
+ endEvent.result,
14269
+ resolveDenyOutputPaths(endEvent, defaultDenyOutputPaths)
14270
+ )
14271
+ });
14272
+ span.end();
14273
+ } catch (error) {
14274
+ debugLogger.error("Error tracing Harness continuation:", error);
14275
+ span.end();
14276
+ }
14277
+ },
14278
+ error: (event) => {
14279
+ const parent = parents.get(event);
14280
+ parents.delete(event);
14281
+ startTimes.delete(event);
14282
+ if (!parent) {
14283
+ return;
14284
+ }
14285
+ updateHarnessTurn(parent, {
14286
+ error: toLoggedError(event.error),
14287
+ output: null
14288
+ });
14289
+ endHarnessTurn(parent);
14290
+ }
14291
+ };
14292
+ channel2.subscribe(handlers);
14293
+ return () => {
14294
+ unbindParentStore();
14295
+ channel2.unsubscribe(handlers);
14296
+ };
14297
+ }
13662
14298
  function subscribeToAISDKV7TelemetryDispatcher() {
13663
14299
  const channel2 = aiSDKChannels.v7CreateTelemetryDispatcher.tracingChannel();
13664
14300
  const telemetry = braintrustAISDKTelemetry();
@@ -14111,7 +14747,13 @@ function prepareAISDKCallInput(params, event, span, defaultDenyOutputPaths, chil
14111
14747
  metadata
14112
14748
  };
14113
14749
  }
14114
- function prepareAISDKHarnessAgentInput(params, self) {
14750
+ function prepareAISDKHarnessAgentInput(params, self, span) {
14751
+ if (span) {
14752
+ registerHarnessTurnSpan({
14753
+ session: params.session,
14754
+ span
14755
+ });
14756
+ }
14115
14757
  if (isObject(self)) {
14116
14758
  try {
14117
14759
  if (isObject(self.settings)) {
@@ -14150,6 +14792,10 @@ function prepareAISDKHarnessAgentInput(params, self) {
14150
14792
  metadata
14151
14793
  };
14152
14794
  }
14795
+ function harnessSessionFromArguments(args) {
14796
+ const params = args[0];
14797
+ return isObject(params) ? params.session : void 0;
14798
+ }
14153
14799
  function prepareAISDKWorkflowAgentStreamInput(params, event, span, defaultDenyOutputPaths) {
14154
14800
  registerWorkflowAgentWrapperSpan(span);
14155
14801
  const { input } = processAISDKWorkflowAgentCallInput(params);
@@ -14597,19 +15243,22 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
14597
15243
  activeEntry.openSpans.delete(span);
14598
15244
  }
14599
15245
  },
14600
- {
14601
- name: "doGenerate",
14602
- spanAttributes: {
14603
- type: "llm" /* LLM */
14604
- },
14605
- event: buildAISDKModelStartEvent(
14606
- callOptions,
14607
- activeEntry.baseMetadata,
14608
- {
14609
- workflowAgent: activeEntry.childTracingOptions.workflowAgent
14610
- }
14611
- )
14612
- }
15246
+ withSpanInstrumentationName(
15247
+ {
15248
+ name: "doGenerate",
15249
+ spanAttributes: {
15250
+ type: "llm" /* LLM */
15251
+ },
15252
+ event: buildAISDKModelStartEvent(
15253
+ callOptions,
15254
+ activeEntry.baseMetadata,
15255
+ {
15256
+ workflowAgent: activeEntry.childTracingOptions.workflowAgent
15257
+ }
15258
+ )
15259
+ },
15260
+ INSTRUMENTATION_NAMES.AI_SDK
15261
+ )
14613
15262
  );
14614
15263
  };
14615
15264
  if (originalDoStream) {
@@ -14619,19 +15268,24 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
14619
15268
  return Reflect.apply(originalDoStream, resolvedModel, [callOptions]);
14620
15269
  }
14621
15270
  closeOpenAISDKModelPatchSpans(activeEntry);
14622
- const span = activeEntry.parentSpan.startSpan({
14623
- name: "doStream",
14624
- spanAttributes: {
14625
- type: "llm" /* LLM */
14626
- },
14627
- event: buildAISDKModelStartEvent(
14628
- callOptions,
14629
- activeEntry.baseMetadata,
15271
+ const span = activeEntry.parentSpan.startSpan(
15272
+ withSpanInstrumentationName(
14630
15273
  {
14631
- workflowAgent: activeEntry.childTracingOptions.workflowAgent
14632
- }
15274
+ name: "doStream",
15275
+ spanAttributes: {
15276
+ type: "llm" /* LLM */
15277
+ },
15278
+ event: buildAISDKModelStartEvent(
15279
+ callOptions,
15280
+ activeEntry.baseMetadata,
15281
+ {
15282
+ workflowAgent: activeEntry.childTracingOptions.workflowAgent
15283
+ }
15284
+ )
15285
+ },
15286
+ INSTRUMENTATION_NAMES.AI_SDK
14633
15287
  )
14634
- });
15288
+ );
14635
15289
  activeEntry.openSpans.add(span);
14636
15290
  const streamStartTime = getCurrentUnixTimestamp();
14637
15291
  const result = await withCurrent(
@@ -14803,12 +15457,17 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
14803
15457
  }
14804
15458
  if (isAsyncGenerator(result)) {
14805
15459
  return (async function* () {
14806
- const span = activeEntry.parentSpan.startSpan({
14807
- name: activeEntry.name,
14808
- spanAttributes: {
14809
- type: "tool" /* TOOL */
14810
- }
14811
- });
15460
+ const span = activeEntry.parentSpan.startSpan(
15461
+ withSpanInstrumentationName(
15462
+ {
15463
+ name: activeEntry.name,
15464
+ spanAttributes: {
15465
+ type: "tool" /* TOOL */
15466
+ }
15467
+ },
15468
+ INSTRUMENTATION_NAMES.AI_SDK
15469
+ )
15470
+ );
14812
15471
  span.log({ input: serializeToolExecutionInput(args) });
14813
15472
  try {
14814
15473
  let lastValue;
@@ -14832,12 +15491,15 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
14832
15491
  span.log({ output: awaitedResult });
14833
15492
  return awaitedResult;
14834
15493
  },
14835
- {
14836
- name: activeEntry.name,
14837
- spanAttributes: {
14838
- type: "tool" /* TOOL */
14839
- }
14840
- }
15494
+ withSpanInstrumentationName(
15495
+ {
15496
+ name: activeEntry.name,
15497
+ spanAttributes: {
15498
+ type: "tool" /* TOOL */
15499
+ }
15500
+ },
15501
+ INSTRUMENTATION_NAMES.AI_SDK
15502
+ )
14841
15503
  );
14842
15504
  };
14843
15505
  cleanup.push(() => {
@@ -14996,6 +15658,8 @@ function patchAISDKStreamingResult(args) {
14996
15658
  defaultDenyOutputPaths,
14997
15659
  endEvent,
14998
15660
  onComplete,
15661
+ onCancel,
15662
+ onError,
14999
15663
  result,
15000
15664
  resolvePromiseUsage,
15001
15665
  span,
@@ -15007,14 +15671,43 @@ function patchAISDKStreamingResult(args) {
15007
15671
  const resultRecord = result;
15008
15672
  attachKnownResultPromiseHandlers(resultRecord);
15009
15673
  let finalized = false;
15010
- const finalize = () => {
15674
+ const finalize = (outcome) => {
15011
15675
  if (finalized) {
15012
15676
  return;
15013
15677
  }
15014
15678
  finalized = true;
15015
- finalizeAISDKChildTracing(endEvent);
15016
- span.end();
15017
- onComplete?.();
15679
+ try {
15680
+ finalizeAISDKChildTracing(endEvent);
15681
+ } catch (error) {
15682
+ debugLogger.error("Error finalizing AI SDK child tracing:", error);
15683
+ }
15684
+ try {
15685
+ span.end();
15686
+ } catch (error) {
15687
+ debugLogger.error("Error ending AI SDK streaming span:", error);
15688
+ }
15689
+ if (outcome && "error" in outcome) {
15690
+ try {
15691
+ onError?.(outcome.error);
15692
+ } catch (error) {
15693
+ debugLogger.error("Error in AI SDK streaming error hook:", error);
15694
+ }
15695
+ } else if (outcome) {
15696
+ try {
15697
+ onComplete?.(outcome);
15698
+ } catch (error) {
15699
+ debugLogger.error("Error in AI SDK streaming completion hook:", error);
15700
+ }
15701
+ } else {
15702
+ try {
15703
+ onCancel?.();
15704
+ } catch (error) {
15705
+ debugLogger.error(
15706
+ "Error in AI SDK streaming cancellation hook:",
15707
+ error
15708
+ );
15709
+ }
15710
+ }
15018
15711
  };
15019
15712
  let outputLogged = false;
15020
15713
  const logStreamingOutput = async (firstChunkTime) => {
@@ -15048,15 +15741,29 @@ function patchAISDKStreamingResult(args) {
15048
15741
  resolveDenyOutputPaths(endEvent, defaultDenyOutputPaths)
15049
15742
  );
15050
15743
  const metadata = buildResolvedMetadataPayload(result).metadata;
15051
- span.log({
15052
- output,
15053
- ...metadata ? { metadata } : {},
15054
- metrics
15055
- });
15744
+ try {
15745
+ span.log({
15746
+ output,
15747
+ ...metadata ? { metadata } : {},
15748
+ metrics
15749
+ });
15750
+ } catch (error) {
15751
+ debugLogger.error("Error logging AI SDK streaming output:", error);
15752
+ }
15753
+ finalize({ metrics, output });
15056
15754
  } catch (error) {
15057
- span.log({ error: toLoggedError(error) });
15058
- } finally {
15059
- finalize();
15755
+ const loggedError = toLoggedError(error);
15756
+ try {
15757
+ span.log({ error: loggedError });
15758
+ } catch (loggingError) {
15759
+ debugLogger.error(
15760
+ "Error logging AI SDK streaming failure:",
15761
+ loggingError
15762
+ );
15763
+ }
15764
+ finalize({
15765
+ error: error instanceof Error ? error : new Error(String(loggedError))
15766
+ });
15060
15767
  }
15061
15768
  };
15062
15769
  const createAsyncIterableHooks = () => {
@@ -15073,11 +15780,16 @@ function patchAISDKStreamingResult(args) {
15073
15780
  onError: (error) => {
15074
15781
  if (!outputLogged) {
15075
15782
  outputLogged = true;
15076
- span.log({
15077
- error: error.message
15078
- });
15783
+ try {
15784
+ span.log({ error });
15785
+ } catch (loggingError) {
15786
+ debugLogger.error(
15787
+ "Error logging AI SDK stream failure:",
15788
+ loggingError
15789
+ );
15790
+ }
15079
15791
  }
15080
- finalize();
15792
+ finalize({ error });
15081
15793
  },
15082
15794
  onCancel: finalize
15083
15795
  };
@@ -15163,8 +15875,18 @@ function patchAISDKStreamingResult(args) {
15163
15875
  }
15164
15876
  controller.enqueue(value);
15165
15877
  } catch (error) {
15166
- span.log({ error: toLoggedError(error) });
15167
- finalize();
15878
+ const loggedError = toLoggedError(error);
15879
+ try {
15880
+ span.log({ error: loggedError });
15881
+ } catch (loggingError) {
15882
+ debugLogger.error(
15883
+ "Error logging AI SDK base stream failure:",
15884
+ loggingError
15885
+ );
15886
+ }
15887
+ finalize({
15888
+ error: error instanceof Error ? error : new Error(String(loggedError))
15889
+ });
15168
15890
  controller.error(error);
15169
15891
  }
15170
15892
  },
@@ -15953,7 +16675,8 @@ var claudeAgentSDKChannels = defineChannels(
15953
16675
  channelName: "query",
15954
16676
  kind: "sync-stream"
15955
16677
  })
15956
- }
16678
+ },
16679
+ { instrumentationName: INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK }
15957
16680
  );
15958
16681
 
15959
16682
  // src/instrumentation/plugins/claude-agent-sdk-instrumentation-constants.ts
@@ -16101,22 +16824,27 @@ function wrapLocalClaudeToolHandler(handler, getMetadata) {
16101
16824
  const spanName = metadata.serverName ? `tool: ${metadata.serverName}/${metadata.toolName}` : `tool: ${metadata.toolName}`;
16102
16825
  const runWithResolvedParent = async () => {
16103
16826
  const parent = toolUseId && localToolParentResolver ? await localToolParentResolver(toolUseId).catch(() => void 0) : void 0;
16104
- const span = startSpan({
16105
- event: {
16106
- input: handlerArgs[0],
16107
- metadata: {
16108
- "claude_agent_sdk.raw_tool_name": rawToolName,
16109
- "gen_ai.tool.name": metadata.toolName,
16110
- ...toolUseId && { "gen_ai.tool.call.id": toolUseId },
16111
- ...metadata.serverName && {
16112
- "mcp.server": metadata.serverName
16113
- }
16114
- }
16115
- },
16116
- name: spanName,
16117
- ...parent && { parent },
16118
- spanAttributes: { type: "tool" /* TOOL */ }
16119
- });
16827
+ const span = startSpan(
16828
+ withSpanInstrumentationName(
16829
+ {
16830
+ event: {
16831
+ input: handlerArgs[0],
16832
+ metadata: {
16833
+ "claude_agent_sdk.raw_tool_name": rawToolName,
16834
+ "gen_ai.tool.name": metadata.toolName,
16835
+ ...toolUseId && { "gen_ai.tool.call.id": toolUseId },
16836
+ ...metadata.serverName && {
16837
+ "mcp.server": metadata.serverName
16838
+ }
16839
+ }
16840
+ },
16841
+ name: spanName,
16842
+ ...parent && { parent },
16843
+ spanAttributes: { type: "tool" /* TOOL */ }
16844
+ },
16845
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
16846
+ )
16847
+ );
16120
16848
  const runHandler = () => Reflect.apply(handler, this, handlerArgs);
16121
16849
  const finalizeSuccess = (result) => {
16122
16850
  span.log({ output: result });
@@ -16441,14 +17169,19 @@ async function createLLMSpanForMessages(messages, promptMessages, conversationHi
16441
17169
  ).filter(
16442
17170
  (c) => c !== void 0
16443
17171
  );
16444
- const span = existingSpan ?? startSpan({
16445
- name: "anthropic.messages.create",
16446
- parent: parentSpan,
16447
- spanAttributes: {
16448
- type: "llm" /* LLM */
16449
- },
16450
- startTime
16451
- });
17172
+ const span = existingSpan ?? startSpan(
17173
+ withSpanInstrumentationName(
17174
+ {
17175
+ name: "anthropic.messages.create",
17176
+ parent: parentSpan,
17177
+ spanAttributes: {
17178
+ type: "llm" /* LLM */
17179
+ },
17180
+ startTime
17181
+ },
17182
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
17183
+ )
17184
+ );
16452
17185
  span.log({
16453
17186
  input,
16454
17187
  metadata: model ? { model } : void 0,
@@ -16551,25 +17284,30 @@ function createToolTracingHooks(resolveParentSpan, activeToolSpans, mcpServers,
16551
17284
  return {};
16552
17285
  }
16553
17286
  const parsed = parseToolName(input.tool_name);
16554
- const toolSpan = startSpan({
16555
- event: {
16556
- input: input.tool_input,
16557
- metadata: {
16558
- "claude_agent_sdk.cwd": input.cwd,
16559
- "claude_agent_sdk.raw_tool_name": parsed.rawToolName,
16560
- "claude_agent_sdk.session_id": input.session_id,
16561
- "gen_ai.tool.call.id": toolUseID,
16562
- "gen_ai.tool.name": parsed.toolName,
16563
- ...parsed.mcpServer && { "mcp.server": parsed.mcpServer },
16564
- ...getMcpServerMetadata(parsed.mcpServer, mcpServers)
16565
- }
16566
- },
16567
- name: parsed.displayName,
16568
- parent: await resolveParentSpan(toolUseID, {
16569
- agentId: input.agent_id
16570
- }),
16571
- spanAttributes: { type: "tool" /* TOOL */ }
16572
- });
17287
+ const toolSpan = startSpan(
17288
+ withSpanInstrumentationName(
17289
+ {
17290
+ event: {
17291
+ input: input.tool_input,
17292
+ metadata: {
17293
+ "claude_agent_sdk.cwd": input.cwd,
17294
+ "claude_agent_sdk.raw_tool_name": parsed.rawToolName,
17295
+ "claude_agent_sdk.session_id": input.session_id,
17296
+ "gen_ai.tool.call.id": toolUseID,
17297
+ "gen_ai.tool.name": parsed.toolName,
17298
+ ...parsed.mcpServer && { "mcp.server": parsed.mcpServer },
17299
+ ...getMcpServerMetadata(parsed.mcpServer, mcpServers)
17300
+ }
17301
+ },
17302
+ name: parsed.displayName,
17303
+ parent: await resolveParentSpan(toolUseID, {
17304
+ agentId: input.agent_id
17305
+ }),
17306
+ spanAttributes: { type: "tool" /* TOOL */ }
17307
+ },
17308
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
17309
+ )
17310
+ );
16573
17311
  activeToolSpans.set(toolUseID, toolSpan);
16574
17312
  return {};
16575
17313
  };
@@ -16935,14 +17673,19 @@ async function ensureSubAgentSpan(subAgentDetailsByToolUseId, rootSpan, activeTo
16935
17673
  const spanName = formatSubAgentSpanName(details);
16936
17674
  const parentToolSpan = activeToolSpans.get(parentToolUseId);
16937
17675
  const parentSpan = parentToolSpan ? await parentToolSpan.export() : await rootSpan.export();
16938
- const subAgentSpan = startSpan({
16939
- event: {
16940
- metadata: subAgentDetailsToMetadata(details)
16941
- },
16942
- name: spanName,
16943
- parent: parentSpan,
16944
- spanAttributes: { type: "task" /* TASK */ }
16945
- });
17676
+ const subAgentSpan = startSpan(
17677
+ withSpanInstrumentationName(
17678
+ {
17679
+ event: {
17680
+ metadata: subAgentDetailsToMetadata(details)
17681
+ },
17682
+ name: spanName,
17683
+ parent: parentSpan,
17684
+ spanAttributes: { type: "task" /* TASK */ }
17685
+ },
17686
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
17687
+ )
17688
+ );
16946
17689
  subAgentSpans.set(parentToolUseId, subAgentSpan);
16947
17690
  return subAgentSpan;
16948
17691
  }
@@ -16963,14 +17706,19 @@ async function ensureActiveLlmSpanForParentToolUse(rootSpan, activeLlmSpansByPar
16963
17706
  );
16964
17707
  llmParentSpan = await subAgentSpan.export();
16965
17708
  }
16966
- const llmSpan = startSpan({
16967
- name: "anthropic.messages.create",
16968
- parent: llmParentSpan,
16969
- spanAttributes: {
16970
- type: "llm" /* LLM */
16971
- },
16972
- startTime
16973
- });
17709
+ const llmSpan = startSpan(
17710
+ withSpanInstrumentationName(
17711
+ {
17712
+ name: "anthropic.messages.create",
17713
+ parent: llmParentSpan,
17714
+ spanAttributes: {
17715
+ type: "llm" /* LLM */
17716
+ },
17717
+ startTime
17718
+ },
17719
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
17720
+ )
17721
+ );
16974
17722
  activeLlmSpansByParentToolUse.set(parentKey, llmSpan);
16975
17723
  return llmSpan;
16976
17724
  }
@@ -17239,12 +17987,17 @@ var ClaudeAgentSDKPlugin = class extends BasePlugin {
17239
17987
  }
17240
17988
  })();
17241
17989
  }
17242
- const span = startSpan({
17243
- name: "Claude Agent",
17244
- spanAttributes: {
17245
- type: "task" /* TASK */
17246
- }
17247
- });
17990
+ const span = startSpan(
17991
+ withSpanInstrumentationName(
17992
+ {
17993
+ name: "Claude Agent",
17994
+ spanAttributes: {
17995
+ type: "task" /* TASK */
17996
+ }
17997
+ },
17998
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
17999
+ )
18000
+ );
17248
18001
  const startTime = getCurrentUnixTimestamp();
17249
18002
  try {
17250
18003
  span.log({
@@ -17409,24 +18162,28 @@ var ClaudeAgentSDKPlugin = class extends BasePlugin {
17409
18162
  };
17410
18163
 
17411
18164
  // src/instrumentation/plugins/cursor-sdk-channels.ts
17412
- var cursorSDKChannels = defineChannels("@cursor/sdk", {
17413
- create: channel({
17414
- channelName: "Agent.create",
17415
- kind: "async"
17416
- }),
17417
- resume: channel({
17418
- channelName: "Agent.resume",
17419
- kind: "async"
17420
- }),
17421
- prompt: channel({
17422
- channelName: "Agent.prompt",
17423
- kind: "async"
17424
- }),
17425
- send: channel({
17426
- channelName: "agent.send",
17427
- kind: "async"
17428
- })
17429
- });
18165
+ var cursorSDKChannels = defineChannels(
18166
+ "@cursor/sdk",
18167
+ {
18168
+ create: channel({
18169
+ channelName: "Agent.create",
18170
+ kind: "async"
18171
+ }),
18172
+ resume: channel({
18173
+ channelName: "Agent.resume",
18174
+ kind: "async"
18175
+ }),
18176
+ prompt: channel({
18177
+ channelName: "Agent.prompt",
18178
+ kind: "async"
18179
+ }),
18180
+ send: channel({
18181
+ channelName: "agent.send",
18182
+ kind: "async"
18183
+ })
18184
+ },
18185
+ { instrumentationName: INSTRUMENTATION_NAMES.CURSOR_SDK }
18186
+ );
17430
18187
 
17431
18188
  // src/instrumentation/plugins/cursor-sdk-plugin.ts
17432
18189
  var PATCHED_AGENT = /* @__PURE__ */ Symbol.for("braintrust.cursor-sdk.auto-patched-agent");
@@ -17478,10 +18235,15 @@ var CursorSDKPlugin = class extends BasePlugin {
17478
18235
  provider: "cursor",
17479
18236
  ...event.moduleVersion ? { "cursor_sdk.version": event.moduleVersion } : {}
17480
18237
  };
17481
- const span = startSpan({
17482
- name: "Cursor Agent",
17483
- spanAttributes: { type: "task" /* TASK */ }
17484
- });
18238
+ const span = startSpan(
18239
+ withSpanInstrumentationName(
18240
+ {
18241
+ name: "Cursor Agent",
18242
+ spanAttributes: { type: "task" /* TASK */ }
18243
+ },
18244
+ INSTRUMENTATION_NAMES.CURSOR_SDK
18245
+ )
18246
+ );
17485
18247
  const startTime = getCurrentUnixTimestamp();
17486
18248
  safeLog2(span, {
17487
18249
  input: sanitizeUserMessage(message),
@@ -17543,10 +18305,15 @@ var CursorSDKPlugin = class extends BasePlugin {
17543
18305
  provider: "cursor",
17544
18306
  ...event.moduleVersion ? { "cursor_sdk.version": event.moduleVersion } : {}
17545
18307
  };
17546
- const span = startSpan({
17547
- name: "Cursor Agent",
17548
- spanAttributes: { type: "task" /* TASK */ }
17549
- });
18308
+ const span = startSpan(
18309
+ withSpanInstrumentationName(
18310
+ {
18311
+ name: "Cursor Agent",
18312
+ spanAttributes: { type: "task" /* TASK */ }
18313
+ },
18314
+ INSTRUMENTATION_NAMES.CURSOR_SDK
18315
+ )
18316
+ );
17550
18317
  const startTime = getCurrentUnixTimestamp();
17551
18318
  safeLog2(span, {
17552
18319
  input: sanitizeUserMessage(message),
@@ -17993,29 +18760,39 @@ async function startToolSpan(state, args) {
17993
18760
  if (args.truncated?.result !== void 0) {
17994
18761
  metadata["cursor_sdk.tool.result_truncated"] = args.truncated.result;
17995
18762
  }
17996
- const span = startSpan({
17997
- event: {
17998
- input: args.args,
17999
- metadata
18000
- },
18001
- name: `tool: ${name}`,
18002
- parent: await state.span.export(),
18003
- spanAttributes: { type: "tool" /* TOOL */ }
18004
- });
18763
+ const span = startSpan(
18764
+ withSpanInstrumentationName(
18765
+ {
18766
+ event: {
18767
+ input: args.args,
18768
+ metadata
18769
+ },
18770
+ name: `tool: ${name}`,
18771
+ parent: await state.span.export(),
18772
+ spanAttributes: { type: "tool" /* TOOL */ }
18773
+ },
18774
+ INSTRUMENTATION_NAMES.CURSOR_SDK
18775
+ )
18776
+ );
18005
18777
  let subAgentSpan;
18006
18778
  if (isSubAgentToolName(name)) {
18007
- subAgentSpan = startSpan({
18008
- event: {
18009
- input: args.args,
18010
- metadata: {
18011
- "cursor_sdk.subagent.tool_call_id": args.callId,
18012
- "gen_ai.tool.name": name
18013
- }
18014
- },
18015
- name: formatSubAgentSpanName2(args.toolCall, args.args),
18016
- parent: await span.export(),
18017
- spanAttributes: { type: "task" /* TASK */ }
18018
- });
18779
+ subAgentSpan = startSpan(
18780
+ withSpanInstrumentationName(
18781
+ {
18782
+ event: {
18783
+ input: args.args,
18784
+ metadata: {
18785
+ "cursor_sdk.subagent.tool_call_id": args.callId,
18786
+ "gen_ai.tool.name": name
18787
+ }
18788
+ },
18789
+ name: formatSubAgentSpanName2(args.toolCall, args.args),
18790
+ parent: await span.export(),
18791
+ spanAttributes: { type: "task" /* TASK */ }
18792
+ },
18793
+ INSTRUMENTATION_NAMES.CURSOR_SDK
18794
+ )
18795
+ );
18019
18796
  }
18020
18797
  return { span, subAgentSpan };
18021
18798
  }
@@ -18274,24 +19051,28 @@ function cleanMetrics2(metrics) {
18274
19051
  }
18275
19052
 
18276
19053
  // src/instrumentation/plugins/openai-agents-channels.ts
18277
- var openAIAgentsCoreChannels = defineChannels("@openai/agents-core", {
18278
- onTraceStart: channel({
18279
- channelName: "tracing.processor.onTraceStart",
18280
- kind: "async"
18281
- }),
18282
- onTraceEnd: channel({
18283
- channelName: "tracing.processor.onTraceEnd",
18284
- kind: "async"
18285
- }),
18286
- onSpanStart: channel({
18287
- channelName: "tracing.processor.onSpanStart",
18288
- kind: "async"
18289
- }),
18290
- onSpanEnd: channel({
18291
- channelName: "tracing.processor.onSpanEnd",
18292
- kind: "async"
18293
- })
18294
- });
19054
+ var openAIAgentsCoreChannels = defineChannels(
19055
+ "@openai/agents-core",
19056
+ {
19057
+ onTraceStart: channel({
19058
+ channelName: "tracing.processor.onTraceStart",
19059
+ kind: "async"
19060
+ }),
19061
+ onTraceEnd: channel({
19062
+ channelName: "tracing.processor.onTraceEnd",
19063
+ kind: "async"
19064
+ }),
19065
+ onSpanStart: channel({
19066
+ channelName: "tracing.processor.onSpanStart",
19067
+ kind: "async"
19068
+ }),
19069
+ onSpanEnd: channel({
19070
+ channelName: "tracing.processor.onSpanEnd",
19071
+ kind: "async"
19072
+ })
19073
+ },
19074
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENAI_AGENTS }
19075
+ );
18295
19076
 
18296
19077
  // src/instrumentation/plugins/openai-agents-trace-processor.ts
18297
19078
  function isSpanData(spanData, type) {
@@ -18407,16 +19188,19 @@ var OpenAIAgentsTraceProcessor = class _OpenAIAgentsTraceProcessor {
18407
19188
  this.evictOldestTrace();
18408
19189
  }
18409
19190
  const current = currentSpan();
18410
- const span = current && current !== NOOP_SPAN ? current.startSpan({
18411
- name: trace.name,
18412
- type: "task" /* TASK */
18413
- }) : this.logger ? this.logger.startSpan({
18414
- name: trace.name,
18415
- type: "task" /* TASK */
18416
- }) : startSpan({
18417
- name: trace.name,
18418
- type: "task" /* TASK */
18419
- });
19191
+ const spanArgs = withSpanInstrumentationName(
19192
+ {
19193
+ name: trace.name,
19194
+ type: "task" /* TASK */
19195
+ },
19196
+ INSTRUMENTATION_NAMES.OPENAI_AGENTS
19197
+ );
19198
+ const span = current && current !== NOOP_SPAN ? current.startSpan(spanArgs) : this.logger ? this.logger.startSpan(spanArgs) : startSpan(
19199
+ withSpanInstrumentationName(
19200
+ spanArgs,
19201
+ INSTRUMENTATION_NAMES.OPENAI_AGENTS
19202
+ )
19203
+ );
18420
19204
  span.log({
18421
19205
  input: "Agent workflow started",
18422
19206
  metadata: {
@@ -18467,10 +19251,15 @@ var OpenAIAgentsTraceProcessor = class _OpenAIAgentsTraceProcessor {
18467
19251
  if (!parentSpan) {
18468
19252
  return Promise.resolve();
18469
19253
  }
18470
- const childSpan = parentSpan.startSpan({
18471
- name: spanNameFromAgents(span),
18472
- type: spanTypeFromAgents(span)
18473
- });
19254
+ const childSpan = parentSpan.startSpan(
19255
+ withSpanInstrumentationName(
19256
+ {
19257
+ name: spanNameFromAgents(span),
19258
+ type: spanTypeFromAgents(span)
19259
+ },
19260
+ INSTRUMENTATION_NAMES.OPENAI_AGENTS
19261
+ )
19262
+ );
18474
19263
  traceData.childSpans.set(span.spanId, childSpan);
18475
19264
  return Promise.resolve();
18476
19265
  }
@@ -18735,24 +19524,28 @@ var OpenAIAgentsPlugin = class extends BasePlugin {
18735
19524
  };
18736
19525
 
18737
19526
  // src/instrumentation/plugins/google-genai-channels.ts
18738
- var googleGenAIChannels = defineChannels("@google/genai", {
18739
- generateContent: channel({
18740
- channelName: "models.generateContent",
18741
- kind: "async"
18742
- }),
18743
- generateContentStream: channel({
18744
- channelName: "models.generateContentStream",
18745
- kind: "async"
18746
- }),
18747
- embedContent: channel({
18748
- channelName: "models.embedContent",
18749
- kind: "async"
18750
- }),
18751
- interactionsCreate: channel({
18752
- channelName: "interactions.create",
18753
- kind: "async"
18754
- })
18755
- });
19527
+ var googleGenAIChannels = defineChannels(
19528
+ "@google/genai",
19529
+ {
19530
+ generateContent: channel({
19531
+ channelName: "models.generateContent",
19532
+ kind: "async"
19533
+ }),
19534
+ generateContentStream: channel({
19535
+ channelName: "models.generateContentStream",
19536
+ kind: "async"
19537
+ }),
19538
+ embedContent: channel({
19539
+ channelName: "models.embedContent",
19540
+ kind: "async"
19541
+ }),
19542
+ interactionsCreate: channel({
19543
+ channelName: "interactions.create",
19544
+ kind: "async"
19545
+ })
19546
+ },
19547
+ { instrumentationName: INSTRUMENTATION_NAMES.GOOGLE_GENAI }
19548
+ );
18756
19549
 
18757
19550
  // src/instrumentation/plugins/google-genai-plugin.ts
18758
19551
  var GOOGLE_GENAI_INTERNAL_CONTEXT = {
@@ -18790,13 +19583,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
18790
19583
  const params = event.arguments[0];
18791
19584
  const input = serializeGenerateContentInput(params);
18792
19585
  const metadata = extractGenerateContentMetadata(params);
18793
- const span = startSpan({
18794
- name: "generate_content",
18795
- spanAttributes: {
18796
- type: "llm" /* LLM */
18797
- },
18798
- event: createWrapperParityEvent({ input, metadata })
18799
- });
19586
+ const span = startSpan(
19587
+ withSpanInstrumentationName(
19588
+ {
19589
+ name: "generate_content",
19590
+ spanAttributes: {
19591
+ type: "llm" /* LLM */
19592
+ },
19593
+ event: createWrapperParityEvent({ input, metadata })
19594
+ },
19595
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
19596
+ )
19597
+ );
18800
19598
  return {
18801
19599
  span,
18802
19600
  startTime: getCurrentUnixTimestamp()
@@ -18809,13 +19607,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
18809
19607
  const params = event.arguments[0];
18810
19608
  const input = serializeGenerateContentInput(params);
18811
19609
  const metadata = extractGenerateContentMetadata(params);
18812
- const span = startSpan({
18813
- name: "generate_content",
18814
- spanAttributes: {
18815
- type: "llm" /* LLM */
18816
- },
18817
- event: createWrapperParityEvent({ input, metadata })
18818
- });
19610
+ const span = startSpan(
19611
+ withSpanInstrumentationName(
19612
+ {
19613
+ name: "generate_content",
19614
+ spanAttributes: {
19615
+ type: "llm" /* LLM */
19616
+ },
19617
+ event: createWrapperParityEvent({ input, metadata })
19618
+ },
19619
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
19620
+ )
19621
+ );
18819
19622
  return {
18820
19623
  span,
18821
19624
  startTime: getCurrentUnixTimestamp()
@@ -18891,13 +19694,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
18891
19694
  const params = event.arguments[0];
18892
19695
  const input = serializeEmbedContentInput(params);
18893
19696
  const metadata = extractEmbedContentMetadata(params);
18894
- const span = startSpan({
18895
- name: "embed_content",
18896
- spanAttributes: {
18897
- type: "llm" /* LLM */
18898
- },
18899
- event: createWrapperParityEvent({ input, metadata })
18900
- });
19697
+ const span = startSpan(
19698
+ withSpanInstrumentationName(
19699
+ {
19700
+ name: "embed_content",
19701
+ spanAttributes: {
19702
+ type: "llm" /* LLM */
19703
+ },
19704
+ event: createWrapperParityEvent({ input, metadata })
19705
+ },
19706
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
19707
+ )
19708
+ );
18901
19709
  return {
18902
19710
  span,
18903
19711
  startTime: getCurrentUnixTimestamp()
@@ -18910,13 +19718,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
18910
19718
  const params = event.arguments[0];
18911
19719
  const input = serializeEmbedContentInput(params);
18912
19720
  const metadata = extractEmbedContentMetadata(params);
18913
- const span = startSpan({
18914
- name: "embed_content",
18915
- spanAttributes: {
18916
- type: "llm" /* LLM */
18917
- },
18918
- event: createWrapperParityEvent({ input, metadata })
18919
- });
19721
+ const span = startSpan(
19722
+ withSpanInstrumentationName(
19723
+ {
19724
+ name: "embed_content",
19725
+ spanAttributes: {
19726
+ type: "llm" /* LLM */
19727
+ },
19728
+ event: createWrapperParityEvent({ input, metadata })
19729
+ },
19730
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
19731
+ )
19732
+ );
18920
19733
  return {
18921
19734
  span,
18922
19735
  startTime: getCurrentUnixTimestamp()
@@ -19027,16 +19840,21 @@ function patchGoogleGenAIStreamingResult(args) {
19027
19840
  const requestStartTime = startTime ?? getCurrentUnixTimestamp();
19028
19841
  const ensureSpan = () => {
19029
19842
  if (!span) {
19030
- span = startSpan({
19031
- name: "generate_content_stream",
19032
- spanAttributes: {
19033
- type: "llm" /* LLM */
19034
- },
19035
- event: {
19036
- input,
19037
- metadata
19038
- }
19039
- });
19843
+ span = startSpan(
19844
+ withSpanInstrumentationName(
19845
+ {
19846
+ name: "generate_content_stream",
19847
+ spanAttributes: {
19848
+ type: "llm" /* LLM */
19849
+ },
19850
+ event: {
19851
+ input,
19852
+ metadata
19853
+ }
19854
+ },
19855
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
19856
+ )
19857
+ );
19040
19858
  }
19041
19859
  return span;
19042
19860
  };
@@ -19804,28 +20622,32 @@ function tryToDict(obj) {
19804
20622
  }
19805
20623
 
19806
20624
  // src/instrumentation/plugins/huggingface-channels.ts
19807
- var huggingFaceChannels = defineChannels("@huggingface/inference", {
19808
- chatCompletion: channel({
19809
- channelName: "chatCompletion",
19810
- kind: "async"
19811
- }),
19812
- chatCompletionStream: channel({
19813
- channelName: "chatCompletionStream",
19814
- kind: "sync-stream"
19815
- }),
19816
- textGeneration: channel({
19817
- channelName: "textGeneration",
19818
- kind: "async"
19819
- }),
19820
- textGenerationStream: channel({
19821
- channelName: "textGenerationStream",
19822
- kind: "sync-stream"
19823
- }),
19824
- featureExtraction: channel({
19825
- channelName: "featureExtraction",
19826
- kind: "async"
19827
- })
19828
- });
20625
+ var huggingFaceChannels = defineChannels(
20626
+ "@huggingface/inference",
20627
+ {
20628
+ chatCompletion: channel({
20629
+ channelName: "chatCompletion",
20630
+ kind: "async"
20631
+ }),
20632
+ chatCompletionStream: channel({
20633
+ channelName: "chatCompletionStream",
20634
+ kind: "sync-stream"
20635
+ }),
20636
+ textGeneration: channel({
20637
+ channelName: "textGeneration",
20638
+ kind: "async"
20639
+ }),
20640
+ textGenerationStream: channel({
20641
+ channelName: "textGenerationStream",
20642
+ kind: "sync-stream"
20643
+ }),
20644
+ featureExtraction: channel({
20645
+ channelName: "featureExtraction",
20646
+ kind: "async"
20647
+ })
20648
+ },
20649
+ { instrumentationName: INSTRUMENTATION_NAMES.HUGGINGFACE }
20650
+ );
19829
20651
 
19830
20652
  // src/instrumentation/plugins/huggingface-plugin.ts
19831
20653
  var REQUEST_METADATA_ALLOWLIST = /* @__PURE__ */ new Set([
@@ -20252,20 +21074,24 @@ function extractTextGenerationStreamMetadata(chunks) {
20252
21074
  }
20253
21075
 
20254
21076
  // src/instrumentation/plugins/openrouter-agent-channels.ts
20255
- var openRouterAgentChannels = defineChannels("@openrouter/agent", {
20256
- callModel: channel({
20257
- channelName: "callModel",
20258
- kind: "sync-stream"
20259
- }),
20260
- callModelTurn: channel({
20261
- channelName: "callModel.turn",
20262
- kind: "async"
20263
- }),
20264
- toolExecute: channel({
20265
- channelName: "tool.execute",
20266
- kind: "async"
20267
- })
20268
- });
21077
+ var openRouterAgentChannels = defineChannels(
21078
+ "@openrouter/agent",
21079
+ {
21080
+ callModel: channel({
21081
+ channelName: "callModel",
21082
+ kind: "sync-stream"
21083
+ }),
21084
+ callModelTurn: channel({
21085
+ channelName: "callModel.turn",
21086
+ kind: "async"
21087
+ }),
21088
+ toolExecute: channel({
21089
+ channelName: "tool.execute",
21090
+ kind: "async"
21091
+ })
21092
+ },
21093
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENROUTER_AGENT }
21094
+ );
20269
21095
 
20270
21096
  // src/instrumentation/plugins/openrouter-agent-plugin.ts
20271
21097
  var OpenRouterAgentPlugin = class extends BasePlugin {
@@ -21035,38 +21861,40 @@ function normalizeError(error) {
21035
21861
  }
21036
21862
 
21037
21863
  // src/instrumentation/plugins/openrouter-channels.ts
21038
- var openRouterChannels = defineChannels("@openrouter/sdk", {
21039
- chatSend: channel({
21040
- channelName: "chat.send",
21041
- kind: "async"
21042
- }),
21043
- embeddingsGenerate: channel({
21044
- channelName: "embeddings.generate",
21045
- kind: "async"
21046
- }),
21047
- rerankRerank: channel(
21048
- {
21864
+ var openRouterChannels = defineChannels(
21865
+ "@openrouter/sdk",
21866
+ {
21867
+ chatSend: channel({
21868
+ channelName: "chat.send",
21869
+ kind: "async"
21870
+ }),
21871
+ embeddingsGenerate: channel({
21872
+ channelName: "embeddings.generate",
21873
+ kind: "async"
21874
+ }),
21875
+ rerankRerank: channel({
21049
21876
  channelName: "rerank.rerank",
21050
21877
  kind: "async"
21051
- }
21052
- ),
21053
- betaResponsesSend: channel({
21054
- channelName: "beta.responses.send",
21055
- kind: "async"
21056
- }),
21057
- callModel: channel({
21058
- channelName: "callModel",
21059
- kind: "sync-stream"
21060
- }),
21061
- callModelTurn: channel({
21062
- channelName: "callModel.turn",
21063
- kind: "async"
21064
- }),
21065
- toolExecute: channel({
21066
- channelName: "tool.execute",
21067
- kind: "async"
21068
- })
21069
- });
21878
+ }),
21879
+ betaResponsesSend: channel({
21880
+ channelName: "beta.responses.send",
21881
+ kind: "async"
21882
+ }),
21883
+ callModel: channel({
21884
+ channelName: "callModel",
21885
+ kind: "sync-stream"
21886
+ }),
21887
+ callModelTurn: channel({
21888
+ channelName: "callModel.turn",
21889
+ kind: "async"
21890
+ }),
21891
+ toolExecute: channel({
21892
+ channelName: "tool.execute",
21893
+ kind: "async"
21894
+ })
21895
+ },
21896
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENROUTER }
21897
+ );
21070
21898
 
21071
21899
  // src/instrumentation/plugins/openrouter-plugin.ts
21072
21900
  var OpenRouterPlugin = class extends BasePlugin {
@@ -22106,52 +22934,56 @@ function normalizeError2(error) {
22106
22934
  }
22107
22935
 
22108
22936
  // src/instrumentation/plugins/mistral-channels.ts
22109
- var mistralChannels = defineChannels("@mistralai/mistralai", {
22110
- chatComplete: channel({
22111
- channelName: "chat.complete",
22112
- kind: "async"
22113
- }),
22114
- chatStream: channel({
22115
- channelName: "chat.stream",
22116
- kind: "async"
22117
- }),
22118
- embeddingsCreate: channel({
22119
- channelName: "embeddings.create",
22120
- kind: "async"
22121
- }),
22122
- classifiersModerate: channel({
22123
- channelName: "classifiers.moderate",
22124
- kind: "async"
22125
- }),
22126
- classifiersModerateChat: channel({
22127
- channelName: "classifiers.moderateChat",
22128
- kind: "async"
22129
- }),
22130
- classifiersClassify: channel({
22131
- channelName: "classifiers.classify",
22132
- kind: "async"
22133
- }),
22134
- classifiersClassifyChat: channel({
22135
- channelName: "classifiers.classifyChat",
22136
- kind: "async"
22137
- }),
22138
- fimComplete: channel({
22139
- channelName: "fim.complete",
22140
- kind: "async"
22141
- }),
22142
- fimStream: channel({
22143
- channelName: "fim.stream",
22144
- kind: "async"
22145
- }),
22146
- agentsComplete: channel({
22147
- channelName: "agents.complete",
22148
- kind: "async"
22149
- }),
22150
- agentsStream: channel({
22151
- channelName: "agents.stream",
22152
- kind: "async"
22153
- })
22154
- });
22937
+ var mistralChannels = defineChannels(
22938
+ "@mistralai/mistralai",
22939
+ {
22940
+ chatComplete: channel({
22941
+ channelName: "chat.complete",
22942
+ kind: "async"
22943
+ }),
22944
+ chatStream: channel({
22945
+ channelName: "chat.stream",
22946
+ kind: "async"
22947
+ }),
22948
+ embeddingsCreate: channel({
22949
+ channelName: "embeddings.create",
22950
+ kind: "async"
22951
+ }),
22952
+ classifiersModerate: channel({
22953
+ channelName: "classifiers.moderate",
22954
+ kind: "async"
22955
+ }),
22956
+ classifiersModerateChat: channel({
22957
+ channelName: "classifiers.moderateChat",
22958
+ kind: "async"
22959
+ }),
22960
+ classifiersClassify: channel({
22961
+ channelName: "classifiers.classify",
22962
+ kind: "async"
22963
+ }),
22964
+ classifiersClassifyChat: channel({
22965
+ channelName: "classifiers.classifyChat",
22966
+ kind: "async"
22967
+ }),
22968
+ fimComplete: channel({
22969
+ channelName: "fim.complete",
22970
+ kind: "async"
22971
+ }),
22972
+ fimStream: channel({
22973
+ channelName: "fim.stream",
22974
+ kind: "async"
22975
+ }),
22976
+ agentsComplete: channel({
22977
+ channelName: "agents.complete",
22978
+ kind: "async"
22979
+ }),
22980
+ agentsStream: channel({
22981
+ channelName: "agents.stream",
22982
+ kind: "async"
22983
+ })
22984
+ },
22985
+ { instrumentationName: INSTRUMENTATION_NAMES.MISTRAL }
22986
+ );
22155
22987
 
22156
22988
  // src/instrumentation/plugins/mistral-plugin.ts
22157
22989
  var MistralPlugin = class extends BasePlugin {
@@ -22771,20 +23603,24 @@ function aggregateMistralStreamChunks(chunks) {
22771
23603
  }
22772
23604
 
22773
23605
  // src/instrumentation/plugins/google-adk-channels.ts
22774
- var googleADKChannels = defineChannels("@google/adk", {
22775
- runnerRunAsync: channel({
22776
- channelName: "runner.runAsync",
22777
- kind: "sync-stream"
22778
- }),
22779
- agentRunAsync: channel({
22780
- channelName: "agent.runAsync",
22781
- kind: "sync-stream"
22782
- }),
22783
- toolRunAsync: channel({
22784
- channelName: "tool.runAsync",
22785
- kind: "async"
22786
- })
22787
- });
23606
+ var googleADKChannels = defineChannels(
23607
+ "@google/adk",
23608
+ {
23609
+ runnerRunAsync: channel({
23610
+ channelName: "runner.runAsync",
23611
+ kind: "sync-stream"
23612
+ }),
23613
+ agentRunAsync: channel({
23614
+ channelName: "agent.runAsync",
23615
+ kind: "sync-stream"
23616
+ }),
23617
+ toolRunAsync: channel({
23618
+ channelName: "tool.runAsync",
23619
+ kind: "async"
23620
+ })
23621
+ },
23622
+ { instrumentationName: INSTRUMENTATION_NAMES.GOOGLE_ADK }
23623
+ );
22788
23624
 
22789
23625
  // src/instrumentation/plugins/google-adk-plugin.ts
22790
23626
  var GoogleADKPlugin = class extends BasePlugin {
@@ -22809,12 +23645,17 @@ var GoogleADKPlugin = class extends BasePlugin {
22809
23645
  const createState = (event) => {
22810
23646
  const params = event.arguments[0] ?? {};
22811
23647
  const contextKey = extractRunnerContextKey(params);
22812
- const span = startSpan({
22813
- name: "Google ADK Runner",
22814
- spanAttributes: {
22815
- type: "task" /* TASK */
22816
- }
22817
- });
23648
+ const span = startSpan(
23649
+ withSpanInstrumentationName(
23650
+ {
23651
+ name: "Google ADK Runner",
23652
+ spanAttributes: {
23653
+ type: "task" /* TASK */
23654
+ }
23655
+ },
23656
+ INSTRUMENTATION_NAMES.GOOGLE_ADK
23657
+ )
23658
+ );
22818
23659
  const startTime = getCurrentUnixTimestamp();
22819
23660
  try {
22820
23661
  const metadata = extractRunnerMetadata(params);
@@ -22900,18 +23741,23 @@ var GoogleADKPlugin = class extends BasePlugin {
22900
23741
  this.activeRunnerSpans
22901
23742
  );
22902
23743
  const contextKey = extractInvocationContextKey(parentContext);
22903
- const span = startSpan({
22904
- name: agentName ? `Agent: ${agentName}` : "Google ADK Agent",
22905
- spanAttributes: {
22906
- type: "task" /* TASK */
22907
- },
22908
- ...runnerParentSpan ? {
22909
- parentSpanIds: {
22910
- spanId: runnerParentSpan.spanId,
22911
- rootSpanId: runnerParentSpan.rootSpanId
22912
- }
22913
- } : {}
22914
- });
23744
+ const span = startSpan(
23745
+ withSpanInstrumentationName(
23746
+ {
23747
+ name: agentName ? `Agent: ${agentName}` : "Google ADK Agent",
23748
+ spanAttributes: {
23749
+ type: "task" /* TASK */
23750
+ },
23751
+ ...runnerParentSpan ? {
23752
+ parentSpanIds: {
23753
+ spanId: runnerParentSpan.spanId,
23754
+ rootSpanId: runnerParentSpan.rootSpanId
23755
+ }
23756
+ } : {}
23757
+ },
23758
+ INSTRUMENTATION_NAMES.GOOGLE_ADK
23759
+ )
23760
+ );
22915
23761
  const startTime = getCurrentUnixTimestamp();
22916
23762
  try {
22917
23763
  const metadata = {
@@ -23004,22 +23850,27 @@ var GoogleADKPlugin = class extends BasePlugin {
23004
23850
  this.activeAgentSpans,
23005
23851
  this.activeRunnerSpans
23006
23852
  );
23007
- const createSpan = () => startSpan({
23008
- name: toolName ? `tool: ${toolName}` : "Google ADK Tool",
23009
- spanAttributes: {
23010
- type: "tool" /* TOOL */
23011
- },
23012
- event: {
23013
- input: req.args,
23014
- metadata: {
23015
- provider: "google-adk",
23016
- ...toolName && { "google_adk.tool_name": toolName },
23017
- ...extractToolCallId(req) && {
23018
- "google_adk.tool_call_id": extractToolCallId(req)
23853
+ const createSpan = () => startSpan(
23854
+ withSpanInstrumentationName(
23855
+ {
23856
+ name: toolName ? `tool: ${toolName}` : "Google ADK Tool",
23857
+ spanAttributes: {
23858
+ type: "tool" /* TOOL */
23859
+ },
23860
+ event: {
23861
+ input: req.args,
23862
+ metadata: {
23863
+ provider: "google-adk",
23864
+ ...toolName && { "google_adk.tool_name": toolName },
23865
+ ...extractToolCallId(req) && {
23866
+ "google_adk.tool_call_id": extractToolCallId(req)
23867
+ }
23868
+ }
23019
23869
  }
23020
- }
23021
- }
23022
- });
23870
+ },
23871
+ INSTRUMENTATION_NAMES.GOOGLE_ADK
23872
+ )
23873
+ );
23023
23874
  const span = parentSpan ? withCurrent(parentSpan, () => createSpan()) : createSpan();
23024
23875
  const startTime = getCurrentUnixTimestamp();
23025
23876
  states.set(event, { span, startTime });
@@ -23418,24 +24269,28 @@ function cleanMetrics4(metrics) {
23418
24269
  }
23419
24270
 
23420
24271
  // src/instrumentation/plugins/cohere-channels.ts
23421
- var cohereChannels = defineChannels("cohere-ai", {
23422
- chat: channel({
23423
- channelName: "chat",
23424
- kind: "async"
23425
- }),
23426
- chatStream: channel({
23427
- channelName: "chatStream",
23428
- kind: "async"
23429
- }),
23430
- embed: channel({
23431
- channelName: "embed",
23432
- kind: "async"
23433
- }),
23434
- rerank: channel({
23435
- channelName: "rerank",
23436
- kind: "async"
23437
- })
23438
- });
24272
+ var cohereChannels = defineChannels(
24273
+ "cohere-ai",
24274
+ {
24275
+ chat: channel({
24276
+ channelName: "chat",
24277
+ kind: "async"
24278
+ }),
24279
+ chatStream: channel({
24280
+ channelName: "chatStream",
24281
+ kind: "async"
24282
+ }),
24283
+ embed: channel({
24284
+ channelName: "embed",
24285
+ kind: "async"
24286
+ }),
24287
+ rerank: channel({
24288
+ channelName: "rerank",
24289
+ kind: "async"
24290
+ })
24291
+ },
24292
+ { instrumentationName: INSTRUMENTATION_NAMES.COHERE }
24293
+ );
23439
24294
 
23440
24295
  // src/instrumentation/plugins/cohere-plugin.ts
23441
24296
  var CoherePlugin = class extends BasePlugin {
@@ -24104,18 +24959,20 @@ function aggregateCohereChatStreamChunks(chunks) {
24104
24959
  }
24105
24960
 
24106
24961
  // src/instrumentation/plugins/groq-channels.ts
24107
- var groqChannels = defineChannels("groq-sdk", {
24108
- chatCompletionsCreate: channel({
24109
- channelName: "chat.completions.create",
24110
- kind: "async"
24111
- }),
24112
- embeddingsCreate: channel(
24113
- {
24962
+ var groqChannels = defineChannels(
24963
+ "groq-sdk",
24964
+ {
24965
+ chatCompletionsCreate: channel({
24966
+ channelName: "chat.completions.create",
24967
+ kind: "async"
24968
+ }),
24969
+ embeddingsCreate: channel({
24114
24970
  channelName: "embeddings.create",
24115
24971
  kind: "async"
24116
- }
24117
- )
24118
- });
24972
+ })
24973
+ },
24974
+ { instrumentationName: INSTRUMENTATION_NAMES.GROQ }
24975
+ );
24119
24976
 
24120
24977
  // src/instrumentation/plugins/groq-plugin.ts
24121
24978
  var GroqPlugin = class extends BasePlugin {
@@ -24218,15 +25075,27 @@ var clientSendChannel = channel({
24218
25075
  channelName: "client.send",
24219
25076
  kind: "async"
24220
25077
  });
24221
- var bedrockRuntimeChannels = defineChannels("aws-bedrock-runtime", {
24222
- clientSend: clientSendChannel
24223
- });
24224
- var smithyCoreChannels = defineChannels("@smithy/core", {
24225
- clientSend: clientSendChannel
24226
- });
24227
- var smithyClientChannels = defineChannels("@smithy/smithy-client", {
24228
- clientSend: clientSendChannel
24229
- });
25078
+ var bedrockRuntimeChannels = defineChannels(
25079
+ "aws-bedrock-runtime",
25080
+ {
25081
+ clientSend: clientSendChannel
25082
+ },
25083
+ { instrumentationName: INSTRUMENTATION_NAMES.BEDROCK_RUNTIME }
25084
+ );
25085
+ var smithyCoreChannels = defineChannels(
25086
+ "@smithy/core",
25087
+ {
25088
+ clientSend: clientSendChannel
25089
+ },
25090
+ { instrumentationName: INSTRUMENTATION_NAMES.BEDROCK_RUNTIME }
25091
+ );
25092
+ var smithyClientChannels = defineChannels(
25093
+ "@smithy/smithy-client",
25094
+ {
25095
+ clientSend: clientSendChannel
25096
+ },
25097
+ { instrumentationName: INSTRUMENTATION_NAMES.BEDROCK_RUNTIME }
25098
+ );
24230
25099
 
24231
25100
  // src/instrumentation/plugins/bedrock-runtime-common.ts
24232
25101
  var BEDROCK_RUNTIME_COMMAND_OPERATIONS = {
@@ -24860,38 +25729,46 @@ function extractTextFromJsonLike(value) {
24860
25729
  }
24861
25730
 
24862
25731
  // src/instrumentation/plugins/genkit-channels.ts
24863
- var genkitChannels = defineChannels("@genkit-ai/ai", {
24864
- generate: channel({
24865
- channelName: "generate",
24866
- kind: "async"
24867
- }),
24868
- generateStream: channel({
24869
- channelName: "generateStream",
24870
- kind: "sync-stream"
24871
- }),
24872
- embed: channel({
24873
- channelName: "embed",
24874
- kind: "async"
24875
- }),
24876
- embedMany: channel({
24877
- channelName: "embedMany",
24878
- kind: "async"
24879
- }),
24880
- actionRun: channel({
24881
- channelName: "action.run",
24882
- kind: "async"
24883
- }),
24884
- actionStream: channel({
24885
- channelName: "action.stream",
24886
- kind: "sync-stream"
24887
- })
24888
- });
24889
- var genkitCoreChannels = defineChannels("@genkit-ai/core", {
24890
- actionSpan: channel({
24891
- channelName: "action.span",
24892
- kind: "async"
24893
- })
24894
- });
25732
+ var genkitChannels = defineChannels(
25733
+ "@genkit-ai/ai",
25734
+ {
25735
+ generate: channel({
25736
+ channelName: "generate",
25737
+ kind: "async"
25738
+ }),
25739
+ generateStream: channel({
25740
+ channelName: "generateStream",
25741
+ kind: "sync-stream"
25742
+ }),
25743
+ embed: channel({
25744
+ channelName: "embed",
25745
+ kind: "async"
25746
+ }),
25747
+ embedMany: channel({
25748
+ channelName: "embedMany",
25749
+ kind: "async"
25750
+ }),
25751
+ actionRun: channel({
25752
+ channelName: "action.run",
25753
+ kind: "async"
25754
+ }),
25755
+ actionStream: channel({
25756
+ channelName: "action.stream",
25757
+ kind: "sync-stream"
25758
+ })
25759
+ },
25760
+ { instrumentationName: INSTRUMENTATION_NAMES.GENKIT }
25761
+ );
25762
+ var genkitCoreChannels = defineChannels(
25763
+ "@genkit-ai/core",
25764
+ {
25765
+ actionSpan: channel({
25766
+ channelName: "action.span",
25767
+ kind: "async"
25768
+ })
25769
+ },
25770
+ { instrumentationName: INSTRUMENTATION_NAMES.GENKIT }
25771
+ );
24895
25772
 
24896
25773
  // src/instrumentation/plugins/genkit-plugin.ts
24897
25774
  var GenkitPlugin = class extends BasePlugin {
@@ -25076,12 +25953,17 @@ function startActionSpanState(args) {
25076
25953
  if (!shouldTraceAction(args.metadata, args.runStepName)) {
25077
25954
  return void 0;
25078
25955
  }
25079
- const span = startSpan({
25080
- name: actionSpanName(args.metadata, args.runStepName),
25081
- spanAttributes: {
25082
- type: actionSpanType(args.metadata)
25083
- }
25084
- });
25956
+ const span = startSpan(
25957
+ withSpanInstrumentationName(
25958
+ {
25959
+ name: actionSpanName(args.metadata, args.runStepName),
25960
+ spanAttributes: {
25961
+ type: actionSpanType(args.metadata)
25962
+ }
25963
+ },
25964
+ INSTRUMENTATION_NAMES.GENKIT
25965
+ )
25966
+ );
25085
25967
  const startTime = getCurrentUnixTimestamp();
25086
25968
  span.log({
25087
25969
  input: args.input,
@@ -25442,20 +26324,24 @@ function stringValue(value) {
25442
26324
  }
25443
26325
 
25444
26326
  // src/instrumentation/plugins/github-copilot-channels.ts
25445
- var gitHubCopilotChannels = defineChannels("@github/copilot-sdk", {
25446
- createSession: channel({
25447
- channelName: "client.createSession",
25448
- kind: "async"
25449
- }),
25450
- resumeSession: channel({
25451
- channelName: "client.resumeSession",
25452
- kind: "async"
25453
- }),
25454
- sendAndWait: channel({
25455
- channelName: "session.sendAndWait",
25456
- kind: "async"
25457
- })
25458
- });
26327
+ var gitHubCopilotChannels = defineChannels(
26328
+ "@github/copilot-sdk",
26329
+ {
26330
+ createSession: channel({
26331
+ channelName: "client.createSession",
26332
+ kind: "async"
26333
+ }),
26334
+ resumeSession: channel({
26335
+ channelName: "client.resumeSession",
26336
+ kind: "async"
26337
+ }),
26338
+ sendAndWait: channel({
26339
+ channelName: "session.sendAndWait",
26340
+ kind: "async"
26341
+ })
26342
+ },
26343
+ { instrumentationName: INSTRUMENTATION_NAMES.GITHUB_COPILOT }
26344
+ );
25459
26345
 
25460
26346
  // src/instrumentation/plugins/github-copilot-plugin.ts
25461
26347
  var ROOT_AGENT_KEY = "__root__";
@@ -25546,11 +26432,16 @@ async function handleTurnStart(state, agentId) {
25546
26432
  return;
25547
26433
  }
25548
26434
  const parentId = await getParentIdForAgent(state, agentId);
25549
- const span = startSpan({
25550
- name: "Copilot Turn",
25551
- parent: parentId,
25552
- spanAttributes: { type: "task" /* TASK */ }
25553
- });
26435
+ const span = startSpan(
26436
+ withSpanInstrumentationName(
26437
+ {
26438
+ name: "Copilot Turn",
26439
+ parent: parentId,
26440
+ spanAttributes: { type: "task" /* TASK */ }
26441
+ },
26442
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
26443
+ )
26444
+ );
25554
26445
  const pendingUserMessage = state.pendingUserMessages.get(key);
25555
26446
  if (pendingUserMessage) {
25556
26447
  span.log({ input: pendingUserMessage });
@@ -25581,11 +26472,16 @@ async function handleUsage(state, agentId, usage) {
25581
26472
  const parentId = turn ? await turn.id : await state.session.id;
25582
26473
  const content = state.currentMessageContent.get(key);
25583
26474
  const { metrics, metadata } = extractMetricsFromUsage(usage);
25584
- const llmSpan = startSpan({
25585
- name: "github.copilot.llm",
25586
- parent: parentId,
25587
- spanAttributes: { type: "llm" /* LLM */ }
25588
- });
26475
+ const llmSpan = startSpan(
26476
+ withSpanInstrumentationName(
26477
+ {
26478
+ name: "github.copilot.llm",
26479
+ parent: parentId,
26480
+ spanAttributes: { type: "llm" /* LLM */ }
26481
+ },
26482
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
26483
+ )
26484
+ );
25589
26485
  llmSpan.log({
25590
26486
  output: content ?? void 0,
25591
26487
  metadata,
@@ -25611,11 +26507,16 @@ async function handleToolStart(state, agentId, toolCallId, toolName, args, mcpSe
25611
26507
  }
25612
26508
  const parentId = await getToolParentId(state, agentId);
25613
26509
  const displayName = mcpServerName ? `tool: ${mcpServerName}/${toolName}` : `tool: ${toolName}`;
25614
- const span = startSpan({
25615
- name: displayName,
25616
- parent: parentId,
25617
- spanAttributes: { type: "tool" /* TOOL */ }
25618
- });
26510
+ const span = startSpan(
26511
+ withSpanInstrumentationName(
26512
+ {
26513
+ name: displayName,
26514
+ parent: parentId,
26515
+ spanAttributes: { type: "tool" /* TOOL */ }
26516
+ },
26517
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
26518
+ )
26519
+ );
25619
26520
  const metadata = {
25620
26521
  "gen_ai.tool.name": toolName,
25621
26522
  "gen_ai.tool.call.id": toolCallId
@@ -25651,11 +26552,16 @@ async function handleSubagentStarted(state, agentId, toolCallId, agentDisplayNam
25651
26552
  }
25652
26553
  const tool = state.activeTools.get(toolCallId);
25653
26554
  const parentId = tool ? await tool.id : await state.session.id;
25654
- const span = startSpan({
25655
- name: `Agent: ${agentDisplayName}`,
25656
- parent: parentId,
25657
- spanAttributes: { type: "task" /* TASK */ }
25658
- });
26555
+ const span = startSpan(
26556
+ withSpanInstrumentationName(
26557
+ {
26558
+ name: `Agent: ${agentDisplayName}`,
26559
+ parent: parentId,
26560
+ spanAttributes: { type: "task" /* TASK */ }
26561
+ },
26562
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
26563
+ )
26564
+ );
25659
26565
  span.log({
25660
26566
  metadata: {
25661
26567
  "github_copilot.agent_name": agentDisplayName,
@@ -25881,10 +26787,15 @@ function makeSessionHandlers(sessionStates, configArgIndex, includeProviderMetad
25881
26787
  if (!config || typeof config !== "object") {
25882
26788
  return;
25883
26789
  }
25884
- const sessionSpan = startSpan({
25885
- name: "Copilot Session",
25886
- spanAttributes: { type: "task" /* TASK */ }
25887
- });
26790
+ const sessionSpan = startSpan(
26791
+ withSpanInstrumentationName(
26792
+ {
26793
+ name: "Copilot Session",
26794
+ spanAttributes: { type: "task" /* TASK */ }
26795
+ },
26796
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
26797
+ )
26798
+ );
25888
26799
  const metadata = {};
25889
26800
  if (config.model) {
25890
26801
  metadata["github_copilot.model"] = config.model;
@@ -25972,12 +26883,16 @@ var GitHubCopilotPlugin = class extends BasePlugin {
25972
26883
  };
25973
26884
 
25974
26885
  // src/instrumentation/plugins/flue-channels.ts
25975
- var flueChannels = defineChannels("@flue/runtime", {
25976
- createContext: channel({
25977
- channelName: "createFlueContext",
25978
- kind: "sync-stream"
25979
- })
25980
- });
26886
+ var flueChannels = defineChannels(
26887
+ "@flue/runtime",
26888
+ {
26889
+ createContext: channel({
26890
+ channelName: "createFlueContext",
26891
+ kind: "sync-stream"
26892
+ })
26893
+ },
26894
+ { instrumentationName: INSTRUMENTATION_NAMES.FLUE }
26895
+ );
25981
26896
 
25982
26897
  // src/instrumentation/plugins/flue-plugin.ts
25983
26898
  var FLUE_AUTO_STATE = /* @__PURE__ */ Symbol.for("braintrust.flue.auto-state");
@@ -26320,15 +27235,20 @@ var FlueObserveBridge = class {
26320
27235
  safeLog3(existing.span, { input, metadata });
26321
27236
  return;
26322
27237
  }
26323
- const span = startSpan({
26324
- name: `workflow:${workflowName}`,
26325
- spanAttributes: { type: "task" /* TASK */ },
26326
- startTime: eventTime(event.startedAt ?? event.timestamp),
26327
- event: {
26328
- input,
26329
- metadata
26330
- }
26331
- });
27238
+ const span = startSpan(
27239
+ withSpanInstrumentationName(
27240
+ {
27241
+ name: `workflow:${workflowName}`,
27242
+ spanAttributes: { type: "task" /* TASK */ },
27243
+ startTime: eventTime(event.startedAt ?? event.timestamp),
27244
+ event: {
27245
+ input,
27246
+ metadata
27247
+ }
27248
+ },
27249
+ INSTRUMENTATION_NAMES.FLUE
27250
+ )
27251
+ );
26332
27252
  this.runsById.set(event.runId, { metadata, span });
26333
27253
  }
26334
27254
  handleRunResume(event, ctx) {
@@ -26348,12 +27268,17 @@ var FlueObserveBridge = class {
26348
27268
  safeLog3(existing.span, { metadata });
26349
27269
  return;
26350
27270
  }
26351
- const span = startSpan({
26352
- name: `workflow:${workflowName}`,
26353
- spanAttributes: { type: "task" /* TASK */ },
26354
- startTime: eventTime(event.startedAt ?? event.timestamp),
26355
- event: { metadata }
26356
- });
27271
+ const span = startSpan(
27272
+ withSpanInstrumentationName(
27273
+ {
27274
+ name: `workflow:${workflowName}`,
27275
+ spanAttributes: { type: "task" /* TASK */ },
27276
+ startTime: eventTime(event.startedAt ?? event.timestamp),
27277
+ event: { metadata }
27278
+ },
27279
+ INSTRUMENTATION_NAMES.FLUE
27280
+ )
27281
+ );
26357
27282
  this.runsById.set(event.runId, { metadata, span });
26358
27283
  }
26359
27284
  handleRunEnd(event) {
@@ -26992,7 +27917,14 @@ function stateMatchesRun(state, runId) {
26992
27917
  return state.metadata["flue.run_id"] === runId;
26993
27918
  }
26994
27919
  function startFlueSpan(parent, args) {
26995
- return parent ? withCurrent(parent, () => startSpan(args)) : startSpan(args);
27920
+ return parent ? withCurrent(
27921
+ parent,
27922
+ () => startSpan(
27923
+ withSpanInstrumentationName(args, INSTRUMENTATION_NAMES.FLUE)
27924
+ )
27925
+ ) : startSpan(
27926
+ withSpanInstrumentationName(args, INSTRUMENTATION_NAMES.FLUE)
27927
+ );
26996
27928
  }
26997
27929
  function runWithCurrentSpanStore(span, next) {
26998
27930
  const state = _internalGetGlobalState();
@@ -27082,9 +28014,13 @@ var BraintrustLangChainCallbackHandler = class {
27082
28014
  ...this.options.debug ? { runId, parentRunId } : {}
27083
28015
  }
27084
28016
  };
27085
- let span = parentSpan.startSpan(args);
28017
+ const spanArgs = withSpanInstrumentationName(
28018
+ args,
28019
+ INSTRUMENTATION_NAMES.LANGCHAIN
28020
+ );
28021
+ let span = parentSpan.startSpan(spanArgs);
27086
28022
  if (!Object.is(this.options.logger, NOOP_SPAN) && Object.is(span, NOOP_SPAN)) {
27087
- span = initLogger().startSpan(args);
28023
+ span = initLogger().startSpan(spanArgs);
27088
28024
  }
27089
28025
  this.spans.set(runId, span);
27090
28026
  }
@@ -27381,16 +28317,20 @@ function isRecord(value) {
27381
28317
  }
27382
28318
 
27383
28319
  // src/instrumentation/plugins/langchain-channels.ts
27384
- var langChainChannels = defineChannels("@langchain/core", {
27385
- configure: channel({
27386
- channelName: "CallbackManager.configure",
27387
- kind: "sync-stream"
27388
- }),
27389
- configureSync: channel({
27390
- channelName: "CallbackManager._configureSync",
27391
- kind: "sync-stream"
27392
- })
27393
- });
28320
+ var langChainChannels = defineChannels(
28321
+ "@langchain/core",
28322
+ {
28323
+ configure: channel({
28324
+ channelName: "CallbackManager.configure",
28325
+ kind: "sync-stream"
28326
+ }),
28327
+ configureSync: channel({
28328
+ channelName: "CallbackManager._configureSync",
28329
+ kind: "sync-stream"
28330
+ })
28331
+ },
28332
+ { instrumentationName: INSTRUMENTATION_NAMES.LANGCHAIN }
28333
+ );
27394
28334
 
27395
28335
  // src/instrumentation/plugins/langchain-plugin.ts
27396
28336
  var LangChainPlugin = class extends BasePlugin {
@@ -27478,20 +28418,24 @@ function isBraintrustHandler(handler) {
27478
28418
  }
27479
28419
 
27480
28420
  // src/instrumentation/plugins/langsmith-channels.ts
27481
- var langSmithChannels = defineChannels("langsmith", {
27482
- createRun: channel({
27483
- channelName: "Client.createRun",
27484
- kind: "async"
27485
- }),
27486
- updateRun: channel({
27487
- channelName: "Client.updateRun",
27488
- kind: "async"
27489
- }),
27490
- batchIngestRuns: channel({
27491
- channelName: "Client.batchIngestRuns",
27492
- kind: "async"
27493
- })
27494
- });
28421
+ var langSmithChannels = defineChannels(
28422
+ "langsmith",
28423
+ {
28424
+ createRun: channel({
28425
+ channelName: "Client.createRun",
28426
+ kind: "async"
28427
+ }),
28428
+ updateRun: channel({
28429
+ channelName: "Client.updateRun",
28430
+ kind: "async"
28431
+ }),
28432
+ batchIngestRuns: channel({
28433
+ channelName: "Client.batchIngestRuns",
28434
+ kind: "async"
28435
+ })
28436
+ },
28437
+ { instrumentationName: INSTRUMENTATION_NAMES.LANGSMITH }
28438
+ );
27495
28439
 
27496
28440
  // src/instrumentation/plugins/langsmith-plugin.ts
27497
28441
  var MAX_COMPLETED_RUNS = 1e4;
@@ -27655,19 +28599,24 @@ var LangSmithPlugin = class extends BasePlugin {
27655
28599
  const traceId = stringValue2(ownValue(run, "trace_id")) ?? id;
27656
28600
  const parentId = stringValue2(ownValue(run, "parent_run_id")) ?? stringValue2(ownValue(ownValue(run, "parent_run"), "id"));
27657
28601
  const startTime = timestampSeconds(ownValue(run, "start_time"));
27658
- return startSpan({
27659
- name: stringValue2(ownValue(run, "name")) ?? "LangSmith run",
27660
- spanId: id,
27661
- parentSpanIds: {
27662
- parentSpanIds: parentId ? [parentId] : [],
27663
- rootSpanId: traceId
27664
- },
27665
- spanAttributes: {
27666
- type: mapRunType(ownValue(run, "run_type"))
27667
- },
27668
- ...startTime === void 0 ? {} : { startTime },
27669
- event: { id }
27670
- });
28602
+ return startSpan(
28603
+ withSpanInstrumentationName(
28604
+ {
28605
+ name: stringValue2(ownValue(run, "name")) ?? "LangSmith run",
28606
+ spanId: id,
28607
+ parentSpanIds: {
28608
+ parentSpanIds: parentId ? [parentId] : [],
28609
+ rootSpanId: traceId
28610
+ },
28611
+ spanAttributes: {
28612
+ type: mapRunType(ownValue(run, "run_type"))
28613
+ },
28614
+ ...startTime === void 0 ? {} : { startTime },
28615
+ event: { id }
28616
+ },
28617
+ INSTRUMENTATION_NAMES.LANGSMITH
28618
+ )
28619
+ );
27671
28620
  }
27672
28621
  logRun(span, run, previous, includeOutput) {
27673
28622
  const inputs = preferOwnValue(run, previous, "inputs");
@@ -27925,7 +28874,8 @@ var piCodingAgentChannels = defineChannels(
27925
28874
  channelName: "AgentSession.prompt",
27926
28875
  kind: "async"
27927
28876
  })
27928
- }
28877
+ },
28878
+ { instrumentationName: INSTRUMENTATION_NAMES.PI_CODING_AGENT }
27929
28879
  );
27930
28880
 
27931
28881
  // src/instrumentation/plugins/pi-coding-agent-plugin.ts
@@ -28009,14 +28959,19 @@ function startPiPromptRun(event, onFinalize) {
28009
28959
  ...session.model?.id || agent.state?.model?.id ? { model: session.model?.id ?? agent.state?.model?.id } : {},
28010
28960
  ...event.moduleVersion ? { "pi_coding_agent.version": event.moduleVersion } : {}
28011
28961
  };
28012
- const span = startSpan({
28013
- event: {
28014
- input: extractPromptInput(event.arguments[0], event.arguments[1]),
28015
- metadata
28016
- },
28017
- name: "AgentSession.prompt",
28018
- spanAttributes: { type: "task" /* TASK */ }
28019
- });
28962
+ const span = startSpan(
28963
+ withSpanInstrumentationName(
28964
+ {
28965
+ event: {
28966
+ input: extractPromptInput(event.arguments[0], event.arguments[1]),
28967
+ metadata
28968
+ },
28969
+ name: "AgentSession.prompt",
28970
+ spanAttributes: { type: "task" /* TASK */ }
28971
+ },
28972
+ INSTRUMENTATION_NAMES.PI_CODING_AGENT
28973
+ )
28974
+ );
28020
28975
  const streamPatchState = installPiStreamPatch(agent);
28021
28976
  const options = event.arguments[1];
28022
28977
  const promptText = event.arguments[0];
@@ -28186,15 +29141,20 @@ async function startPiLlmSpan(state, model, context, options) {
28186
29141
  ...extractToolMetadata(context.tools),
28187
29142
  "pi_coding_agent.operation": "agent.streamFn"
28188
29143
  };
28189
- const span = startSpan({
28190
- event: {
28191
- input: processInputAttachments(normalizePiContextInput(context)),
28192
- metadata
28193
- },
28194
- name: getLlmSpanName(model),
28195
- parent: await state.span.export(),
28196
- spanAttributes: { type: "llm" /* LLM */ }
28197
- });
29144
+ const span = startSpan(
29145
+ withSpanInstrumentationName(
29146
+ {
29147
+ event: {
29148
+ input: processInputAttachments(normalizePiContextInput(context)),
29149
+ metadata
29150
+ },
29151
+ name: getLlmSpanName(model),
29152
+ parent: await state.span.export(),
29153
+ spanAttributes: { type: "llm" /* LLM */ }
29154
+ },
29155
+ INSTRUMENTATION_NAMES.PI_CODING_AGENT
29156
+ )
29157
+ );
28198
29158
  const llmState = {
28199
29159
  finalized: false,
28200
29160
  metadata,
@@ -28362,15 +29322,20 @@ async function startPiToolSpan(state, event) {
28362
29322
  "pi_coding_agent.tool.name": event.toolName
28363
29323
  };
28364
29324
  try {
28365
- const span = startSpan({
28366
- event: {
28367
- input: event.args,
28368
- metadata
28369
- },
28370
- name: event.toolName || "tool",
28371
- parent: await state.span.export(),
28372
- spanAttributes: { type: "tool" /* TOOL */ }
28373
- });
29325
+ const span = startSpan(
29326
+ withSpanInstrumentationName(
29327
+ {
29328
+ event: {
29329
+ input: event.args,
29330
+ metadata
29331
+ },
29332
+ name: event.toolName || "tool",
29333
+ parent: await state.span.export(),
29334
+ spanAttributes: { type: "tool" /* TOOL */ }
29335
+ },
29336
+ INSTRUMENTATION_NAMES.PI_CODING_AGENT
29337
+ )
29338
+ );
28374
29339
  state.activeToolSpans.set(event.toolCallId, {
28375
29340
  restoreAutoInstrumentation,
28376
29341
  span
@@ -28802,20 +29767,24 @@ function logInstrumentationError4(context, error) {
28802
29767
  }
28803
29768
 
28804
29769
  // src/instrumentation/plugins/strands-agent-sdk-channels.ts
28805
- var strandsAgentSDKChannels = defineChannels("@strands-agents/sdk", {
28806
- agentStream: channel({
28807
- channelName: "Agent.stream",
28808
- kind: "sync-stream"
28809
- }),
28810
- graphStream: channel({
28811
- channelName: "Graph.stream",
28812
- kind: "sync-stream"
28813
- }),
28814
- swarmStream: channel({
28815
- channelName: "Swarm.stream",
28816
- kind: "sync-stream"
28817
- })
28818
- });
29770
+ var strandsAgentSDKChannels = defineChannels(
29771
+ "@strands-agents/sdk",
29772
+ {
29773
+ agentStream: channel({
29774
+ channelName: "Agent.stream",
29775
+ kind: "sync-stream"
29776
+ }),
29777
+ graphStream: channel({
29778
+ channelName: "Graph.stream",
29779
+ kind: "sync-stream"
29780
+ }),
29781
+ swarmStream: channel({
29782
+ channelName: "Swarm.stream",
29783
+ kind: "sync-stream"
29784
+ })
29785
+ },
29786
+ { instrumentationName: INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK }
29787
+ );
28819
29788
 
28820
29789
  // src/instrumentation/plugins/strands-agent-sdk-plugin.ts
28821
29790
  var MAX_STRANDS_STRING_ATTACHMENT_CACHE_ENTRIES = 32;
@@ -28970,22 +29939,32 @@ function startAgentStream(event, activeChildParents) {
28970
29939
  );
28971
29940
  const span = parentSpan ? withCurrent(
28972
29941
  parentSpan,
28973
- () => startSpan({
28974
- event: {
28975
- input,
28976
- metadata
29942
+ () => startSpan(
29943
+ withSpanInstrumentationName(
29944
+ {
29945
+ event: {
29946
+ input,
29947
+ metadata
29948
+ },
29949
+ name: formatAgentSpanName(agent),
29950
+ spanAttributes: { type: "task" /* TASK */ }
29951
+ },
29952
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
29953
+ )
29954
+ )
29955
+ ) : startSpan(
29956
+ withSpanInstrumentationName(
29957
+ {
29958
+ event: {
29959
+ input,
29960
+ metadata
29961
+ },
29962
+ name: formatAgentSpanName(agent),
29963
+ spanAttributes: { type: "task" /* TASK */ }
28977
29964
  },
28978
- name: formatAgentSpanName(agent),
28979
- spanAttributes: { type: "task" /* TASK */ }
28980
- })
28981
- ) : startSpan({
28982
- event: {
28983
- input,
28984
- metadata
28985
- },
28986
- name: formatAgentSpanName(agent),
28987
- spanAttributes: { type: "task" /* TASK */ }
28988
- });
29965
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
29966
+ )
29967
+ );
28989
29968
  return {
28990
29969
  activeTools: /* @__PURE__ */ new Map(),
28991
29970
  attachmentCache,
@@ -29007,22 +29986,32 @@ function startMultiAgentStream(event, operation, activeChildParents) {
29007
29986
  const input = processStrandsInputAttachments(event.arguments[0]);
29008
29987
  const span = parentSpan ? withCurrent(
29009
29988
  parentSpan,
29010
- () => startSpan({
29011
- event: {
29012
- input,
29013
- metadata
29989
+ () => startSpan(
29990
+ withSpanInstrumentationName(
29991
+ {
29992
+ event: {
29993
+ input,
29994
+ metadata
29995
+ },
29996
+ name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
29997
+ spanAttributes: { type: "task" /* TASK */ }
29998
+ },
29999
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
30000
+ )
30001
+ )
30002
+ ) : startSpan(
30003
+ withSpanInstrumentationName(
30004
+ {
30005
+ event: {
30006
+ input,
30007
+ metadata
30008
+ },
30009
+ name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
30010
+ spanAttributes: { type: "task" /* TASK */ }
29014
30011
  },
29015
- name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
29016
- spanAttributes: { type: "task" /* TASK */ }
29017
- })
29018
- ) : startSpan({
29019
- event: {
29020
- input,
29021
- metadata
29022
- },
29023
- name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
29024
- spanAttributes: { type: "task" /* TASK */ }
29025
- });
30012
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
30013
+ )
30014
+ );
29026
30015
  return {
29027
30016
  activeNodes: /* @__PURE__ */ new Map(),
29028
30017
  finalized: false,
@@ -29124,17 +30113,22 @@ function startModelSpan(state, event) {
29124
30113
  };
29125
30114
  const span = withCurrent(
29126
30115
  state.span,
29127
- () => startSpan({
29128
- event: {
29129
- input: Array.isArray(event.agent?.messages) ? processStrandsInputAttachments(
29130
- event.agent.messages,
29131
- state.attachmentCache
29132
- ) : void 0,
29133
- metadata
29134
- },
29135
- name: formatModelSpanName(model),
29136
- spanAttributes: { type: "llm" /* LLM */ }
29137
- })
30116
+ () => startSpan(
30117
+ withSpanInstrumentationName(
30118
+ {
30119
+ event: {
30120
+ input: Array.isArray(event.agent?.messages) ? processStrandsInputAttachments(
30121
+ event.agent.messages,
30122
+ state.attachmentCache
30123
+ ) : void 0,
30124
+ metadata
30125
+ },
30126
+ name: formatModelSpanName(model),
30127
+ spanAttributes: { type: "llm" /* LLM */ }
30128
+ },
30129
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
30130
+ )
30131
+ )
29138
30132
  );
29139
30133
  state.activeModel = {
29140
30134
  metadata,
@@ -29186,20 +30180,25 @@ function startToolSpan2(state, event) {
29186
30180
  const name = extractToolName3(toolUse, event.tool);
29187
30181
  const span = withCurrent(
29188
30182
  state.span,
29189
- () => startSpan({
29190
- event: {
29191
- input: toolUse?.input,
29192
- metadata: {
29193
- "gen_ai.tool.call.id": toolUse?.toolUseId,
29194
- "gen_ai.tool.name": name,
29195
- "strands.operation": "tool.call",
29196
- "strands.tool.name": name,
29197
- provider: "strands"
29198
- }
29199
- },
29200
- name: `tool: ${name}`,
29201
- spanAttributes: { type: "tool" /* TOOL */ }
29202
- })
30183
+ () => startSpan(
30184
+ withSpanInstrumentationName(
30185
+ {
30186
+ event: {
30187
+ input: toolUse?.input,
30188
+ metadata: {
30189
+ "gen_ai.tool.call.id": toolUse?.toolUseId,
30190
+ "gen_ai.tool.name": name,
30191
+ "strands.operation": "tool.call",
30192
+ "strands.tool.name": name,
30193
+ provider: "strands"
30194
+ }
30195
+ },
30196
+ name: `tool: ${name}`,
30197
+ spanAttributes: { type: "tool" /* TOOL */ }
30198
+ },
30199
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
30200
+ )
30201
+ )
29203
30202
  );
29204
30203
  state.activeTools.set(key, {
29205
30204
  span,
@@ -29270,11 +30269,16 @@ function startNodeSpan(state, event, activeChildParents) {
29270
30269
  };
29271
30270
  const span = withCurrent(
29272
30271
  state.span,
29273
- () => startSpan({
29274
- event: { metadata },
29275
- name: `node: ${nodeId}`,
29276
- spanAttributes: { type: "task" /* TASK */ }
29277
- })
30272
+ () => startSpan(
30273
+ withSpanInstrumentationName(
30274
+ {
30275
+ event: { metadata },
30276
+ name: `node: ${nodeId}`,
30277
+ spanAttributes: { type: "task" /* TASK */ }
30278
+ },
30279
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
30280
+ )
30281
+ )
29278
30282
  );
29279
30283
  const nodeState = {
29280
30284
  ...child ? { child } : {},
@@ -30088,7 +31092,12 @@ var EveBridge = class {
30088
31092
  };
30089
31093
  const span = withCurrent(
30090
31094
  NOOP_SPAN,
30091
- () => _internalStartSpanWithInitialMerge({ ...args, startTime })
31095
+ () => _internalStartSpanWithInitialMerge(
31096
+ withSpanInstrumentationName(
31097
+ { ...args, startTime },
31098
+ INSTRUMENTATION_NAMES.EVE
31099
+ )
31100
+ )
30092
31101
  );
30093
31102
  if (typeof rowId !== "string") {
30094
31103
  return span;