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
@@ -4920,7 +4920,51 @@ var SpanCache = class {
4920
4920
  };
4921
4921
 
4922
4922
  // src/span-origin.ts
4923
- var SDK_VERSION = true ? "3.24.0" : "0.0.0";
4923
+ var INSTRUMENTATION_NAMES = {
4924
+ AI_SDK: "ai-sdk",
4925
+ ANTHROPIC: "anthropic",
4926
+ BEDROCK_RUNTIME: "bedrock-runtime",
4927
+ BRAINTRUST_JS_LOGGER: "braintrust-js-logger",
4928
+ CLAUDE_AGENT_SDK: "claude-agent-sdk",
4929
+ COHERE: "cohere",
4930
+ CURSOR_SDK: "cursor-sdk",
4931
+ EVE: "eve",
4932
+ FLUE: "flue",
4933
+ GENKIT: "genkit",
4934
+ GITHUB_COPILOT: "github-copilot",
4935
+ GOOGLE_ADK: "google-adk",
4936
+ GOOGLE_GENAI: "google-genai",
4937
+ GROQ: "groq",
4938
+ HUGGINGFACE: "huggingface",
4939
+ LANGCHAIN: "langchain",
4940
+ LANGSMITH: "langsmith",
4941
+ MASTRA: "mastra",
4942
+ MISTRAL: "mistral",
4943
+ OPENAI: "openai",
4944
+ OPENAI_AGENTS: "openai-agents",
4945
+ OPENAI_CODEX: "openai-codex",
4946
+ OPENROUTER: "openrouter",
4947
+ OPENROUTER_AGENT: "openrouter-agent",
4948
+ PI_CODING_AGENT: "pi-coding-agent",
4949
+ STRANDS_AGENT_SDK: "strands-agent-sdk"
4950
+ };
4951
+ var INTERNAL_SPAN_INSTRUMENTATION_NAME = /* @__PURE__ */ Symbol.for(
4952
+ "braintrust.spanInstrumentationName"
4953
+ );
4954
+ var SDK_VERSION = true ? "3.25.0" : "0.0.0";
4955
+ function withSpanInstrumentationName(args, instrumentationName) {
4956
+ return {
4957
+ ...args,
4958
+ [INTERNAL_SPAN_INSTRUMENTATION_NAME]: instrumentationName
4959
+ };
4960
+ }
4961
+ function getSpanInstrumentationName(args) {
4962
+ if (typeof args !== "object" || args === null) {
4963
+ return void 0;
4964
+ }
4965
+ const value = args[INTERNAL_SPAN_INSTRUMENTATION_NAME];
4966
+ return isSpanInstrumentationName(value) ? value : void 0;
4967
+ }
4924
4968
  function detectSpanOriginEnvironment(explicit) {
4925
4969
  if (explicit) return explicit;
4926
4970
  const envType = isomorph_default.getEnv("BRAINTRUST_ENVIRONMENT_TYPE");
@@ -4992,6 +5036,9 @@ function mergeSpanOriginContext(context, instrumentationName, environment) {
4992
5036
  };
4993
5037
  return next;
4994
5038
  }
5039
+ function isSpanInstrumentationName(value) {
5040
+ return Object.values(INSTRUMENTATION_NAMES).some((name) => name === value);
5041
+ }
4995
5042
  function firstPresent(entries) {
4996
5043
  return entries.find(([key]) => Boolean(isomorph_default.getEnv(key)))?.[1];
4997
5044
  }
@@ -5286,6 +5333,7 @@ var BraintrustState = class _BraintrustState {
5286
5333
  });
5287
5334
  this.spanCache = new SpanCache({ disabled: loginParams.disableSpanCache });
5288
5335
  this.spanOriginEnvironment = detectSpanOriginEnvironment();
5336
+ this._internalSetTraceContextSigningSecret(loginParams.apiKey);
5289
5337
  }
5290
5338
  loginParams;
5291
5339
  id;
@@ -5323,6 +5371,18 @@ var BraintrustState = class _BraintrustState {
5323
5371
  _contextManager = null;
5324
5372
  _otelFlushCallback = null;
5325
5373
  spanOriginEnvironment;
5374
+ traceContextSigningSecret;
5375
+ /** @internal */
5376
+ _internalSetTraceContextSigningSecret(secret) {
5377
+ const normalizedSecret = secret?.trim();
5378
+ if (normalizedSecret) {
5379
+ this.traceContextSigningSecret = normalizedSecret;
5380
+ }
5381
+ }
5382
+ /** @internal */
5383
+ _internalGetTraceContextSigningSecret() {
5384
+ return (this.traceContextSigningSecret ?? this.loginToken ?? isomorph_default.getEnv("BRAINTRUST_API_KEY"))?.trim();
5385
+ }
5326
5386
  resetLoginInfo() {
5327
5387
  this.appUrl = null;
5328
5388
  this.appPublicUrl = null;
@@ -5383,6 +5443,7 @@ var BraintrustState = class _BraintrustState {
5383
5443
  this.gitMetadataSettings = other.gitMetadataSettings;
5384
5444
  this.debugLogLevel = other.debugLogLevel;
5385
5445
  this.debugLogLevelConfigured = other.debugLogLevelConfigured;
5446
+ this.traceContextSigningSecret = other.traceContextSigningSecret;
5386
5447
  setGlobalDebugLogLevel(
5387
5448
  this.debugLogLevelConfigured ? this.debugLogLevel ?? false : void 0
5388
5449
  );
@@ -5470,6 +5531,7 @@ var BraintrustState = class _BraintrustState {
5470
5531
  return this.debugLogLevelConfigured;
5471
5532
  }
5472
5533
  async login(loginParams) {
5534
+ this._internalSetTraceContextSigningSecret(loginParams.apiKey);
5473
5535
  this.setDebugLogLevel(loginParams.debugLogLevel);
5474
5536
  if (this.apiUrl && !loginParams.forceLogin) {
5475
5537
  return;
@@ -7256,6 +7318,7 @@ function initLogger(options = {}) {
7256
7318
  project_id: projectId
7257
7319
  };
7258
7320
  const state = stateArg ?? _globalState;
7321
+ state._internalSetTraceContextSigningSecret(apiKey);
7259
7322
  state.setDebugLogLevel(debugLogLevel);
7260
7323
  state.spanOriginEnvironment = detectSpanOriginEnvironment(environment);
7261
7324
  state.enforceQueueSizeLimit(true);
@@ -7780,7 +7843,9 @@ function deepCopyEvent(event) {
7780
7843
  const ATTACHMENT_MARKER_KEY = "_bt_internal_saved_attachment_marker";
7781
7844
  const attachmentMarker = ++deepCopyEventMarkerCounter;
7782
7845
  const serialized = JSON.stringify(event, (_k, v) => {
7783
- if (v instanceof SpanImpl || v instanceof NoopSpan) {
7846
+ if (v instanceof Error) {
7847
+ return v.message;
7848
+ } else if (v instanceof SpanImpl || v instanceof NoopSpan) {
7784
7849
  return `<span>`;
7785
7850
  } else if (v instanceof Experiment2) {
7786
7851
  return `<experiment>`;
@@ -8392,6 +8457,7 @@ var SpanImpl = class _SpanImpl {
8392
8457
  constructor(args) {
8393
8458
  this._state = args.state;
8394
8459
  this._propagatedState = args.propagatedState;
8460
+ const instrumentationName = getSpanInstrumentationName(args) ?? INSTRUMENTATION_NAMES.BRAINTRUST_JS_LOGGER;
8395
8461
  const spanAttributes = args.spanAttributes ?? {};
8396
8462
  const rawEvent = args.event ?? {};
8397
8463
  const type = args.type ?? (args.parentSpanIds ? void 0 : args.defaultRootType);
@@ -8423,7 +8489,7 @@ var SpanImpl = class _SpanImpl {
8423
8489
  },
8424
8490
  context: mergeSpanOriginContext(
8425
8491
  { ...callerLocation },
8426
- "braintrust-js-logger",
8492
+ instrumentationName,
8427
8493
  this._state.spanOriginEnvironment
8428
8494
  ),
8429
8495
  span_attributes: {
@@ -9648,15 +9714,25 @@ function hasChoices(value) {
9648
9714
  function normalizeMetadata(metadata) {
9649
9715
  return isObject(metadata) ? metadata : void 0;
9650
9716
  }
9651
- function startSpanForEvent(config, event, channelName) {
9717
+ function startSpanForEvent(config, event, channelName, instrumentationName) {
9652
9718
  const { name, spanAttributes, spanInfoMetadata } = buildStartSpanArgs(
9653
9719
  config,
9654
9720
  event
9655
9721
  );
9656
- const span = startSpan({
9657
- name,
9658
- spanAttributes
9659
- });
9722
+ const spanArgs = withSpanInstrumentationName(
9723
+ {
9724
+ name,
9725
+ spanAttributes
9726
+ },
9727
+ instrumentationName
9728
+ );
9729
+ let span;
9730
+ try {
9731
+ span = config.startSpan?.(spanArgs) ?? startSpan(spanArgs);
9732
+ } catch (error) {
9733
+ debugLogger.error(`Error starting span for ${channelName}:`, error);
9734
+ span = startSpan(spanArgs);
9735
+ }
9660
9736
  const startTime = getCurrentUnixTimestamp();
9661
9737
  try {
9662
9738
  const { input, metadata } = config.extractInput(
@@ -9687,7 +9763,7 @@ function shouldTraceEvent(config, event, channelName) {
9687
9763
  return true;
9688
9764
  }
9689
9765
  }
9690
- function ensureSpanStateForEvent(states, config, event, channelName) {
9766
+ function ensureSpanStateForEvent(states, config, event, channelName, instrumentationName) {
9691
9767
  const key = event;
9692
9768
  const existing = states.get(key);
9693
9769
  if (existing) {
@@ -9696,11 +9772,16 @@ function ensureSpanStateForEvent(states, config, event, channelName) {
9696
9772
  if (!shouldTraceEvent(config, event, channelName)) {
9697
9773
  return void 0;
9698
9774
  }
9699
- const created = startSpanForEvent(config, event, channelName);
9775
+ const created = startSpanForEvent(
9776
+ config,
9777
+ event,
9778
+ channelName,
9779
+ instrumentationName
9780
+ );
9700
9781
  states.set(key, created);
9701
9782
  return created;
9702
9783
  }
9703
- function bindCurrentSpanStoreToStart(tracingChannel, states, config, channelName) {
9784
+ function bindCurrentSpanStoreToStart(tracingChannel, states, config, channelName, instrumentationName) {
9704
9785
  const state = _internalGetGlobalState();
9705
9786
  const startChannel = tracingChannel.start;
9706
9787
  const contextManager = state?.contextManager;
@@ -9718,7 +9799,8 @@ function bindCurrentSpanStoreToStart(tracingChannel, states, config, channelName
9718
9799
  states,
9719
9800
  config,
9720
9801
  event,
9721
- channelName
9802
+ channelName,
9803
+ instrumentationName
9722
9804
  );
9723
9805
  return spanState ? contextManager.wrapSpanForStore(spanState.span) : currentSpanStore.getStore();
9724
9806
  }
@@ -9727,15 +9809,21 @@ function bindCurrentSpanStoreToStart(tracingChannel, states, config, channelName
9727
9809
  startChannel.unbindStore(currentSpanStore);
9728
9810
  };
9729
9811
  }
9730
- function logErrorAndEnd(states, event) {
9812
+ function logErrorAndEnd(states, event, channelName) {
9731
9813
  const spanData = states.get(event);
9732
9814
  if (!spanData) {
9733
9815
  return;
9734
9816
  }
9735
- spanData.span.log({
9736
- error: event.error.message
9737
- });
9738
- spanData.span.end();
9817
+ try {
9818
+ spanData.span.log({ error: event.error });
9819
+ } catch (error) {
9820
+ debugLogger.error(`Error logging failure for ${channelName}:`, error);
9821
+ }
9822
+ try {
9823
+ spanData.span.end();
9824
+ } catch (error) {
9825
+ debugLogger.error(`Error ending span for ${channelName}:`, error);
9826
+ }
9739
9827
  states.delete(event);
9740
9828
  }
9741
9829
  function runStreamingCompletionHook(args) {
@@ -9785,7 +9873,8 @@ function traceAsyncChannel(channel2, config) {
9785
9873
  tracingChannel,
9786
9874
  states,
9787
9875
  config,
9788
- channelName
9876
+ channelName,
9877
+ channel2.instrumentationName
9789
9878
  );
9790
9879
  const handlers = {
9791
9880
  start: (event) => {
@@ -9796,7 +9885,8 @@ function traceAsyncChannel(channel2, config) {
9796
9885
  states,
9797
9886
  config,
9798
9887
  event,
9799
- channelName
9888
+ channelName,
9889
+ channel2.instrumentationName
9800
9890
  );
9801
9891
  },
9802
9892
  asyncEnd: (event) => {
@@ -9833,7 +9923,7 @@ function traceAsyncChannel(channel2, config) {
9833
9923
  }
9834
9924
  },
9835
9925
  error: (event) => {
9836
- logErrorAndEnd(states, event);
9926
+ logErrorAndEnd(states, event, channelName);
9837
9927
  }
9838
9928
  };
9839
9929
  tracingChannel.subscribe(handlers);
@@ -9850,7 +9940,8 @@ function traceStreamingChannel(channel2, config) {
9850
9940
  tracingChannel,
9851
9941
  states,
9852
9942
  config,
9853
- channelName
9943
+ channelName,
9944
+ channel2.instrumentationName
9854
9945
  );
9855
9946
  const handlers = {
9856
9947
  start: (event) => {
@@ -9861,7 +9952,8 @@ function traceStreamingChannel(channel2, config) {
9861
9952
  states,
9862
9953
  config,
9863
9954
  event,
9864
- channelName
9955
+ channelName,
9956
+ channel2.instrumentationName
9865
9957
  );
9866
9958
  },
9867
9959
  asyncEnd: (event) => {
@@ -9880,6 +9972,7 @@ function traceStreamingChannel(channel2, config) {
9880
9972
  }
9881
9973
  },
9882
9974
  onComplete: (chunks) => {
9975
+ let completion2;
9883
9976
  try {
9884
9977
  let output;
9885
9978
  let metrics;
@@ -9910,18 +10003,11 @@ function traceStreamingChannel(channel2, config) {
9910
10003
  } else if (metrics.time_to_first_token === void 0 && chunks.length > 0) {
9911
10004
  metrics.time_to_first_token = getCurrentUnixTimestamp() - startTime;
9912
10005
  }
9913
- runStreamingCompletionHook({
9914
- channelName,
9915
- chunks,
9916
- config,
9917
- endEvent: asyncEndEvent,
10006
+ completion2 = {
9918
10007
  ...metadata !== void 0 ? { metadata } : {},
9919
10008
  metrics,
9920
- output,
9921
- result: asyncEndEvent.result,
9922
- span,
9923
- startTime
9924
- });
10009
+ output
10010
+ };
9925
10011
  span.log({
9926
10012
  output,
9927
10013
  ...metadata !== void 0 ? { metadata } : {},
@@ -9933,11 +10019,49 @@ function traceStreamingChannel(channel2, config) {
9933
10019
  error
9934
10020
  );
9935
10021
  } finally {
9936
- span.end();
10022
+ try {
10023
+ span.end();
10024
+ } catch (error) {
10025
+ debugLogger.error(
10026
+ `Error ending span for ${channelName}:`,
10027
+ error
10028
+ );
10029
+ }
9937
10030
  states.delete(event);
9938
10031
  }
10032
+ if (completion2) {
10033
+ runStreamingCompletionHook({
10034
+ channelName,
10035
+ chunks,
10036
+ config,
10037
+ endEvent: asyncEndEvent,
10038
+ ...completion2.metadata !== void 0 ? { metadata: completion2.metadata } : {},
10039
+ metrics: completion2.metrics,
10040
+ output: completion2.output,
10041
+ result: asyncEndEvent.result,
10042
+ span,
10043
+ startTime
10044
+ });
10045
+ }
9939
10046
  },
9940
10047
  onError: (error) => {
10048
+ try {
10049
+ span.log({ error });
10050
+ } catch (loggingError) {
10051
+ debugLogger.error(
10052
+ `Error logging failure for ${channelName}:`,
10053
+ loggingError
10054
+ );
10055
+ }
10056
+ try {
10057
+ span.end();
10058
+ } catch (endingError) {
10059
+ debugLogger.error(
10060
+ `Error ending span for ${channelName}:`,
10061
+ endingError
10062
+ );
10063
+ }
10064
+ states.delete(event);
9941
10065
  runStreamingErrorHook({
9942
10066
  channelName,
9943
10067
  config,
@@ -9946,11 +10070,6 @@ function traceStreamingChannel(channel2, config) {
9946
10070
  span,
9947
10071
  startTime
9948
10072
  });
9949
- span.log({
9950
- error: error.message
9951
- });
9952
- span.end();
9953
- states.delete(event);
9954
10073
  }
9955
10074
  });
9956
10075
  return;
@@ -9965,6 +10084,7 @@ function traceStreamingChannel(channel2, config) {
9965
10084
  states.delete(event);
9966
10085
  return;
9967
10086
  }
10087
+ let completion;
9968
10088
  try {
9969
10089
  const output = config.extractOutput(
9970
10090
  asyncEndEvent.result,
@@ -9979,17 +10099,11 @@ function traceStreamingChannel(channel2, config) {
9979
10099
  asyncEndEvent.result,
9980
10100
  asyncEndEvent
9981
10101
  );
9982
- runStreamingCompletionHook({
9983
- channelName,
9984
- config,
9985
- endEvent: asyncEndEvent,
10102
+ completion = {
9986
10103
  ...normalizeMetadata(metadata) !== void 0 ? { metadata: normalizeMetadata(metadata) } : {},
9987
10104
  metrics,
9988
- output,
9989
- result: asyncEndEvent.result,
9990
- span,
9991
- startTime
9992
- });
10105
+ output
10106
+ };
9993
10107
  span.log({
9994
10108
  output,
9995
10109
  ...normalizeMetadata(metadata) !== void 0 ? { metadata: normalizeMetadata(metadata) } : {},
@@ -9998,12 +10112,30 @@ function traceStreamingChannel(channel2, config) {
9998
10112
  } catch (error) {
9999
10113
  debugLogger.error(`Error extracting output for ${channelName}:`, error);
10000
10114
  } finally {
10001
- span.end();
10115
+ try {
10116
+ span.end();
10117
+ } catch (error) {
10118
+ debugLogger.error(`Error ending span for ${channelName}:`, error);
10119
+ }
10002
10120
  states.delete(event);
10003
10121
  }
10122
+ if (completion) {
10123
+ runStreamingCompletionHook({
10124
+ channelName,
10125
+ config,
10126
+ endEvent: asyncEndEvent,
10127
+ ...completion.metadata !== void 0 ? { metadata: completion.metadata } : {},
10128
+ metrics: completion.metrics,
10129
+ output: completion.output,
10130
+ result: asyncEndEvent.result,
10131
+ span,
10132
+ startTime
10133
+ });
10134
+ }
10004
10135
  },
10005
10136
  error: (event) => {
10006
10137
  const spanData = states.get(event);
10138
+ logErrorAndEnd(states, event, channelName);
10007
10139
  if (spanData) {
10008
10140
  runStreamingErrorHook({
10009
10141
  channelName,
@@ -10014,7 +10146,6 @@ function traceStreamingChannel(channel2, config) {
10014
10146
  startTime: spanData.startTime
10015
10147
  });
10016
10148
  }
10017
- logErrorAndEnd(states, event);
10018
10149
  }
10019
10150
  };
10020
10151
  tracingChannel.subscribe(handlers);
@@ -10031,7 +10162,8 @@ function traceSyncStreamChannel(channel2, config) {
10031
10162
  tracingChannel,
10032
10163
  states,
10033
10164
  config,
10034
- channelName
10165
+ channelName,
10166
+ channel2.instrumentationName
10035
10167
  );
10036
10168
  const handlers = {
10037
10169
  start: (event) => {
@@ -10042,7 +10174,8 @@ function traceSyncStreamChannel(channel2, config) {
10042
10174
  states,
10043
10175
  config,
10044
10176
  event,
10045
- channelName
10177
+ channelName,
10178
+ channel2.instrumentationName
10046
10179
  );
10047
10180
  },
10048
10181
  end: (event) => {
@@ -10136,7 +10269,7 @@ function traceSyncStreamChannel(channel2, config) {
10136
10269
  handleResolvedResult(endEvent.result);
10137
10270
  },
10138
10271
  error: (event) => {
10139
- logErrorAndEnd(states, event);
10272
+ logErrorAndEnd(states, event, channelName);
10140
10273
  }
10141
10274
  };
10142
10275
  tracingChannel.subscribe(handlers);
@@ -10315,7 +10448,8 @@ function processInputAttachments(input) {
10315
10448
  function channel(spec) {
10316
10449
  return spec;
10317
10450
  }
10318
- function defineChannels(pkg, channels) {
10451
+ function defineChannels(pkg, channels, options) {
10452
+ const { instrumentationName } = options;
10319
10453
  return Object.fromEntries(
10320
10454
  Object.entries(channels).map(([key, spec]) => {
10321
10455
  const fullChannelName = `orchestrion:${pkg}:${spec.channelName}`;
@@ -10328,6 +10462,7 @@ function defineChannels(pkg, channels) {
10328
10462
  key,
10329
10463
  {
10330
10464
  ...asyncSpec,
10465
+ instrumentationName,
10331
10466
  tracingChannel: tracingChannel2,
10332
10467
  tracePromise: (fn, context) => tracingChannel2().tracePromise(
10333
10468
  fn,
@@ -10345,6 +10480,7 @@ function defineChannels(pkg, channels) {
10345
10480
  key,
10346
10481
  {
10347
10482
  ...syncSpec,
10483
+ instrumentationName,
10348
10484
  tracingChannel,
10349
10485
  traceSync: (fn, context) => tracingChannel().traceSync(
10350
10486
  fn,
@@ -10358,44 +10494,48 @@ function defineChannels(pkg, channels) {
10358
10494
  }
10359
10495
 
10360
10496
  // src/instrumentation/plugins/openai-channels.ts
10361
- var openAIChannels = defineChannels("openai", {
10362
- chatCompletionsCreate: channel({
10363
- channelName: "chat.completions.create",
10364
- kind: "async"
10365
- }),
10366
- embeddingsCreate: channel({
10367
- channelName: "embeddings.create",
10368
- kind: "async"
10369
- }),
10370
- betaChatCompletionsParse: channel({
10371
- channelName: "beta.chat.completions.parse",
10372
- kind: "async"
10373
- }),
10374
- betaChatCompletionsStream: channel({
10375
- channelName: "beta.chat.completions.stream",
10376
- kind: "sync-stream"
10377
- }),
10378
- moderationsCreate: channel({
10379
- channelName: "moderations.create",
10380
- kind: "async"
10381
- }),
10382
- responsesCreate: channel({
10383
- channelName: "responses.create",
10384
- kind: "async"
10385
- }),
10386
- responsesStream: channel({
10387
- channelName: "responses.stream",
10388
- kind: "sync-stream"
10389
- }),
10390
- responsesParse: channel({
10391
- channelName: "responses.parse",
10392
- kind: "async"
10393
- }),
10394
- responsesCompact: channel({
10395
- channelName: "responses.compact",
10396
- kind: "async"
10397
- })
10398
- });
10497
+ var openAIChannels = defineChannels(
10498
+ "openai",
10499
+ {
10500
+ chatCompletionsCreate: channel({
10501
+ channelName: "chat.completions.create",
10502
+ kind: "async"
10503
+ }),
10504
+ embeddingsCreate: channel({
10505
+ channelName: "embeddings.create",
10506
+ kind: "async"
10507
+ }),
10508
+ betaChatCompletionsParse: channel({
10509
+ channelName: "beta.chat.completions.parse",
10510
+ kind: "async"
10511
+ }),
10512
+ betaChatCompletionsStream: channel({
10513
+ channelName: "beta.chat.completions.stream",
10514
+ kind: "sync-stream"
10515
+ }),
10516
+ moderationsCreate: channel({
10517
+ channelName: "moderations.create",
10518
+ kind: "async"
10519
+ }),
10520
+ responsesCreate: channel({
10521
+ channelName: "responses.create",
10522
+ kind: "async"
10523
+ }),
10524
+ responsesStream: channel({
10525
+ channelName: "responses.stream",
10526
+ kind: "sync-stream"
10527
+ }),
10528
+ responsesParse: channel({
10529
+ channelName: "responses.parse",
10530
+ kind: "async"
10531
+ }),
10532
+ responsesCompact: channel({
10533
+ channelName: "responses.compact",
10534
+ kind: "async"
10535
+ })
10536
+ },
10537
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENAI }
10538
+ );
10399
10539
 
10400
10540
  // src/openai-utils.ts
10401
10541
  var BRAINTRUST_CACHED_STREAM_METRIC = "__braintrust_cached_metric";
@@ -10910,16 +11050,20 @@ function aggregateResponseStreamEvents(chunks, _streamResult, endEvent) {
10910
11050
  }
10911
11051
 
10912
11052
  // src/instrumentation/plugins/openai-codex-channels.ts
10913
- var openAICodexChannels = defineChannels("@openai/codex-sdk", {
10914
- run: channel({
10915
- channelName: "Thread.run",
10916
- kind: "async"
10917
- }),
10918
- runStreamed: channel({
10919
- channelName: "Thread.runStreamed",
10920
- kind: "async"
10921
- })
10922
- });
11053
+ var openAICodexChannels = defineChannels(
11054
+ "@openai/codex-sdk",
11055
+ {
11056
+ run: channel({
11057
+ channelName: "Thread.run",
11058
+ kind: "async"
11059
+ }),
11060
+ runStreamed: channel({
11061
+ channelName: "Thread.runStreamed",
11062
+ kind: "async"
11063
+ })
11064
+ },
11065
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENAI_CODEX }
11066
+ );
10923
11067
 
10924
11068
  // src/instrumentation/plugins/openai-codex-plugin.ts
10925
11069
  var PATCHED_STREAMED_TURN = /* @__PURE__ */ Symbol.for(
@@ -11007,10 +11151,15 @@ function startCodexRun(event, operation) {
11007
11151
  provider: "openai",
11008
11152
  ...event.moduleVersion ? { "openai_codex.version": event.moduleVersion } : {}
11009
11153
  };
11010
- const span = startSpan({
11011
- name: "OpenAI Codex",
11012
- spanAttributes: { type: "task" /* TASK */ }
11013
- });
11154
+ const span = startSpan(
11155
+ withSpanInstrumentationName(
11156
+ {
11157
+ name: "OpenAI Codex",
11158
+ spanAttributes: { type: "task" /* TASK */ }
11159
+ },
11160
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
11161
+ )
11162
+ );
11014
11163
  const startTime = getCurrentUnixTimestamp();
11015
11164
  safeLog(span, {
11016
11165
  input: sanitizedInput,
@@ -11159,7 +11308,12 @@ async function createCompletedItemSpan(state, item) {
11159
11308
  if (!spanArgs) {
11160
11309
  return;
11161
11310
  }
11162
- const span = startSpan(spanArgs.start);
11311
+ const span = startSpan(
11312
+ withSpanInstrumentationName(
11313
+ spanArgs.start,
11314
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
11315
+ )
11316
+ );
11163
11317
  safeLog(span, spanArgs.end);
11164
11318
  span.end();
11165
11319
  }
@@ -11201,15 +11355,20 @@ async function ensureActiveLlmSpan(state) {
11201
11355
  ...state.metadata["openai_codex.thread_id"] ? { "openai_codex.thread_id": state.metadata["openai_codex.thread_id"] } : {},
11202
11356
  "openai_codex.llm_sequence": sequence
11203
11357
  };
11204
- const span = startSpan({
11205
- event: {
11206
- ...sequence === 1 ? { input: state.input } : {},
11207
- metadata
11208
- },
11209
- name: "OpenAI Codex LLM",
11210
- parent: await state.span.export(),
11211
- spanAttributes: { type: "llm" /* LLM */ }
11212
- });
11358
+ const span = startSpan(
11359
+ withSpanInstrumentationName(
11360
+ {
11361
+ event: {
11362
+ ...sequence === 1 ? { input: state.input } : {},
11363
+ metadata
11364
+ },
11365
+ name: "OpenAI Codex LLM",
11366
+ parent: await state.span.export(),
11367
+ spanAttributes: { type: "llm" /* LLM */ }
11368
+ },
11369
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
11370
+ )
11371
+ );
11213
11372
  state.activeLlmSpan = {
11214
11373
  anonymousMessages: [],
11215
11374
  anonymousReasoning: [],
@@ -11255,7 +11414,15 @@ async function startCodexItemSpan(state, item) {
11255
11414
  if (!spanArgs) {
11256
11415
  return;
11257
11416
  }
11258
- state.activeItemSpans.set(itemId, startSpan(spanArgs.start));
11417
+ state.activeItemSpans.set(
11418
+ itemId,
11419
+ startSpan(
11420
+ withSpanInstrumentationName(
11421
+ spanArgs.start,
11422
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
11423
+ )
11424
+ )
11425
+ );
11259
11426
  }
11260
11427
  function updateCodexItem(state, item) {
11261
11428
  if (item.type === "agent_message" && typeof item.text === "string") {
@@ -11565,20 +11732,24 @@ function extractAnthropicCacheTokens(cacheReadTokens = 0, cacheCreationTokens =
11565
11732
  }
11566
11733
 
11567
11734
  // src/instrumentation/plugins/anthropic-channels.ts
11568
- var anthropicChannels = defineChannels("@anthropic-ai/sdk", {
11569
- messagesCreate: channel({
11570
- channelName: "messages.create",
11571
- kind: "async"
11572
- }),
11573
- betaMessagesCreate: channel({
11574
- channelName: "beta.messages.create",
11575
- kind: "async"
11576
- }),
11577
- betaMessagesToolRunner: channel({
11578
- channelName: "beta.messages.toolRunner",
11579
- kind: "sync-stream"
11580
- })
11581
- });
11735
+ var anthropicChannels = defineChannels(
11736
+ "@anthropic-ai/sdk",
11737
+ {
11738
+ messagesCreate: channel({
11739
+ channelName: "messages.create",
11740
+ kind: "async"
11741
+ }),
11742
+ betaMessagesCreate: channel({
11743
+ channelName: "beta.messages.create",
11744
+ kind: "async"
11745
+ }),
11746
+ betaMessagesToolRunner: channel({
11747
+ channelName: "beta.messages.toolRunner",
11748
+ kind: "sync-stream"
11749
+ })
11750
+ },
11751
+ { instrumentationName: INSTRUMENTATION_NAMES.ANTHROPIC }
11752
+ );
11582
11753
 
11583
11754
  // src/instrumentation/plugins/anthropic-plugin.ts
11584
11755
  var ANTHROPIC_TOOL_RUNNER_TOOL_WRAPPED = /* @__PURE__ */ Symbol.for(
@@ -11651,12 +11822,17 @@ var AnthropicPlugin = class extends BasePlugin {
11651
11822
  return;
11652
11823
  }
11653
11824
  const params = event.arguments[0] ?? {};
11654
- const span = startSpan({
11655
- name: "anthropic.beta.messages.toolRunner",
11656
- spanAttributes: {
11657
- type: "task" /* TASK */
11658
- }
11659
- });
11825
+ const span = startSpan(
11826
+ withSpanInstrumentationName(
11827
+ {
11828
+ name: "anthropic.beta.messages.toolRunner",
11829
+ spanAttributes: {
11830
+ type: "task" /* TASK */
11831
+ }
11832
+ },
11833
+ INSTRUMENTATION_NAMES.ANTHROPIC
11834
+ )
11835
+ );
11660
11836
  span.log({
11661
11837
  input: processAttachmentsInInput(
11662
11838
  coalesceInput(params.messages ?? [], params.system)
@@ -11797,19 +11973,22 @@ function wrapAnthropicToolRunnerTool(tool, index, state) {
11797
11973
  return finalizeError(error);
11798
11974
  }
11799
11975
  },
11800
- {
11801
- event: {
11802
- input: getAnthropicToolRunnerInput(args),
11803
- metadata: {
11804
- "gen_ai.tool.name": toolName,
11805
- provider: "anthropic"
11976
+ withSpanInstrumentationName(
11977
+ {
11978
+ event: {
11979
+ input: getAnthropicToolRunnerInput(args),
11980
+ metadata: {
11981
+ "gen_ai.tool.name": toolName,
11982
+ provider: "anthropic"
11983
+ }
11984
+ },
11985
+ name: `tool: ${toolName}`,
11986
+ spanAttributes: {
11987
+ type: "tool" /* TOOL */
11806
11988
  }
11807
11989
  },
11808
- name: `tool: ${toolName}`,
11809
- spanAttributes: {
11810
- type: "tool" /* TOOL */
11811
- }
11812
- }
11990
+ INSTRUMENTATION_NAMES.ANTHROPIC
11991
+ )
11813
11992
  );
11814
11993
  },
11815
11994
  writable: runDescriptor?.writable ?? true
@@ -12404,57 +12583,321 @@ function currentWorkflowAgentWrapperSpan() {
12404
12583
  return void 0;
12405
12584
  }
12406
12585
 
12407
- // src/wrappers/ai-sdk/telemetry.ts
12408
- function braintrustAISDKTelemetry() {
12409
- const operations = /* @__PURE__ */ new Map();
12410
- const operationKeysByCallId = /* @__PURE__ */ new Map();
12411
- const workflowOperationKeyStore = isomorph_default.newAsyncLocalStorage();
12412
- const modelSpans = /* @__PURE__ */ new Map();
12413
- const objectSpans = /* @__PURE__ */ new Map();
12414
- const embedSpans = /* @__PURE__ */ new Map();
12415
- const rerankSpans = /* @__PURE__ */ new Map();
12416
- const toolSpans = /* @__PURE__ */ new Map();
12417
- let workflowAgentOperationCounter = 0;
12418
- const runSafely = (name, callback) => {
12419
- try {
12420
- callback();
12421
- } catch (error) {
12422
- console.error(`Error in Braintrust AI SDK telemetry ${name}:`, error);
12423
- }
12424
- };
12425
- const startChildSpan = (operationKey, name, type, event) => {
12426
- const parent = operations.get(operationKey)?.span;
12427
- const spanArgs = {
12428
- name,
12429
- spanAttributes: { type },
12430
- ...event ? { event } : {}
12431
- };
12432
- const span = parent ? parent.startSpan(spanArgs) : startSpan(spanArgs);
12433
- const state = operations.get(operationKey);
12434
- if (state && type === "llm" /* LLM */) {
12435
- state.hadModelChild = true;
12436
- }
12437
- return span;
12438
- };
12439
- const registerOperation = (state) => {
12440
- operations.set(state.operationKey, state);
12441
- const keys = operationKeysByCallId.get(state.callId) ?? [];
12442
- keys.push(state.operationKey);
12443
- operationKeysByCallId.set(state.callId, keys);
12586
+ // src/wrappers/ai-sdk/harness-agent-context.ts
12587
+ var BRAINTRUST_TURN_CONTEXT_KEY = "__braintrust_trace_context";
12588
+ var sessionTurnParents = /* @__PURE__ */ new WeakMap();
12589
+ var wrapperTurnParents = /* @__PURE__ */ new WeakMap();
12590
+ var patchedLifecycleMethods = /* @__PURE__ */ new WeakMap();
12591
+ var harnessTurnParentStore;
12592
+ function serializedTurnContext(value) {
12593
+ if (!isObject(value)) {
12594
+ return void 0;
12595
+ }
12596
+ const context = value[BRAINTRUST_TURN_CONTEXT_KEY];
12597
+ if (!isObject(context) || typeof context.parent !== "string" || typeof context.sessionId !== "string" || typeof context.signature !== "string") {
12598
+ return void 0;
12599
+ }
12600
+ const expectedSignature = signTurnContext({
12601
+ parent: context.parent,
12602
+ sessionId: context.sessionId
12603
+ });
12604
+ if (!expectedSignature || !isomorph_default.timingSafeEqual?.(context.signature, expectedSignature)) {
12605
+ return void 0;
12606
+ }
12607
+ const parent = SpanComponentsV4.fromStr(context.parent);
12608
+ if (!parent.data.row_id || !parent.data.root_span_id || !parent.data.span_id) {
12609
+ return void 0;
12610
+ }
12611
+ return {
12612
+ parent: context.parent,
12613
+ sessionId: context.sessionId
12444
12614
  };
12445
- const deleteOperation = (operationKey) => {
12446
- const state = operations.get(operationKey);
12447
- if (!state) {
12448
- return;
12449
- }
12450
- operations.delete(operationKey);
12451
- if (workflowOperationKeyStore.getStore() === operationKey) {
12452
- workflowOperationKeyStore.enterWith(void 0);
12453
- }
12454
- const keys = operationKeysByCallId.get(state.callId);
12455
- if (!keys) {
12456
- return;
12457
- }
12615
+ }
12616
+ function signTurnContext(context) {
12617
+ const secret = _internalGetGlobalState()._internalGetTraceContextSigningSecret();
12618
+ return secret ? isomorph_default.hmacSha256?.(
12619
+ secret,
12620
+ JSON.stringify([BRAINTRUST_TURN_CONTEXT_KEY, context])
12621
+ ) : void 0;
12622
+ }
12623
+ function continuationParentFromCreateSessionParams(params) {
12624
+ if (!isObject(params)) {
12625
+ return void 0;
12626
+ }
12627
+ const continuation = params.continueFrom ?? (isObject(params.resumeFrom) ? params.resumeFrom.continueFrom : void 0);
12628
+ const context = serializedTurnContext(continuation);
12629
+ if (!context) {
12630
+ return void 0;
12631
+ }
12632
+ if (params.sessionId !== context.sessionId) {
12633
+ return void 0;
12634
+ }
12635
+ return context.parent;
12636
+ }
12637
+ function exportSpanSynchronously(span) {
12638
+ const parentInfo = span.getParentInfo();
12639
+ if (!parentInfo) {
12640
+ return void 0;
12641
+ }
12642
+ const objectId = parentInfo.objectId.getSync().value;
12643
+ if (!objectId && !parentInfo.computeObjectMetadataArgs) {
12644
+ return void 0;
12645
+ }
12646
+ return new SpanComponentsV4({
12647
+ object_type: parentInfo.objectType,
12648
+ ...objectId ? { object_id: objectId } : {
12649
+ compute_object_metadata_args: parentInfo.computeObjectMetadataArgs ?? {}
12650
+ },
12651
+ row_id: span.id,
12652
+ root_span_id: span.rootSpanId,
12653
+ span_id: span.spanId
12654
+ }).toStr();
12655
+ }
12656
+ function exportedParent(parent) {
12657
+ return typeof parent === "string" ? parent : exportSpanSynchronously(parent);
12658
+ }
12659
+ function addSerializedContext(args) {
12660
+ if (!isObject(args.continuation) || args.sessionId === void 0) {
12661
+ return;
12662
+ }
12663
+ const parent = exportedParent(args.parent);
12664
+ if (!parent) {
12665
+ return;
12666
+ }
12667
+ const context = {
12668
+ parent,
12669
+ sessionId: args.sessionId
12670
+ };
12671
+ const signature = signTurnContext(context);
12672
+ if (!signature) {
12673
+ return;
12674
+ }
12675
+ Object.defineProperty(args.continuation, BRAINTRUST_TURN_CONTEXT_KEY, {
12676
+ configurable: true,
12677
+ enumerable: true,
12678
+ value: {
12679
+ ...context,
12680
+ signature
12681
+ },
12682
+ writable: true
12683
+ });
12684
+ }
12685
+ function lifecycleMethodDescriptor(session, method) {
12686
+ let owner = session;
12687
+ while (owner) {
12688
+ const descriptor = Object.getOwnPropertyDescriptor(owner, method);
12689
+ if (descriptor) {
12690
+ return { descriptor, owner };
12691
+ }
12692
+ owner = Object.getPrototypeOf(owner);
12693
+ }
12694
+ return void 0;
12695
+ }
12696
+ function patchLifecycleMethod(session, method) {
12697
+ let resolvedDescriptor;
12698
+ try {
12699
+ resolvedDescriptor = lifecycleMethodDescriptor(session, method);
12700
+ } catch {
12701
+ return;
12702
+ }
12703
+ if (!resolvedDescriptor || !("value" in resolvedDescriptor.descriptor) || typeof resolvedDescriptor.descriptor.value !== "function") {
12704
+ return;
12705
+ }
12706
+ const { descriptor, owner } = resolvedDescriptor;
12707
+ const patched = patchedLifecycleMethods.get(owner);
12708
+ if (patched?.has(method)) {
12709
+ return;
12710
+ }
12711
+ const original = descriptor.value;
12712
+ const replacement = function(...args) {
12713
+ const result = Reflect.apply(original, this, args);
12714
+ const addContext = (state) => {
12715
+ try {
12716
+ const parent = sessionTurnParents.get(this);
12717
+ if (!parent) {
12718
+ return;
12719
+ }
12720
+ const continuation = method === "suspendTurn" ? state : isObject(state) ? state.continueFrom : void 0;
12721
+ addSerializedContext({
12722
+ continuation,
12723
+ parent,
12724
+ sessionId: typeof this.sessionId === "string" ? this.sessionId : void 0
12725
+ });
12726
+ } catch {
12727
+ }
12728
+ };
12729
+ try {
12730
+ if (isObject(result) && typeof result.then === "function") {
12731
+ void Promise.resolve(result).then(addContext, () => {
12732
+ });
12733
+ } else {
12734
+ addContext(result);
12735
+ }
12736
+ } catch {
12737
+ }
12738
+ return result;
12739
+ };
12740
+ try {
12741
+ Object.defineProperty(owner, method, {
12742
+ ...descriptor,
12743
+ value: replacement
12744
+ });
12745
+ const ownerMethods = patched ?? /* @__PURE__ */ new Set();
12746
+ ownerMethods.add(method);
12747
+ if (!patched) {
12748
+ patchedLifecycleMethods.set(owner, ownerMethods);
12749
+ }
12750
+ } catch {
12751
+ }
12752
+ }
12753
+ function patchLifecycleMethods(session) {
12754
+ patchLifecycleMethod(session, "suspendTurn");
12755
+ patchLifecycleMethod(session, "detach");
12756
+ patchLifecycleMethod(session, "stop");
12757
+ }
12758
+ function registerHarnessTurnSpan(args) {
12759
+ if (!isObject(args.session)) {
12760
+ return;
12761
+ }
12762
+ const session = args.session;
12763
+ sessionTurnParents.set(session, args.span);
12764
+ wrapperTurnParents.set(args.span, args.span);
12765
+ patchLifecycleMethods(session);
12766
+ }
12767
+ function harnessContinuationParent(session) {
12768
+ return isObject(session) ? sessionTurnParents.get(session) : void 0;
12769
+ }
12770
+ function captureHarnessCreateSessionParent(params) {
12771
+ try {
12772
+ return continuationParentFromCreateSessionParams(params);
12773
+ } catch {
12774
+ return void 0;
12775
+ }
12776
+ }
12777
+ function registerHarnessSessionParent(session, parent) {
12778
+ if (!parent || !isObject(session)) {
12779
+ return;
12780
+ }
12781
+ const harnessSession = session;
12782
+ sessionTurnParents.set(harnessSession, parent);
12783
+ patchLifecycleMethods(harnessSession);
12784
+ }
12785
+ function currentHarnessTurnParent() {
12786
+ return harnessTurnParentStore?.getStore() ?? wrapperTurnParents.get(currentSpan());
12787
+ }
12788
+ function bindHarnessTurnParentToStart(tracingChannel, parentFromEvent) {
12789
+ const startChannel = tracingChannel.start;
12790
+ if (!startChannel) {
12791
+ return () => {
12792
+ };
12793
+ }
12794
+ harnessTurnParentStore ??= isomorph_default.newAsyncLocalStorage();
12795
+ const store = harnessTurnParentStore;
12796
+ startChannel.bindStore(
12797
+ store,
12798
+ (event) => parentFromEvent(event) ?? store.getStore()
12799
+ );
12800
+ return () => {
12801
+ startChannel.unbindStore(store);
12802
+ };
12803
+ }
12804
+ function startHarnessTurnChildSpan(parent, args) {
12805
+ const spanArgs = withSpanInstrumentationName(
12806
+ args,
12807
+ INSTRUMENTATION_NAMES.AI_SDK
12808
+ );
12809
+ return typeof parent === "string" ? startSpan({ ...spanArgs, parent }) : parent.startSpan(spanArgs);
12810
+ }
12811
+ function updateHarnessTurn(parent, update = {}) {
12812
+ if (!parent) {
12813
+ return;
12814
+ }
12815
+ const log = (event) => {
12816
+ if (typeof parent === "string") {
12817
+ updateSpan({ exported: parent, ...event });
12818
+ } else {
12819
+ parent.log(event);
12820
+ }
12821
+ };
12822
+ try {
12823
+ if (Object.prototype.hasOwnProperty.call(update, "output")) {
12824
+ log({ output: null });
12825
+ }
12826
+ log(update);
12827
+ } catch {
12828
+ }
12829
+ }
12830
+ function endHarnessTurn(parent) {
12831
+ const endTime = getCurrentUnixTimestamp();
12832
+ if (!parent) {
12833
+ return endTime;
12834
+ }
12835
+ try {
12836
+ const event = { metrics: { end: endTime } };
12837
+ if (typeof parent === "string") {
12838
+ updateSpan({ exported: parent, ...event });
12839
+ } else {
12840
+ parent.log(event);
12841
+ }
12842
+ } catch {
12843
+ }
12844
+ return endTime;
12845
+ }
12846
+
12847
+ // src/wrappers/ai-sdk/telemetry.ts
12848
+ function braintrustAISDKTelemetry() {
12849
+ const operations = /* @__PURE__ */ new Map();
12850
+ const operationKeysByCallId = /* @__PURE__ */ new Map();
12851
+ const workflowOperationKeyStore = isomorph_default.newAsyncLocalStorage();
12852
+ const modelSpans = /* @__PURE__ */ new Map();
12853
+ const objectSpans = /* @__PURE__ */ new Map();
12854
+ const embedSpans = /* @__PURE__ */ new Map();
12855
+ const rerankSpans = /* @__PURE__ */ new Map();
12856
+ const toolSpans = /* @__PURE__ */ new Map();
12857
+ let workflowAgentOperationCounter = 0;
12858
+ const runSafely = (name, callback) => {
12859
+ try {
12860
+ callback();
12861
+ } catch (error) {
12862
+ console.error(`Error in Braintrust AI SDK telemetry ${name}:`, error);
12863
+ }
12864
+ };
12865
+ const startChildSpan = (operationKey, name, type, event, parentOverride) => {
12866
+ const parent = operations.get(operationKey)?.span;
12867
+ const spanArgs = withSpanInstrumentationName(
12868
+ {
12869
+ name,
12870
+ spanAttributes: { type },
12871
+ ...event ? { event } : {}
12872
+ },
12873
+ INSTRUMENTATION_NAMES.AI_SDK
12874
+ );
12875
+ const span = parentOverride ? startHarnessTurnChildSpan(parentOverride, spanArgs) : parent ? parent.startSpan(spanArgs) : startSpan(spanArgs);
12876
+ const state = operations.get(operationKey);
12877
+ if (state && type === "llm" /* LLM */) {
12878
+ state.hadModelChild = true;
12879
+ }
12880
+ return span;
12881
+ };
12882
+ const registerOperation = (state) => {
12883
+ operations.set(state.operationKey, state);
12884
+ const keys = operationKeysByCallId.get(state.callId) ?? [];
12885
+ keys.push(state.operationKey);
12886
+ operationKeysByCallId.set(state.callId, keys);
12887
+ };
12888
+ const deleteOperation = (operationKey) => {
12889
+ const state = operations.get(operationKey);
12890
+ if (!state) {
12891
+ return;
12892
+ }
12893
+ operations.delete(operationKey);
12894
+ if (workflowOperationKeyStore.getStore() === operationKey) {
12895
+ workflowOperationKeyStore.enterWith(void 0);
12896
+ }
12897
+ const keys = operationKeysByCallId.get(state.callId);
12898
+ if (!keys) {
12899
+ return;
12900
+ }
12458
12901
  const index = keys.indexOf(operationKey);
12459
12902
  if (index >= 0) {
12460
12903
  keys.splice(index, 1);
@@ -12709,14 +13152,30 @@ function braintrustAISDKTelemetry() {
12709
13152
  const workflowAgent = operationName === "WorkflowAgent.stream";
12710
13153
  const wrapperSpan = workflowAgent ? currentWorkflowAgentWrapperSpan() : void 0;
12711
13154
  const ownsSpan = !wrapperSpan;
12712
- const span = ownsSpan ? startSpan({
12713
- name: operationName,
12714
- spanAttributes: { type: "function" /* FUNCTION */ }
12715
- }) : wrapperSpan;
13155
+ const harnessTurnParent = currentHarnessTurnParent();
13156
+ const span = ownsSpan ? harnessTurnParent ? startHarnessTurnChildSpan(
13157
+ harnessTurnParent,
13158
+ withSpanInstrumentationName(
13159
+ {
13160
+ name: operationName,
13161
+ spanAttributes: { type: "function" /* FUNCTION */ }
13162
+ },
13163
+ INSTRUMENTATION_NAMES.AI_SDK
13164
+ )
13165
+ ) : startSpan(
13166
+ withSpanInstrumentationName(
13167
+ {
13168
+ name: operationName,
13169
+ spanAttributes: { type: "function" /* FUNCTION */ }
13170
+ },
13171
+ INSTRUMENTATION_NAMES.AI_SDK
13172
+ )
13173
+ ) : wrapperSpan;
12716
13174
  const operationKey = createOperationKey(event, operationName);
12717
13175
  registerOperation({
12718
13176
  callId: event.callId,
12719
13177
  hadModelChild: false,
13178
+ harnessTurnParent,
12720
13179
  loggedInput: false,
12721
13180
  operationName,
12722
13181
  operationKey,
@@ -12957,7 +13416,8 @@ function braintrustAISDKTelemetry() {
12957
13416
  toolCallId,
12958
13417
  ...typeof event.toolCall.toolName === "string" ? { toolName: event.toolCall.toolName } : {}
12959
13418
  }
12960
- }
13419
+ },
13420
+ state?.harnessTurnParent
12961
13421
  );
12962
13422
  toolSpans.set(toolCallId, { operationKey, span });
12963
13423
  });
@@ -13193,92 +13653,102 @@ function finishOutput(result, operationName) {
13193
13653
  }
13194
13654
 
13195
13655
  // src/instrumentation/plugins/ai-sdk-channels.ts
13196
- var aiSDKChannels = defineChannels("ai", {
13197
- generateText: channel({
13198
- channelName: "generateText",
13199
- kind: "async"
13200
- }),
13201
- streamText: channel({
13202
- channelName: "streamText",
13203
- kind: "async"
13204
- }),
13205
- streamTextSync: channel({
13206
- channelName: "streamText.sync",
13207
- kind: "sync-stream"
13208
- }),
13209
- generateObject: channel({
13210
- channelName: "generateObject",
13211
- kind: "async"
13212
- }),
13213
- streamObject: channel({
13214
- channelName: "streamObject",
13215
- kind: "async"
13216
- }),
13217
- streamObjectSync: channel({
13218
- channelName: "streamObject.sync",
13219
- kind: "sync-stream"
13220
- }),
13221
- embed: channel(
13222
- {
13656
+ var aiSDKChannels = defineChannels(
13657
+ "ai",
13658
+ {
13659
+ generateText: channel({
13660
+ channelName: "generateText",
13661
+ kind: "async"
13662
+ }),
13663
+ streamText: channel({
13664
+ channelName: "streamText",
13665
+ kind: "async"
13666
+ }),
13667
+ streamTextSync: channel({
13668
+ channelName: "streamText.sync",
13669
+ kind: "sync-stream"
13670
+ }),
13671
+ generateObject: channel({
13672
+ channelName: "generateObject",
13673
+ kind: "async"
13674
+ }),
13675
+ streamObject: channel({
13676
+ channelName: "streamObject",
13677
+ kind: "async"
13678
+ }),
13679
+ streamObjectSync: channel({
13680
+ channelName: "streamObject.sync",
13681
+ kind: "sync-stream"
13682
+ }),
13683
+ embed: channel({
13223
13684
  channelName: "embed",
13224
13685
  kind: "async"
13225
- }
13226
- ),
13227
- embedMany: channel({
13228
- channelName: "embedMany",
13229
- kind: "async"
13230
- }),
13231
- rerank: channel({
13232
- channelName: "rerank",
13233
- kind: "async"
13234
- }),
13235
- agentGenerate: channel({
13236
- channelName: "Agent.generate",
13237
- kind: "async"
13238
- }),
13239
- agentStream: channel({
13240
- channelName: "Agent.stream",
13241
- kind: "async"
13242
- }),
13243
- agentStreamSync: channel({
13244
- channelName: "Agent.stream.sync",
13245
- kind: "sync-stream"
13246
- }),
13247
- toolLoopAgentGenerate: channel({
13248
- channelName: "ToolLoopAgent.generate",
13249
- kind: "async"
13250
- }),
13251
- toolLoopAgentStream: channel({
13252
- channelName: "ToolLoopAgent.stream",
13253
- kind: "async"
13254
- }),
13255
- workflowAgentStream: channel({
13256
- channelName: "WorkflowAgent.stream",
13257
- kind: "async"
13258
- }),
13259
- v7CreateTelemetryDispatcher: channel({
13260
- channelName: "createTelemetryDispatcher",
13261
- kind: "sync-stream"
13262
- })
13263
- });
13264
- var harnessAgentChannels = defineChannels("@ai-sdk/harness", {
13265
- generate: channel({
13266
- channelName: "HarnessAgent.generate",
13267
- kind: "async"
13268
- }),
13269
- stream: channel({
13270
- channelName: "HarnessAgent.stream",
13271
- kind: "async"
13272
- }),
13273
- continueGenerate: channel({
13274
- channelName: "HarnessAgent.continueGenerate",
13275
- kind: "async"
13276
- }),
13277
- continueStream: channel({
13278
- channelName: "HarnessAgent.continueStream",
13279
- kind: "async"
13280
- })
13281
- });
13686
+ }),
13687
+ embedMany: channel({
13688
+ channelName: "embedMany",
13689
+ kind: "async"
13690
+ }),
13691
+ rerank: channel({
13692
+ channelName: "rerank",
13693
+ kind: "async"
13694
+ }),
13695
+ agentGenerate: channel({
13696
+ channelName: "Agent.generate",
13697
+ kind: "async"
13698
+ }),
13699
+ agentStream: channel({
13700
+ channelName: "Agent.stream",
13701
+ kind: "async"
13702
+ }),
13703
+ agentStreamSync: channel({
13704
+ channelName: "Agent.stream.sync",
13705
+ kind: "sync-stream"
13706
+ }),
13707
+ toolLoopAgentGenerate: channel({
13708
+ channelName: "ToolLoopAgent.generate",
13709
+ kind: "async"
13710
+ }),
13711
+ toolLoopAgentStream: channel({
13712
+ channelName: "ToolLoopAgent.stream",
13713
+ kind: "async"
13714
+ }),
13715
+ workflowAgentStream: channel({
13716
+ channelName: "WorkflowAgent.stream",
13717
+ kind: "async"
13718
+ }),
13719
+ v7CreateTelemetryDispatcher: channel({
13720
+ channelName: "createTelemetryDispatcher",
13721
+ kind: "sync-stream"
13722
+ })
13723
+ },
13724
+ { instrumentationName: INSTRUMENTATION_NAMES.AI_SDK }
13725
+ );
13726
+ var harnessAgentChannels = defineChannels(
13727
+ "@ai-sdk/harness",
13728
+ {
13729
+ createSession: channel({
13730
+ channelName: "HarnessAgent.createSession",
13731
+ kind: "async"
13732
+ }),
13733
+ generate: channel({
13734
+ channelName: "HarnessAgent.generate",
13735
+ kind: "async"
13736
+ }),
13737
+ stream: channel({
13738
+ channelName: "HarnessAgent.stream",
13739
+ kind: "async"
13740
+ }),
13741
+ continueGenerate: channel({
13742
+ channelName: "HarnessAgent.continueGenerate",
13743
+ kind: "async"
13744
+ }),
13745
+ continueStream: channel({
13746
+ channelName: "HarnessAgent.continueStream",
13747
+ kind: "async"
13748
+ })
13749
+ },
13750
+ { instrumentationName: INSTRUMENTATION_NAMES.AI_SDK }
13751
+ );
13282
13752
 
13283
13753
  // src/instrumentation/plugins/ai-sdk-plugin.ts
13284
13754
  var DEFAULT_DENY_OUTPUT_PATHS = [
@@ -13355,6 +13825,17 @@ var AISDKPlugin = class extends BasePlugin {
13355
13825
  subscribeToAISDK() {
13356
13826
  const denyOutputPaths = this.config.denyOutputPaths || DEFAULT_DENY_OUTPUT_PATHS;
13357
13827
  this.unsubscribers.push(subscribeToAISDKV7TelemetryDispatcher());
13828
+ this.unsubscribers.push(subscribeToHarnessAgentCreateSession());
13829
+ this.unsubscribers.push(
13830
+ subscribeToHarnessContinuation(
13831
+ harnessAgentChannels.continueGenerate,
13832
+ denyOutputPaths
13833
+ ),
13834
+ subscribeToHarnessContinuation(
13835
+ harnessAgentChannels.continueStream,
13836
+ denyOutputPaths
13837
+ )
13838
+ );
13358
13839
  this.unsubscribers.push(
13359
13840
  traceStreamingChannel(aiSDKChannels.generateText, {
13360
13841
  name: "generateText",
@@ -13550,8 +14031,9 @@ var AISDKPlugin = class extends BasePlugin {
13550
14031
  this.unsubscribers.push(
13551
14032
  traceStreamingChannel(harnessAgentChannels.generate, {
13552
14033
  name: "HarnessAgent.generate",
14034
+ startSpan: _internalStartSpanWithInitialMerge,
13553
14035
  type: "task" /* TASK */,
13554
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
14036
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
13555
14037
  extractOutput: (result, endEvent) => processAISDKOutput(
13556
14038
  result,
13557
14039
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -13563,8 +14045,9 @@ var AISDKPlugin = class extends BasePlugin {
13563
14045
  this.unsubscribers.push(
13564
14046
  traceStreamingChannel(harnessAgentChannels.stream, {
13565
14047
  name: "HarnessAgent.stream",
14048
+ startSpan: _internalStartSpanWithInitialMerge,
13566
14049
  type: "task" /* TASK */,
13567
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
14050
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
13568
14051
  extractOutput: (result, endEvent) => processAISDKOutput(
13569
14052
  result,
13570
14053
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -13589,8 +14072,10 @@ var AISDKPlugin = class extends BasePlugin {
13589
14072
  this.unsubscribers.push(
13590
14073
  traceStreamingChannel(harnessAgentChannels.continueGenerate, {
13591
14074
  name: "HarnessAgent.continueGenerate",
14075
+ shouldTrace: (args) => !harnessContinuationParent(harnessSessionFromArguments(args)),
14076
+ startSpan: _internalStartSpanWithInitialMerge,
13592
14077
  type: "task" /* TASK */,
13593
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
14078
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
13594
14079
  extractOutput: (result, endEvent) => processAISDKOutput(
13595
14080
  result,
13596
14081
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -13602,8 +14087,10 @@ var AISDKPlugin = class extends BasePlugin {
13602
14087
  this.unsubscribers.push(
13603
14088
  traceStreamingChannel(harnessAgentChannels.continueStream, {
13604
14089
  name: "HarnessAgent.continueStream",
14090
+ shouldTrace: (args) => !harnessContinuationParent(harnessSessionFromArguments(args)),
14091
+ startSpan: _internalStartSpanWithInitialMerge,
13605
14092
  type: "task" /* TASK */,
13606
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
14093
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
13607
14094
  extractOutput: (result, endEvent) => processAISDKOutput(
13608
14095
  result,
13609
14096
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -13695,6 +14182,8 @@ var AISDKPlugin = class extends BasePlugin {
13695
14182
  defaultDenyOutputPaths: denyOutputPaths,
13696
14183
  endEvent,
13697
14184
  onComplete: () => unregisterWorkflowAgentWrapperSpan(span),
14185
+ onCancel: () => unregisterWorkflowAgentWrapperSpan(span),
14186
+ onError: () => unregisterWorkflowAgentWrapperSpan(span),
13698
14187
  result,
13699
14188
  span,
13700
14189
  startTime
@@ -13703,6 +14192,153 @@ var AISDKPlugin = class extends BasePlugin {
13703
14192
  );
13704
14193
  }
13705
14194
  };
14195
+ function subscribeToHarnessAgentCreateSession() {
14196
+ const channel2 = harnessAgentChannels.createSession.tracingChannel();
14197
+ const parents = /* @__PURE__ */ new WeakMap();
14198
+ const handlers = {
14199
+ start: (event) => {
14200
+ const parent = captureHarnessCreateSessionParent(event.arguments?.[0]);
14201
+ if (parent) {
14202
+ parents.set(event, parent);
14203
+ }
14204
+ },
14205
+ asyncEnd: (event) => {
14206
+ registerHarnessSessionParent(event.result, parents.get(event));
14207
+ parents.delete(event);
14208
+ },
14209
+ error: (event) => {
14210
+ parents.delete(event);
14211
+ }
14212
+ };
14213
+ channel2.subscribe(handlers);
14214
+ return () => channel2.unsubscribe(handlers);
14215
+ }
14216
+ function harnessContinuationParentFromEvent(event) {
14217
+ try {
14218
+ return harnessContinuationParent(event.arguments?.[0]?.session);
14219
+ } catch {
14220
+ return void 0;
14221
+ }
14222
+ }
14223
+ function subscribeToHarnessContinuation(continuationChannel, defaultDenyOutputPaths) {
14224
+ const channel2 = continuationChannel.tracingChannel();
14225
+ const parents = /* @__PURE__ */ new WeakMap();
14226
+ const startTimes = /* @__PURE__ */ new WeakMap();
14227
+ const unbindParentStore = bindHarnessTurnParentToStart(
14228
+ channel2,
14229
+ harnessContinuationParentFromEvent
14230
+ );
14231
+ const handlers = {
14232
+ start: (event) => {
14233
+ const parent = harnessContinuationParentFromEvent(event);
14234
+ if (!parent) {
14235
+ return;
14236
+ }
14237
+ parents.set(event, parent);
14238
+ startTimes.set(event, getCurrentUnixTimestamp());
14239
+ try {
14240
+ const params = event.arguments?.[0];
14241
+ if (params) {
14242
+ prepareAISDKHarnessAgentInput(params, event.self);
14243
+ }
14244
+ } catch (error) {
14245
+ debugLogger.error(
14246
+ "Error preparing Harness continuation telemetry:",
14247
+ error
14248
+ );
14249
+ }
14250
+ },
14251
+ asyncEnd: (event) => {
14252
+ const parent = parents.get(event);
14253
+ const startTime = startTimes.get(event) ?? getCurrentUnixTimestamp();
14254
+ parents.delete(event);
14255
+ startTimes.delete(event);
14256
+ if (!parent) {
14257
+ return;
14258
+ }
14259
+ const endEvent = event;
14260
+ const span = {
14261
+ end: () => endHarnessTurn(parent),
14262
+ log: (update) => updateHarnessTurn(
14263
+ parent,
14264
+ Object.prototype.hasOwnProperty.call(update, "error") && !Object.prototype.hasOwnProperty.call(update, "output") ? { ...update, output: null } : update
14265
+ )
14266
+ };
14267
+ try {
14268
+ if (isAsyncIterable(endEvent.result)) {
14269
+ patchStreamIfNeeded(endEvent.result, {
14270
+ onComplete: (chunks) => {
14271
+ try {
14272
+ const { metadata, metrics, output } = aggregateAISDKChunks(
14273
+ chunks,
14274
+ endEvent.result,
14275
+ endEvent
14276
+ );
14277
+ span.log({
14278
+ ...metadata ? { metadata } : {},
14279
+ metrics,
14280
+ output
14281
+ });
14282
+ } catch (error) {
14283
+ debugLogger.error(
14284
+ "Error aggregating Harness continuation stream:",
14285
+ error
14286
+ );
14287
+ } finally {
14288
+ span.end();
14289
+ }
14290
+ },
14291
+ onError: (error) => {
14292
+ span.log({ error: toLoggedError(error), output: null });
14293
+ span.end();
14294
+ }
14295
+ });
14296
+ return;
14297
+ }
14298
+ if (patchAISDKStreamingResult({
14299
+ defaultDenyOutputPaths,
14300
+ endEvent,
14301
+ result: endEvent.result,
14302
+ resolvePromiseUsage: true,
14303
+ span,
14304
+ startTime
14305
+ })) {
14306
+ return;
14307
+ }
14308
+ finalizeAISDKChildTracing(endEvent);
14309
+ span.log({
14310
+ metrics: extractTokenMetrics(endEvent.result),
14311
+ output: processAISDKOutput(
14312
+ endEvent.result,
14313
+ resolveDenyOutputPaths(endEvent, defaultDenyOutputPaths)
14314
+ )
14315
+ });
14316
+ span.end();
14317
+ } catch (error) {
14318
+ debugLogger.error("Error tracing Harness continuation:", error);
14319
+ span.end();
14320
+ }
14321
+ },
14322
+ error: (event) => {
14323
+ const parent = parents.get(event);
14324
+ parents.delete(event);
14325
+ startTimes.delete(event);
14326
+ if (!parent) {
14327
+ return;
14328
+ }
14329
+ updateHarnessTurn(parent, {
14330
+ error: toLoggedError(event.error),
14331
+ output: null
14332
+ });
14333
+ endHarnessTurn(parent);
14334
+ }
14335
+ };
14336
+ channel2.subscribe(handlers);
14337
+ return () => {
14338
+ unbindParentStore();
14339
+ channel2.unsubscribe(handlers);
14340
+ };
14341
+ }
13706
14342
  function subscribeToAISDKV7TelemetryDispatcher() {
13707
14343
  const channel2 = aiSDKChannels.v7CreateTelemetryDispatcher.tracingChannel();
13708
14344
  const telemetry = braintrustAISDKTelemetry();
@@ -14155,7 +14791,13 @@ function prepareAISDKCallInput(params, event, span, defaultDenyOutputPaths, chil
14155
14791
  metadata
14156
14792
  };
14157
14793
  }
14158
- function prepareAISDKHarnessAgentInput(params, self) {
14794
+ function prepareAISDKHarnessAgentInput(params, self, span) {
14795
+ if (span) {
14796
+ registerHarnessTurnSpan({
14797
+ session: params.session,
14798
+ span
14799
+ });
14800
+ }
14159
14801
  if (isObject(self)) {
14160
14802
  try {
14161
14803
  if (isObject(self.settings)) {
@@ -14194,6 +14836,10 @@ function prepareAISDKHarnessAgentInput(params, self) {
14194
14836
  metadata
14195
14837
  };
14196
14838
  }
14839
+ function harnessSessionFromArguments(args) {
14840
+ const params = args[0];
14841
+ return isObject(params) ? params.session : void 0;
14842
+ }
14197
14843
  function prepareAISDKWorkflowAgentStreamInput(params, event, span, defaultDenyOutputPaths) {
14198
14844
  registerWorkflowAgentWrapperSpan(span);
14199
14845
  const { input } = processAISDKWorkflowAgentCallInput(params);
@@ -14641,19 +15287,22 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
14641
15287
  activeEntry.openSpans.delete(span);
14642
15288
  }
14643
15289
  },
14644
- {
14645
- name: "doGenerate",
14646
- spanAttributes: {
14647
- type: "llm" /* LLM */
14648
- },
14649
- event: buildAISDKModelStartEvent(
14650
- callOptions,
14651
- activeEntry.baseMetadata,
14652
- {
14653
- workflowAgent: activeEntry.childTracingOptions.workflowAgent
14654
- }
14655
- )
14656
- }
15290
+ withSpanInstrumentationName(
15291
+ {
15292
+ name: "doGenerate",
15293
+ spanAttributes: {
15294
+ type: "llm" /* LLM */
15295
+ },
15296
+ event: buildAISDKModelStartEvent(
15297
+ callOptions,
15298
+ activeEntry.baseMetadata,
15299
+ {
15300
+ workflowAgent: activeEntry.childTracingOptions.workflowAgent
15301
+ }
15302
+ )
15303
+ },
15304
+ INSTRUMENTATION_NAMES.AI_SDK
15305
+ )
14657
15306
  );
14658
15307
  };
14659
15308
  if (originalDoStream) {
@@ -14663,19 +15312,24 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
14663
15312
  return Reflect.apply(originalDoStream, resolvedModel, [callOptions]);
14664
15313
  }
14665
15314
  closeOpenAISDKModelPatchSpans(activeEntry);
14666
- const span = activeEntry.parentSpan.startSpan({
14667
- name: "doStream",
14668
- spanAttributes: {
14669
- type: "llm" /* LLM */
14670
- },
14671
- event: buildAISDKModelStartEvent(
14672
- callOptions,
14673
- activeEntry.baseMetadata,
15315
+ const span = activeEntry.parentSpan.startSpan(
15316
+ withSpanInstrumentationName(
14674
15317
  {
14675
- workflowAgent: activeEntry.childTracingOptions.workflowAgent
14676
- }
15318
+ name: "doStream",
15319
+ spanAttributes: {
15320
+ type: "llm" /* LLM */
15321
+ },
15322
+ event: buildAISDKModelStartEvent(
15323
+ callOptions,
15324
+ activeEntry.baseMetadata,
15325
+ {
15326
+ workflowAgent: activeEntry.childTracingOptions.workflowAgent
15327
+ }
15328
+ )
15329
+ },
15330
+ INSTRUMENTATION_NAMES.AI_SDK
14677
15331
  )
14678
- });
15332
+ );
14679
15333
  activeEntry.openSpans.add(span);
14680
15334
  const streamStartTime = getCurrentUnixTimestamp();
14681
15335
  const result = await withCurrent(
@@ -14847,12 +15501,17 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
14847
15501
  }
14848
15502
  if (isAsyncGenerator(result)) {
14849
15503
  return (async function* () {
14850
- const span = activeEntry.parentSpan.startSpan({
14851
- name: activeEntry.name,
14852
- spanAttributes: {
14853
- type: "tool" /* TOOL */
14854
- }
14855
- });
15504
+ const span = activeEntry.parentSpan.startSpan(
15505
+ withSpanInstrumentationName(
15506
+ {
15507
+ name: activeEntry.name,
15508
+ spanAttributes: {
15509
+ type: "tool" /* TOOL */
15510
+ }
15511
+ },
15512
+ INSTRUMENTATION_NAMES.AI_SDK
15513
+ )
15514
+ );
14856
15515
  span.log({ input: serializeToolExecutionInput(args) });
14857
15516
  try {
14858
15517
  let lastValue;
@@ -14876,12 +15535,15 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
14876
15535
  span.log({ output: awaitedResult });
14877
15536
  return awaitedResult;
14878
15537
  },
14879
- {
14880
- name: activeEntry.name,
14881
- spanAttributes: {
14882
- type: "tool" /* TOOL */
14883
- }
14884
- }
15538
+ withSpanInstrumentationName(
15539
+ {
15540
+ name: activeEntry.name,
15541
+ spanAttributes: {
15542
+ type: "tool" /* TOOL */
15543
+ }
15544
+ },
15545
+ INSTRUMENTATION_NAMES.AI_SDK
15546
+ )
14885
15547
  );
14886
15548
  };
14887
15549
  cleanup.push(() => {
@@ -15040,6 +15702,8 @@ function patchAISDKStreamingResult(args) {
15040
15702
  defaultDenyOutputPaths,
15041
15703
  endEvent,
15042
15704
  onComplete,
15705
+ onCancel,
15706
+ onError,
15043
15707
  result,
15044
15708
  resolvePromiseUsage,
15045
15709
  span,
@@ -15051,14 +15715,43 @@ function patchAISDKStreamingResult(args) {
15051
15715
  const resultRecord = result;
15052
15716
  attachKnownResultPromiseHandlers(resultRecord);
15053
15717
  let finalized = false;
15054
- const finalize = () => {
15718
+ const finalize = (outcome) => {
15055
15719
  if (finalized) {
15056
15720
  return;
15057
15721
  }
15058
15722
  finalized = true;
15059
- finalizeAISDKChildTracing(endEvent);
15060
- span.end();
15061
- onComplete?.();
15723
+ try {
15724
+ finalizeAISDKChildTracing(endEvent);
15725
+ } catch (error) {
15726
+ debugLogger.error("Error finalizing AI SDK child tracing:", error);
15727
+ }
15728
+ try {
15729
+ span.end();
15730
+ } catch (error) {
15731
+ debugLogger.error("Error ending AI SDK streaming span:", error);
15732
+ }
15733
+ if (outcome && "error" in outcome) {
15734
+ try {
15735
+ onError?.(outcome.error);
15736
+ } catch (error) {
15737
+ debugLogger.error("Error in AI SDK streaming error hook:", error);
15738
+ }
15739
+ } else if (outcome) {
15740
+ try {
15741
+ onComplete?.(outcome);
15742
+ } catch (error) {
15743
+ debugLogger.error("Error in AI SDK streaming completion hook:", error);
15744
+ }
15745
+ } else {
15746
+ try {
15747
+ onCancel?.();
15748
+ } catch (error) {
15749
+ debugLogger.error(
15750
+ "Error in AI SDK streaming cancellation hook:",
15751
+ error
15752
+ );
15753
+ }
15754
+ }
15062
15755
  };
15063
15756
  let outputLogged = false;
15064
15757
  const logStreamingOutput = async (firstChunkTime) => {
@@ -15092,15 +15785,29 @@ function patchAISDKStreamingResult(args) {
15092
15785
  resolveDenyOutputPaths(endEvent, defaultDenyOutputPaths)
15093
15786
  );
15094
15787
  const metadata = buildResolvedMetadataPayload(result).metadata;
15095
- span.log({
15096
- output,
15097
- ...metadata ? { metadata } : {},
15098
- metrics
15099
- });
15788
+ try {
15789
+ span.log({
15790
+ output,
15791
+ ...metadata ? { metadata } : {},
15792
+ metrics
15793
+ });
15794
+ } catch (error) {
15795
+ debugLogger.error("Error logging AI SDK streaming output:", error);
15796
+ }
15797
+ finalize({ metrics, output });
15100
15798
  } catch (error) {
15101
- span.log({ error: toLoggedError(error) });
15102
- } finally {
15103
- finalize();
15799
+ const loggedError = toLoggedError(error);
15800
+ try {
15801
+ span.log({ error: loggedError });
15802
+ } catch (loggingError) {
15803
+ debugLogger.error(
15804
+ "Error logging AI SDK streaming failure:",
15805
+ loggingError
15806
+ );
15807
+ }
15808
+ finalize({
15809
+ error: error instanceof Error ? error : new Error(String(loggedError))
15810
+ });
15104
15811
  }
15105
15812
  };
15106
15813
  const createAsyncIterableHooks = () => {
@@ -15117,11 +15824,16 @@ function patchAISDKStreamingResult(args) {
15117
15824
  onError: (error) => {
15118
15825
  if (!outputLogged) {
15119
15826
  outputLogged = true;
15120
- span.log({
15121
- error: error.message
15122
- });
15827
+ try {
15828
+ span.log({ error });
15829
+ } catch (loggingError) {
15830
+ debugLogger.error(
15831
+ "Error logging AI SDK stream failure:",
15832
+ loggingError
15833
+ );
15834
+ }
15123
15835
  }
15124
- finalize();
15836
+ finalize({ error });
15125
15837
  },
15126
15838
  onCancel: finalize
15127
15839
  };
@@ -15207,8 +15919,18 @@ function patchAISDKStreamingResult(args) {
15207
15919
  }
15208
15920
  controller.enqueue(value);
15209
15921
  } catch (error) {
15210
- span.log({ error: toLoggedError(error) });
15211
- finalize();
15922
+ const loggedError = toLoggedError(error);
15923
+ try {
15924
+ span.log({ error: loggedError });
15925
+ } catch (loggingError) {
15926
+ debugLogger.error(
15927
+ "Error logging AI SDK base stream failure:",
15928
+ loggingError
15929
+ );
15930
+ }
15931
+ finalize({
15932
+ error: error instanceof Error ? error : new Error(String(loggedError))
15933
+ });
15212
15934
  controller.error(error);
15213
15935
  }
15214
15936
  },
@@ -15997,7 +16719,8 @@ var claudeAgentSDKChannels = defineChannels(
15997
16719
  channelName: "query",
15998
16720
  kind: "sync-stream"
15999
16721
  })
16000
- }
16722
+ },
16723
+ { instrumentationName: INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK }
16001
16724
  );
16002
16725
 
16003
16726
  // src/instrumentation/plugins/claude-agent-sdk-instrumentation-constants.ts
@@ -16145,22 +16868,27 @@ function wrapLocalClaudeToolHandler(handler, getMetadata) {
16145
16868
  const spanName = metadata.serverName ? `tool: ${metadata.serverName}/${metadata.toolName}` : `tool: ${metadata.toolName}`;
16146
16869
  const runWithResolvedParent = async () => {
16147
16870
  const parent = toolUseId && localToolParentResolver ? await localToolParentResolver(toolUseId).catch(() => void 0) : void 0;
16148
- const span = startSpan({
16149
- event: {
16150
- input: handlerArgs[0],
16151
- metadata: {
16152
- "claude_agent_sdk.raw_tool_name": rawToolName,
16153
- "gen_ai.tool.name": metadata.toolName,
16154
- ...toolUseId && { "gen_ai.tool.call.id": toolUseId },
16155
- ...metadata.serverName && {
16156
- "mcp.server": metadata.serverName
16157
- }
16158
- }
16159
- },
16160
- name: spanName,
16161
- ...parent && { parent },
16162
- spanAttributes: { type: "tool" /* TOOL */ }
16163
- });
16871
+ const span = startSpan(
16872
+ withSpanInstrumentationName(
16873
+ {
16874
+ event: {
16875
+ input: handlerArgs[0],
16876
+ metadata: {
16877
+ "claude_agent_sdk.raw_tool_name": rawToolName,
16878
+ "gen_ai.tool.name": metadata.toolName,
16879
+ ...toolUseId && { "gen_ai.tool.call.id": toolUseId },
16880
+ ...metadata.serverName && {
16881
+ "mcp.server": metadata.serverName
16882
+ }
16883
+ }
16884
+ },
16885
+ name: spanName,
16886
+ ...parent && { parent },
16887
+ spanAttributes: { type: "tool" /* TOOL */ }
16888
+ },
16889
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
16890
+ )
16891
+ );
16164
16892
  const runHandler = () => Reflect.apply(handler, this, handlerArgs);
16165
16893
  const finalizeSuccess = (result) => {
16166
16894
  span.log({ output: result });
@@ -16485,14 +17213,19 @@ async function createLLMSpanForMessages(messages, promptMessages, conversationHi
16485
17213
  ).filter(
16486
17214
  (c) => c !== void 0
16487
17215
  );
16488
- const span = existingSpan ?? startSpan({
16489
- name: "anthropic.messages.create",
16490
- parent: parentSpan,
16491
- spanAttributes: {
16492
- type: "llm" /* LLM */
16493
- },
16494
- startTime
16495
- });
17216
+ const span = existingSpan ?? startSpan(
17217
+ withSpanInstrumentationName(
17218
+ {
17219
+ name: "anthropic.messages.create",
17220
+ parent: parentSpan,
17221
+ spanAttributes: {
17222
+ type: "llm" /* LLM */
17223
+ },
17224
+ startTime
17225
+ },
17226
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
17227
+ )
17228
+ );
16496
17229
  span.log({
16497
17230
  input,
16498
17231
  metadata: model ? { model } : void 0,
@@ -16595,25 +17328,30 @@ function createToolTracingHooks(resolveParentSpan, activeToolSpans, mcpServers,
16595
17328
  return {};
16596
17329
  }
16597
17330
  const parsed = parseToolName(input.tool_name);
16598
- const toolSpan = startSpan({
16599
- event: {
16600
- input: input.tool_input,
16601
- metadata: {
16602
- "claude_agent_sdk.cwd": input.cwd,
16603
- "claude_agent_sdk.raw_tool_name": parsed.rawToolName,
16604
- "claude_agent_sdk.session_id": input.session_id,
16605
- "gen_ai.tool.call.id": toolUseID,
16606
- "gen_ai.tool.name": parsed.toolName,
16607
- ...parsed.mcpServer && { "mcp.server": parsed.mcpServer },
16608
- ...getMcpServerMetadata(parsed.mcpServer, mcpServers)
16609
- }
16610
- },
16611
- name: parsed.displayName,
16612
- parent: await resolveParentSpan(toolUseID, {
16613
- agentId: input.agent_id
16614
- }),
16615
- spanAttributes: { type: "tool" /* TOOL */ }
16616
- });
17331
+ const toolSpan = startSpan(
17332
+ withSpanInstrumentationName(
17333
+ {
17334
+ event: {
17335
+ input: input.tool_input,
17336
+ metadata: {
17337
+ "claude_agent_sdk.cwd": input.cwd,
17338
+ "claude_agent_sdk.raw_tool_name": parsed.rawToolName,
17339
+ "claude_agent_sdk.session_id": input.session_id,
17340
+ "gen_ai.tool.call.id": toolUseID,
17341
+ "gen_ai.tool.name": parsed.toolName,
17342
+ ...parsed.mcpServer && { "mcp.server": parsed.mcpServer },
17343
+ ...getMcpServerMetadata(parsed.mcpServer, mcpServers)
17344
+ }
17345
+ },
17346
+ name: parsed.displayName,
17347
+ parent: await resolveParentSpan(toolUseID, {
17348
+ agentId: input.agent_id
17349
+ }),
17350
+ spanAttributes: { type: "tool" /* TOOL */ }
17351
+ },
17352
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
17353
+ )
17354
+ );
16617
17355
  activeToolSpans.set(toolUseID, toolSpan);
16618
17356
  return {};
16619
17357
  };
@@ -16979,14 +17717,19 @@ async function ensureSubAgentSpan(subAgentDetailsByToolUseId, rootSpan, activeTo
16979
17717
  const spanName = formatSubAgentSpanName(details);
16980
17718
  const parentToolSpan = activeToolSpans.get(parentToolUseId);
16981
17719
  const parentSpan = parentToolSpan ? await parentToolSpan.export() : await rootSpan.export();
16982
- const subAgentSpan = startSpan({
16983
- event: {
16984
- metadata: subAgentDetailsToMetadata(details)
16985
- },
16986
- name: spanName,
16987
- parent: parentSpan,
16988
- spanAttributes: { type: "task" /* TASK */ }
16989
- });
17720
+ const subAgentSpan = startSpan(
17721
+ withSpanInstrumentationName(
17722
+ {
17723
+ event: {
17724
+ metadata: subAgentDetailsToMetadata(details)
17725
+ },
17726
+ name: spanName,
17727
+ parent: parentSpan,
17728
+ spanAttributes: { type: "task" /* TASK */ }
17729
+ },
17730
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
17731
+ )
17732
+ );
16990
17733
  subAgentSpans.set(parentToolUseId, subAgentSpan);
16991
17734
  return subAgentSpan;
16992
17735
  }
@@ -17007,14 +17750,19 @@ async function ensureActiveLlmSpanForParentToolUse(rootSpan, activeLlmSpansByPar
17007
17750
  );
17008
17751
  llmParentSpan = await subAgentSpan.export();
17009
17752
  }
17010
- const llmSpan = startSpan({
17011
- name: "anthropic.messages.create",
17012
- parent: llmParentSpan,
17013
- spanAttributes: {
17014
- type: "llm" /* LLM */
17015
- },
17016
- startTime
17017
- });
17753
+ const llmSpan = startSpan(
17754
+ withSpanInstrumentationName(
17755
+ {
17756
+ name: "anthropic.messages.create",
17757
+ parent: llmParentSpan,
17758
+ spanAttributes: {
17759
+ type: "llm" /* LLM */
17760
+ },
17761
+ startTime
17762
+ },
17763
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
17764
+ )
17765
+ );
17018
17766
  activeLlmSpansByParentToolUse.set(parentKey, llmSpan);
17019
17767
  return llmSpan;
17020
17768
  }
@@ -17283,12 +18031,17 @@ var ClaudeAgentSDKPlugin = class extends BasePlugin {
17283
18031
  }
17284
18032
  })();
17285
18033
  }
17286
- const span = startSpan({
17287
- name: "Claude Agent",
17288
- spanAttributes: {
17289
- type: "task" /* TASK */
17290
- }
17291
- });
18034
+ const span = startSpan(
18035
+ withSpanInstrumentationName(
18036
+ {
18037
+ name: "Claude Agent",
18038
+ spanAttributes: {
18039
+ type: "task" /* TASK */
18040
+ }
18041
+ },
18042
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
18043
+ )
18044
+ );
17292
18045
  const startTime = getCurrentUnixTimestamp();
17293
18046
  try {
17294
18047
  span.log({
@@ -17453,24 +18206,28 @@ var ClaudeAgentSDKPlugin = class extends BasePlugin {
17453
18206
  };
17454
18207
 
17455
18208
  // src/instrumentation/plugins/cursor-sdk-channels.ts
17456
- var cursorSDKChannels = defineChannels("@cursor/sdk", {
17457
- create: channel({
17458
- channelName: "Agent.create",
17459
- kind: "async"
17460
- }),
17461
- resume: channel({
17462
- channelName: "Agent.resume",
17463
- kind: "async"
17464
- }),
17465
- prompt: channel({
17466
- channelName: "Agent.prompt",
17467
- kind: "async"
17468
- }),
17469
- send: channel({
17470
- channelName: "agent.send",
17471
- kind: "async"
17472
- })
17473
- });
18209
+ var cursorSDKChannels = defineChannels(
18210
+ "@cursor/sdk",
18211
+ {
18212
+ create: channel({
18213
+ channelName: "Agent.create",
18214
+ kind: "async"
18215
+ }),
18216
+ resume: channel({
18217
+ channelName: "Agent.resume",
18218
+ kind: "async"
18219
+ }),
18220
+ prompt: channel({
18221
+ channelName: "Agent.prompt",
18222
+ kind: "async"
18223
+ }),
18224
+ send: channel({
18225
+ channelName: "agent.send",
18226
+ kind: "async"
18227
+ })
18228
+ },
18229
+ { instrumentationName: INSTRUMENTATION_NAMES.CURSOR_SDK }
18230
+ );
17474
18231
 
17475
18232
  // src/instrumentation/plugins/cursor-sdk-plugin.ts
17476
18233
  var PATCHED_AGENT = /* @__PURE__ */ Symbol.for("braintrust.cursor-sdk.auto-patched-agent");
@@ -17522,10 +18279,15 @@ var CursorSDKPlugin = class extends BasePlugin {
17522
18279
  provider: "cursor",
17523
18280
  ...event.moduleVersion ? { "cursor_sdk.version": event.moduleVersion } : {}
17524
18281
  };
17525
- const span = startSpan({
17526
- name: "Cursor Agent",
17527
- spanAttributes: { type: "task" /* TASK */ }
17528
- });
18282
+ const span = startSpan(
18283
+ withSpanInstrumentationName(
18284
+ {
18285
+ name: "Cursor Agent",
18286
+ spanAttributes: { type: "task" /* TASK */ }
18287
+ },
18288
+ INSTRUMENTATION_NAMES.CURSOR_SDK
18289
+ )
18290
+ );
17529
18291
  const startTime = getCurrentUnixTimestamp();
17530
18292
  safeLog2(span, {
17531
18293
  input: sanitizeUserMessage(message),
@@ -17587,10 +18349,15 @@ var CursorSDKPlugin = class extends BasePlugin {
17587
18349
  provider: "cursor",
17588
18350
  ...event.moduleVersion ? { "cursor_sdk.version": event.moduleVersion } : {}
17589
18351
  };
17590
- const span = startSpan({
17591
- name: "Cursor Agent",
17592
- spanAttributes: { type: "task" /* TASK */ }
17593
- });
18352
+ const span = startSpan(
18353
+ withSpanInstrumentationName(
18354
+ {
18355
+ name: "Cursor Agent",
18356
+ spanAttributes: { type: "task" /* TASK */ }
18357
+ },
18358
+ INSTRUMENTATION_NAMES.CURSOR_SDK
18359
+ )
18360
+ );
17594
18361
  const startTime = getCurrentUnixTimestamp();
17595
18362
  safeLog2(span, {
17596
18363
  input: sanitizeUserMessage(message),
@@ -18037,29 +18804,39 @@ async function startToolSpan(state, args) {
18037
18804
  if (args.truncated?.result !== void 0) {
18038
18805
  metadata["cursor_sdk.tool.result_truncated"] = args.truncated.result;
18039
18806
  }
18040
- const span = startSpan({
18041
- event: {
18042
- input: args.args,
18043
- metadata
18044
- },
18045
- name: `tool: ${name}`,
18046
- parent: await state.span.export(),
18047
- spanAttributes: { type: "tool" /* TOOL */ }
18048
- });
18807
+ const span = startSpan(
18808
+ withSpanInstrumentationName(
18809
+ {
18810
+ event: {
18811
+ input: args.args,
18812
+ metadata
18813
+ },
18814
+ name: `tool: ${name}`,
18815
+ parent: await state.span.export(),
18816
+ spanAttributes: { type: "tool" /* TOOL */ }
18817
+ },
18818
+ INSTRUMENTATION_NAMES.CURSOR_SDK
18819
+ )
18820
+ );
18049
18821
  let subAgentSpan;
18050
18822
  if (isSubAgentToolName(name)) {
18051
- subAgentSpan = startSpan({
18052
- event: {
18053
- input: args.args,
18054
- metadata: {
18055
- "cursor_sdk.subagent.tool_call_id": args.callId,
18056
- "gen_ai.tool.name": name
18057
- }
18058
- },
18059
- name: formatSubAgentSpanName2(args.toolCall, args.args),
18060
- parent: await span.export(),
18061
- spanAttributes: { type: "task" /* TASK */ }
18062
- });
18823
+ subAgentSpan = startSpan(
18824
+ withSpanInstrumentationName(
18825
+ {
18826
+ event: {
18827
+ input: args.args,
18828
+ metadata: {
18829
+ "cursor_sdk.subagent.tool_call_id": args.callId,
18830
+ "gen_ai.tool.name": name
18831
+ }
18832
+ },
18833
+ name: formatSubAgentSpanName2(args.toolCall, args.args),
18834
+ parent: await span.export(),
18835
+ spanAttributes: { type: "task" /* TASK */ }
18836
+ },
18837
+ INSTRUMENTATION_NAMES.CURSOR_SDK
18838
+ )
18839
+ );
18063
18840
  }
18064
18841
  return { span, subAgentSpan };
18065
18842
  }
@@ -18318,24 +19095,28 @@ function cleanMetrics2(metrics) {
18318
19095
  }
18319
19096
 
18320
19097
  // src/instrumentation/plugins/openai-agents-channels.ts
18321
- var openAIAgentsCoreChannels = defineChannels("@openai/agents-core", {
18322
- onTraceStart: channel({
18323
- channelName: "tracing.processor.onTraceStart",
18324
- kind: "async"
18325
- }),
18326
- onTraceEnd: channel({
18327
- channelName: "tracing.processor.onTraceEnd",
18328
- kind: "async"
18329
- }),
18330
- onSpanStart: channel({
18331
- channelName: "tracing.processor.onSpanStart",
18332
- kind: "async"
18333
- }),
18334
- onSpanEnd: channel({
18335
- channelName: "tracing.processor.onSpanEnd",
18336
- kind: "async"
18337
- })
18338
- });
19098
+ var openAIAgentsCoreChannels = defineChannels(
19099
+ "@openai/agents-core",
19100
+ {
19101
+ onTraceStart: channel({
19102
+ channelName: "tracing.processor.onTraceStart",
19103
+ kind: "async"
19104
+ }),
19105
+ onTraceEnd: channel({
19106
+ channelName: "tracing.processor.onTraceEnd",
19107
+ kind: "async"
19108
+ }),
19109
+ onSpanStart: channel({
19110
+ channelName: "tracing.processor.onSpanStart",
19111
+ kind: "async"
19112
+ }),
19113
+ onSpanEnd: channel({
19114
+ channelName: "tracing.processor.onSpanEnd",
19115
+ kind: "async"
19116
+ })
19117
+ },
19118
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENAI_AGENTS }
19119
+ );
18339
19120
 
18340
19121
  // src/instrumentation/plugins/openai-agents-trace-processor.ts
18341
19122
  function isSpanData(spanData, type) {
@@ -18451,16 +19232,19 @@ var OpenAIAgentsTraceProcessor = class _OpenAIAgentsTraceProcessor {
18451
19232
  this.evictOldestTrace();
18452
19233
  }
18453
19234
  const current = currentSpan();
18454
- const span = current && current !== NOOP_SPAN ? current.startSpan({
18455
- name: trace.name,
18456
- type: "task" /* TASK */
18457
- }) : this.logger ? this.logger.startSpan({
18458
- name: trace.name,
18459
- type: "task" /* TASK */
18460
- }) : startSpan({
18461
- name: trace.name,
18462
- type: "task" /* TASK */
18463
- });
19235
+ const spanArgs = withSpanInstrumentationName(
19236
+ {
19237
+ name: trace.name,
19238
+ type: "task" /* TASK */
19239
+ },
19240
+ INSTRUMENTATION_NAMES.OPENAI_AGENTS
19241
+ );
19242
+ const span = current && current !== NOOP_SPAN ? current.startSpan(spanArgs) : this.logger ? this.logger.startSpan(spanArgs) : startSpan(
19243
+ withSpanInstrumentationName(
19244
+ spanArgs,
19245
+ INSTRUMENTATION_NAMES.OPENAI_AGENTS
19246
+ )
19247
+ );
18464
19248
  span.log({
18465
19249
  input: "Agent workflow started",
18466
19250
  metadata: {
@@ -18511,10 +19295,15 @@ var OpenAIAgentsTraceProcessor = class _OpenAIAgentsTraceProcessor {
18511
19295
  if (!parentSpan) {
18512
19296
  return Promise.resolve();
18513
19297
  }
18514
- const childSpan = parentSpan.startSpan({
18515
- name: spanNameFromAgents(span),
18516
- type: spanTypeFromAgents(span)
18517
- });
19298
+ const childSpan = parentSpan.startSpan(
19299
+ withSpanInstrumentationName(
19300
+ {
19301
+ name: spanNameFromAgents(span),
19302
+ type: spanTypeFromAgents(span)
19303
+ },
19304
+ INSTRUMENTATION_NAMES.OPENAI_AGENTS
19305
+ )
19306
+ );
18518
19307
  traceData.childSpans.set(span.spanId, childSpan);
18519
19308
  return Promise.resolve();
18520
19309
  }
@@ -18779,24 +19568,28 @@ var OpenAIAgentsPlugin = class extends BasePlugin {
18779
19568
  };
18780
19569
 
18781
19570
  // src/instrumentation/plugins/google-genai-channels.ts
18782
- var googleGenAIChannels = defineChannels("@google/genai", {
18783
- generateContent: channel({
18784
- channelName: "models.generateContent",
18785
- kind: "async"
18786
- }),
18787
- generateContentStream: channel({
18788
- channelName: "models.generateContentStream",
18789
- kind: "async"
18790
- }),
18791
- embedContent: channel({
18792
- channelName: "models.embedContent",
18793
- kind: "async"
18794
- }),
18795
- interactionsCreate: channel({
18796
- channelName: "interactions.create",
18797
- kind: "async"
18798
- })
18799
- });
19571
+ var googleGenAIChannels = defineChannels(
19572
+ "@google/genai",
19573
+ {
19574
+ generateContent: channel({
19575
+ channelName: "models.generateContent",
19576
+ kind: "async"
19577
+ }),
19578
+ generateContentStream: channel({
19579
+ channelName: "models.generateContentStream",
19580
+ kind: "async"
19581
+ }),
19582
+ embedContent: channel({
19583
+ channelName: "models.embedContent",
19584
+ kind: "async"
19585
+ }),
19586
+ interactionsCreate: channel({
19587
+ channelName: "interactions.create",
19588
+ kind: "async"
19589
+ })
19590
+ },
19591
+ { instrumentationName: INSTRUMENTATION_NAMES.GOOGLE_GENAI }
19592
+ );
18800
19593
 
18801
19594
  // src/instrumentation/plugins/google-genai-plugin.ts
18802
19595
  var GOOGLE_GENAI_INTERNAL_CONTEXT = {
@@ -18834,13 +19627,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
18834
19627
  const params = event.arguments[0];
18835
19628
  const input = serializeGenerateContentInput(params);
18836
19629
  const metadata = extractGenerateContentMetadata(params);
18837
- const span = startSpan({
18838
- name: "generate_content",
18839
- spanAttributes: {
18840
- type: "llm" /* LLM */
18841
- },
18842
- event: createWrapperParityEvent({ input, metadata })
18843
- });
19630
+ const span = startSpan(
19631
+ withSpanInstrumentationName(
19632
+ {
19633
+ name: "generate_content",
19634
+ spanAttributes: {
19635
+ type: "llm" /* LLM */
19636
+ },
19637
+ event: createWrapperParityEvent({ input, metadata })
19638
+ },
19639
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
19640
+ )
19641
+ );
18844
19642
  return {
18845
19643
  span,
18846
19644
  startTime: getCurrentUnixTimestamp()
@@ -18853,13 +19651,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
18853
19651
  const params = event.arguments[0];
18854
19652
  const input = serializeGenerateContentInput(params);
18855
19653
  const metadata = extractGenerateContentMetadata(params);
18856
- const span = startSpan({
18857
- name: "generate_content",
18858
- spanAttributes: {
18859
- type: "llm" /* LLM */
18860
- },
18861
- event: createWrapperParityEvent({ input, metadata })
18862
- });
19654
+ const span = startSpan(
19655
+ withSpanInstrumentationName(
19656
+ {
19657
+ name: "generate_content",
19658
+ spanAttributes: {
19659
+ type: "llm" /* LLM */
19660
+ },
19661
+ event: createWrapperParityEvent({ input, metadata })
19662
+ },
19663
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
19664
+ )
19665
+ );
18863
19666
  return {
18864
19667
  span,
18865
19668
  startTime: getCurrentUnixTimestamp()
@@ -18935,13 +19738,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
18935
19738
  const params = event.arguments[0];
18936
19739
  const input = serializeEmbedContentInput(params);
18937
19740
  const metadata = extractEmbedContentMetadata(params);
18938
- const span = startSpan({
18939
- name: "embed_content",
18940
- spanAttributes: {
18941
- type: "llm" /* LLM */
18942
- },
18943
- event: createWrapperParityEvent({ input, metadata })
18944
- });
19741
+ const span = startSpan(
19742
+ withSpanInstrumentationName(
19743
+ {
19744
+ name: "embed_content",
19745
+ spanAttributes: {
19746
+ type: "llm" /* LLM */
19747
+ },
19748
+ event: createWrapperParityEvent({ input, metadata })
19749
+ },
19750
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
19751
+ )
19752
+ );
18945
19753
  return {
18946
19754
  span,
18947
19755
  startTime: getCurrentUnixTimestamp()
@@ -18954,13 +19762,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
18954
19762
  const params = event.arguments[0];
18955
19763
  const input = serializeEmbedContentInput(params);
18956
19764
  const metadata = extractEmbedContentMetadata(params);
18957
- const span = startSpan({
18958
- name: "embed_content",
18959
- spanAttributes: {
18960
- type: "llm" /* LLM */
18961
- },
18962
- event: createWrapperParityEvent({ input, metadata })
18963
- });
19765
+ const span = startSpan(
19766
+ withSpanInstrumentationName(
19767
+ {
19768
+ name: "embed_content",
19769
+ spanAttributes: {
19770
+ type: "llm" /* LLM */
19771
+ },
19772
+ event: createWrapperParityEvent({ input, metadata })
19773
+ },
19774
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
19775
+ )
19776
+ );
18964
19777
  return {
18965
19778
  span,
18966
19779
  startTime: getCurrentUnixTimestamp()
@@ -19071,16 +19884,21 @@ function patchGoogleGenAIStreamingResult(args) {
19071
19884
  const requestStartTime = startTime ?? getCurrentUnixTimestamp();
19072
19885
  const ensureSpan = () => {
19073
19886
  if (!span) {
19074
- span = startSpan({
19075
- name: "generate_content_stream",
19076
- spanAttributes: {
19077
- type: "llm" /* LLM */
19078
- },
19079
- event: {
19080
- input,
19081
- metadata
19082
- }
19083
- });
19887
+ span = startSpan(
19888
+ withSpanInstrumentationName(
19889
+ {
19890
+ name: "generate_content_stream",
19891
+ spanAttributes: {
19892
+ type: "llm" /* LLM */
19893
+ },
19894
+ event: {
19895
+ input,
19896
+ metadata
19897
+ }
19898
+ },
19899
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
19900
+ )
19901
+ );
19084
19902
  }
19085
19903
  return span;
19086
19904
  };
@@ -19848,28 +20666,32 @@ function tryToDict(obj) {
19848
20666
  }
19849
20667
 
19850
20668
  // src/instrumentation/plugins/huggingface-channels.ts
19851
- var huggingFaceChannels = defineChannels("@huggingface/inference", {
19852
- chatCompletion: channel({
19853
- channelName: "chatCompletion",
19854
- kind: "async"
19855
- }),
19856
- chatCompletionStream: channel({
19857
- channelName: "chatCompletionStream",
19858
- kind: "sync-stream"
19859
- }),
19860
- textGeneration: channel({
19861
- channelName: "textGeneration",
19862
- kind: "async"
19863
- }),
19864
- textGenerationStream: channel({
19865
- channelName: "textGenerationStream",
19866
- kind: "sync-stream"
19867
- }),
19868
- featureExtraction: channel({
19869
- channelName: "featureExtraction",
19870
- kind: "async"
19871
- })
19872
- });
20669
+ var huggingFaceChannels = defineChannels(
20670
+ "@huggingface/inference",
20671
+ {
20672
+ chatCompletion: channel({
20673
+ channelName: "chatCompletion",
20674
+ kind: "async"
20675
+ }),
20676
+ chatCompletionStream: channel({
20677
+ channelName: "chatCompletionStream",
20678
+ kind: "sync-stream"
20679
+ }),
20680
+ textGeneration: channel({
20681
+ channelName: "textGeneration",
20682
+ kind: "async"
20683
+ }),
20684
+ textGenerationStream: channel({
20685
+ channelName: "textGenerationStream",
20686
+ kind: "sync-stream"
20687
+ }),
20688
+ featureExtraction: channel({
20689
+ channelName: "featureExtraction",
20690
+ kind: "async"
20691
+ })
20692
+ },
20693
+ { instrumentationName: INSTRUMENTATION_NAMES.HUGGINGFACE }
20694
+ );
19873
20695
 
19874
20696
  // src/instrumentation/plugins/huggingface-plugin.ts
19875
20697
  var REQUEST_METADATA_ALLOWLIST = /* @__PURE__ */ new Set([
@@ -20296,20 +21118,24 @@ function extractTextGenerationStreamMetadata(chunks) {
20296
21118
  }
20297
21119
 
20298
21120
  // src/instrumentation/plugins/openrouter-agent-channels.ts
20299
- var openRouterAgentChannels = defineChannels("@openrouter/agent", {
20300
- callModel: channel({
20301
- channelName: "callModel",
20302
- kind: "sync-stream"
20303
- }),
20304
- callModelTurn: channel({
20305
- channelName: "callModel.turn",
20306
- kind: "async"
20307
- }),
20308
- toolExecute: channel({
20309
- channelName: "tool.execute",
20310
- kind: "async"
20311
- })
20312
- });
21121
+ var openRouterAgentChannels = defineChannels(
21122
+ "@openrouter/agent",
21123
+ {
21124
+ callModel: channel({
21125
+ channelName: "callModel",
21126
+ kind: "sync-stream"
21127
+ }),
21128
+ callModelTurn: channel({
21129
+ channelName: "callModel.turn",
21130
+ kind: "async"
21131
+ }),
21132
+ toolExecute: channel({
21133
+ channelName: "tool.execute",
21134
+ kind: "async"
21135
+ })
21136
+ },
21137
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENROUTER_AGENT }
21138
+ );
20313
21139
 
20314
21140
  // src/instrumentation/plugins/openrouter-agent-plugin.ts
20315
21141
  var OpenRouterAgentPlugin = class extends BasePlugin {
@@ -21079,38 +21905,40 @@ function normalizeError(error) {
21079
21905
  }
21080
21906
 
21081
21907
  // src/instrumentation/plugins/openrouter-channels.ts
21082
- var openRouterChannels = defineChannels("@openrouter/sdk", {
21083
- chatSend: channel({
21084
- channelName: "chat.send",
21085
- kind: "async"
21086
- }),
21087
- embeddingsGenerate: channel({
21088
- channelName: "embeddings.generate",
21089
- kind: "async"
21090
- }),
21091
- rerankRerank: channel(
21092
- {
21908
+ var openRouterChannels = defineChannels(
21909
+ "@openrouter/sdk",
21910
+ {
21911
+ chatSend: channel({
21912
+ channelName: "chat.send",
21913
+ kind: "async"
21914
+ }),
21915
+ embeddingsGenerate: channel({
21916
+ channelName: "embeddings.generate",
21917
+ kind: "async"
21918
+ }),
21919
+ rerankRerank: channel({
21093
21920
  channelName: "rerank.rerank",
21094
21921
  kind: "async"
21095
- }
21096
- ),
21097
- betaResponsesSend: channel({
21098
- channelName: "beta.responses.send",
21099
- kind: "async"
21100
- }),
21101
- callModel: channel({
21102
- channelName: "callModel",
21103
- kind: "sync-stream"
21104
- }),
21105
- callModelTurn: channel({
21106
- channelName: "callModel.turn",
21107
- kind: "async"
21108
- }),
21109
- toolExecute: channel({
21110
- channelName: "tool.execute",
21111
- kind: "async"
21112
- })
21113
- });
21922
+ }),
21923
+ betaResponsesSend: channel({
21924
+ channelName: "beta.responses.send",
21925
+ kind: "async"
21926
+ }),
21927
+ callModel: channel({
21928
+ channelName: "callModel",
21929
+ kind: "sync-stream"
21930
+ }),
21931
+ callModelTurn: channel({
21932
+ channelName: "callModel.turn",
21933
+ kind: "async"
21934
+ }),
21935
+ toolExecute: channel({
21936
+ channelName: "tool.execute",
21937
+ kind: "async"
21938
+ })
21939
+ },
21940
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENROUTER }
21941
+ );
21114
21942
 
21115
21943
  // src/instrumentation/plugins/openrouter-plugin.ts
21116
21944
  var OpenRouterPlugin = class extends BasePlugin {
@@ -22150,52 +22978,56 @@ function normalizeError2(error) {
22150
22978
  }
22151
22979
 
22152
22980
  // src/instrumentation/plugins/mistral-channels.ts
22153
- var mistralChannels = defineChannels("@mistralai/mistralai", {
22154
- chatComplete: channel({
22155
- channelName: "chat.complete",
22156
- kind: "async"
22157
- }),
22158
- chatStream: channel({
22159
- channelName: "chat.stream",
22160
- kind: "async"
22161
- }),
22162
- embeddingsCreate: channel({
22163
- channelName: "embeddings.create",
22164
- kind: "async"
22165
- }),
22166
- classifiersModerate: channel({
22167
- channelName: "classifiers.moderate",
22168
- kind: "async"
22169
- }),
22170
- classifiersModerateChat: channel({
22171
- channelName: "classifiers.moderateChat",
22172
- kind: "async"
22173
- }),
22174
- classifiersClassify: channel({
22175
- channelName: "classifiers.classify",
22176
- kind: "async"
22177
- }),
22178
- classifiersClassifyChat: channel({
22179
- channelName: "classifiers.classifyChat",
22180
- kind: "async"
22181
- }),
22182
- fimComplete: channel({
22183
- channelName: "fim.complete",
22184
- kind: "async"
22185
- }),
22186
- fimStream: channel({
22187
- channelName: "fim.stream",
22188
- kind: "async"
22189
- }),
22190
- agentsComplete: channel({
22191
- channelName: "agents.complete",
22192
- kind: "async"
22193
- }),
22194
- agentsStream: channel({
22195
- channelName: "agents.stream",
22196
- kind: "async"
22197
- })
22198
- });
22981
+ var mistralChannels = defineChannels(
22982
+ "@mistralai/mistralai",
22983
+ {
22984
+ chatComplete: channel({
22985
+ channelName: "chat.complete",
22986
+ kind: "async"
22987
+ }),
22988
+ chatStream: channel({
22989
+ channelName: "chat.stream",
22990
+ kind: "async"
22991
+ }),
22992
+ embeddingsCreate: channel({
22993
+ channelName: "embeddings.create",
22994
+ kind: "async"
22995
+ }),
22996
+ classifiersModerate: channel({
22997
+ channelName: "classifiers.moderate",
22998
+ kind: "async"
22999
+ }),
23000
+ classifiersModerateChat: channel({
23001
+ channelName: "classifiers.moderateChat",
23002
+ kind: "async"
23003
+ }),
23004
+ classifiersClassify: channel({
23005
+ channelName: "classifiers.classify",
23006
+ kind: "async"
23007
+ }),
23008
+ classifiersClassifyChat: channel({
23009
+ channelName: "classifiers.classifyChat",
23010
+ kind: "async"
23011
+ }),
23012
+ fimComplete: channel({
23013
+ channelName: "fim.complete",
23014
+ kind: "async"
23015
+ }),
23016
+ fimStream: channel({
23017
+ channelName: "fim.stream",
23018
+ kind: "async"
23019
+ }),
23020
+ agentsComplete: channel({
23021
+ channelName: "agents.complete",
23022
+ kind: "async"
23023
+ }),
23024
+ agentsStream: channel({
23025
+ channelName: "agents.stream",
23026
+ kind: "async"
23027
+ })
23028
+ },
23029
+ { instrumentationName: INSTRUMENTATION_NAMES.MISTRAL }
23030
+ );
22199
23031
 
22200
23032
  // src/instrumentation/plugins/mistral-plugin.ts
22201
23033
  var MistralPlugin = class extends BasePlugin {
@@ -22815,20 +23647,24 @@ function aggregateMistralStreamChunks(chunks) {
22815
23647
  }
22816
23648
 
22817
23649
  // src/instrumentation/plugins/google-adk-channels.ts
22818
- var googleADKChannels = defineChannels("@google/adk", {
22819
- runnerRunAsync: channel({
22820
- channelName: "runner.runAsync",
22821
- kind: "sync-stream"
22822
- }),
22823
- agentRunAsync: channel({
22824
- channelName: "agent.runAsync",
22825
- kind: "sync-stream"
22826
- }),
22827
- toolRunAsync: channel({
22828
- channelName: "tool.runAsync",
22829
- kind: "async"
22830
- })
22831
- });
23650
+ var googleADKChannels = defineChannels(
23651
+ "@google/adk",
23652
+ {
23653
+ runnerRunAsync: channel({
23654
+ channelName: "runner.runAsync",
23655
+ kind: "sync-stream"
23656
+ }),
23657
+ agentRunAsync: channel({
23658
+ channelName: "agent.runAsync",
23659
+ kind: "sync-stream"
23660
+ }),
23661
+ toolRunAsync: channel({
23662
+ channelName: "tool.runAsync",
23663
+ kind: "async"
23664
+ })
23665
+ },
23666
+ { instrumentationName: INSTRUMENTATION_NAMES.GOOGLE_ADK }
23667
+ );
22832
23668
 
22833
23669
  // src/instrumentation/plugins/google-adk-plugin.ts
22834
23670
  var GoogleADKPlugin = class extends BasePlugin {
@@ -22853,12 +23689,17 @@ var GoogleADKPlugin = class extends BasePlugin {
22853
23689
  const createState = (event) => {
22854
23690
  const params = event.arguments[0] ?? {};
22855
23691
  const contextKey = extractRunnerContextKey(params);
22856
- const span = startSpan({
22857
- name: "Google ADK Runner",
22858
- spanAttributes: {
22859
- type: "task" /* TASK */
22860
- }
22861
- });
23692
+ const span = startSpan(
23693
+ withSpanInstrumentationName(
23694
+ {
23695
+ name: "Google ADK Runner",
23696
+ spanAttributes: {
23697
+ type: "task" /* TASK */
23698
+ }
23699
+ },
23700
+ INSTRUMENTATION_NAMES.GOOGLE_ADK
23701
+ )
23702
+ );
22862
23703
  const startTime = getCurrentUnixTimestamp();
22863
23704
  try {
22864
23705
  const metadata = extractRunnerMetadata(params);
@@ -22944,18 +23785,23 @@ var GoogleADKPlugin = class extends BasePlugin {
22944
23785
  this.activeRunnerSpans
22945
23786
  );
22946
23787
  const contextKey = extractInvocationContextKey(parentContext);
22947
- const span = startSpan({
22948
- name: agentName ? `Agent: ${agentName}` : "Google ADK Agent",
22949
- spanAttributes: {
22950
- type: "task" /* TASK */
22951
- },
22952
- ...runnerParentSpan ? {
22953
- parentSpanIds: {
22954
- spanId: runnerParentSpan.spanId,
22955
- rootSpanId: runnerParentSpan.rootSpanId
22956
- }
22957
- } : {}
22958
- });
23788
+ const span = startSpan(
23789
+ withSpanInstrumentationName(
23790
+ {
23791
+ name: agentName ? `Agent: ${agentName}` : "Google ADK Agent",
23792
+ spanAttributes: {
23793
+ type: "task" /* TASK */
23794
+ },
23795
+ ...runnerParentSpan ? {
23796
+ parentSpanIds: {
23797
+ spanId: runnerParentSpan.spanId,
23798
+ rootSpanId: runnerParentSpan.rootSpanId
23799
+ }
23800
+ } : {}
23801
+ },
23802
+ INSTRUMENTATION_NAMES.GOOGLE_ADK
23803
+ )
23804
+ );
22959
23805
  const startTime = getCurrentUnixTimestamp();
22960
23806
  try {
22961
23807
  const metadata = {
@@ -23048,22 +23894,27 @@ var GoogleADKPlugin = class extends BasePlugin {
23048
23894
  this.activeAgentSpans,
23049
23895
  this.activeRunnerSpans
23050
23896
  );
23051
- const createSpan = () => startSpan({
23052
- name: toolName ? `tool: ${toolName}` : "Google ADK Tool",
23053
- spanAttributes: {
23054
- type: "tool" /* TOOL */
23055
- },
23056
- event: {
23057
- input: req.args,
23058
- metadata: {
23059
- provider: "google-adk",
23060
- ...toolName && { "google_adk.tool_name": toolName },
23061
- ...extractToolCallId(req) && {
23062
- "google_adk.tool_call_id": extractToolCallId(req)
23897
+ const createSpan = () => startSpan(
23898
+ withSpanInstrumentationName(
23899
+ {
23900
+ name: toolName ? `tool: ${toolName}` : "Google ADK Tool",
23901
+ spanAttributes: {
23902
+ type: "tool" /* TOOL */
23903
+ },
23904
+ event: {
23905
+ input: req.args,
23906
+ metadata: {
23907
+ provider: "google-adk",
23908
+ ...toolName && { "google_adk.tool_name": toolName },
23909
+ ...extractToolCallId(req) && {
23910
+ "google_adk.tool_call_id": extractToolCallId(req)
23911
+ }
23912
+ }
23063
23913
  }
23064
- }
23065
- }
23066
- });
23914
+ },
23915
+ INSTRUMENTATION_NAMES.GOOGLE_ADK
23916
+ )
23917
+ );
23067
23918
  const span = parentSpan ? withCurrent(parentSpan, () => createSpan()) : createSpan();
23068
23919
  const startTime = getCurrentUnixTimestamp();
23069
23920
  states.set(event, { span, startTime });
@@ -23462,24 +24313,28 @@ function cleanMetrics4(metrics) {
23462
24313
  }
23463
24314
 
23464
24315
  // src/instrumentation/plugins/cohere-channels.ts
23465
- var cohereChannels = defineChannels("cohere-ai", {
23466
- chat: channel({
23467
- channelName: "chat",
23468
- kind: "async"
23469
- }),
23470
- chatStream: channel({
23471
- channelName: "chatStream",
23472
- kind: "async"
23473
- }),
23474
- embed: channel({
23475
- channelName: "embed",
23476
- kind: "async"
23477
- }),
23478
- rerank: channel({
23479
- channelName: "rerank",
23480
- kind: "async"
23481
- })
23482
- });
24316
+ var cohereChannels = defineChannels(
24317
+ "cohere-ai",
24318
+ {
24319
+ chat: channel({
24320
+ channelName: "chat",
24321
+ kind: "async"
24322
+ }),
24323
+ chatStream: channel({
24324
+ channelName: "chatStream",
24325
+ kind: "async"
24326
+ }),
24327
+ embed: channel({
24328
+ channelName: "embed",
24329
+ kind: "async"
24330
+ }),
24331
+ rerank: channel({
24332
+ channelName: "rerank",
24333
+ kind: "async"
24334
+ })
24335
+ },
24336
+ { instrumentationName: INSTRUMENTATION_NAMES.COHERE }
24337
+ );
23483
24338
 
23484
24339
  // src/instrumentation/plugins/cohere-plugin.ts
23485
24340
  var CoherePlugin = class extends BasePlugin {
@@ -24148,18 +25003,20 @@ function aggregateCohereChatStreamChunks(chunks) {
24148
25003
  }
24149
25004
 
24150
25005
  // src/instrumentation/plugins/groq-channels.ts
24151
- var groqChannels = defineChannels("groq-sdk", {
24152
- chatCompletionsCreate: channel({
24153
- channelName: "chat.completions.create",
24154
- kind: "async"
24155
- }),
24156
- embeddingsCreate: channel(
24157
- {
25006
+ var groqChannels = defineChannels(
25007
+ "groq-sdk",
25008
+ {
25009
+ chatCompletionsCreate: channel({
25010
+ channelName: "chat.completions.create",
25011
+ kind: "async"
25012
+ }),
25013
+ embeddingsCreate: channel({
24158
25014
  channelName: "embeddings.create",
24159
25015
  kind: "async"
24160
- }
24161
- )
24162
- });
25016
+ })
25017
+ },
25018
+ { instrumentationName: INSTRUMENTATION_NAMES.GROQ }
25019
+ );
24163
25020
 
24164
25021
  // src/instrumentation/plugins/groq-plugin.ts
24165
25022
  var GroqPlugin = class extends BasePlugin {
@@ -24262,15 +25119,27 @@ var clientSendChannel = channel({
24262
25119
  channelName: "client.send",
24263
25120
  kind: "async"
24264
25121
  });
24265
- var bedrockRuntimeChannels = defineChannels("aws-bedrock-runtime", {
24266
- clientSend: clientSendChannel
24267
- });
24268
- var smithyCoreChannels = defineChannels("@smithy/core", {
24269
- clientSend: clientSendChannel
24270
- });
24271
- var smithyClientChannels = defineChannels("@smithy/smithy-client", {
24272
- clientSend: clientSendChannel
24273
- });
25122
+ var bedrockRuntimeChannels = defineChannels(
25123
+ "aws-bedrock-runtime",
25124
+ {
25125
+ clientSend: clientSendChannel
25126
+ },
25127
+ { instrumentationName: INSTRUMENTATION_NAMES.BEDROCK_RUNTIME }
25128
+ );
25129
+ var smithyCoreChannels = defineChannels(
25130
+ "@smithy/core",
25131
+ {
25132
+ clientSend: clientSendChannel
25133
+ },
25134
+ { instrumentationName: INSTRUMENTATION_NAMES.BEDROCK_RUNTIME }
25135
+ );
25136
+ var smithyClientChannels = defineChannels(
25137
+ "@smithy/smithy-client",
25138
+ {
25139
+ clientSend: clientSendChannel
25140
+ },
25141
+ { instrumentationName: INSTRUMENTATION_NAMES.BEDROCK_RUNTIME }
25142
+ );
24274
25143
 
24275
25144
  // src/instrumentation/plugins/bedrock-runtime-common.ts
24276
25145
  var BEDROCK_RUNTIME_COMMAND_OPERATIONS = {
@@ -24904,38 +25773,46 @@ function extractTextFromJsonLike(value) {
24904
25773
  }
24905
25774
 
24906
25775
  // src/instrumentation/plugins/genkit-channels.ts
24907
- var genkitChannels = defineChannels("@genkit-ai/ai", {
24908
- generate: channel({
24909
- channelName: "generate",
24910
- kind: "async"
24911
- }),
24912
- generateStream: channel({
24913
- channelName: "generateStream",
24914
- kind: "sync-stream"
24915
- }),
24916
- embed: channel({
24917
- channelName: "embed",
24918
- kind: "async"
24919
- }),
24920
- embedMany: channel({
24921
- channelName: "embedMany",
24922
- kind: "async"
24923
- }),
24924
- actionRun: channel({
24925
- channelName: "action.run",
24926
- kind: "async"
24927
- }),
24928
- actionStream: channel({
24929
- channelName: "action.stream",
24930
- kind: "sync-stream"
24931
- })
24932
- });
24933
- var genkitCoreChannels = defineChannels("@genkit-ai/core", {
24934
- actionSpan: channel({
24935
- channelName: "action.span",
24936
- kind: "async"
24937
- })
24938
- });
25776
+ var genkitChannels = defineChannels(
25777
+ "@genkit-ai/ai",
25778
+ {
25779
+ generate: channel({
25780
+ channelName: "generate",
25781
+ kind: "async"
25782
+ }),
25783
+ generateStream: channel({
25784
+ channelName: "generateStream",
25785
+ kind: "sync-stream"
25786
+ }),
25787
+ embed: channel({
25788
+ channelName: "embed",
25789
+ kind: "async"
25790
+ }),
25791
+ embedMany: channel({
25792
+ channelName: "embedMany",
25793
+ kind: "async"
25794
+ }),
25795
+ actionRun: channel({
25796
+ channelName: "action.run",
25797
+ kind: "async"
25798
+ }),
25799
+ actionStream: channel({
25800
+ channelName: "action.stream",
25801
+ kind: "sync-stream"
25802
+ })
25803
+ },
25804
+ { instrumentationName: INSTRUMENTATION_NAMES.GENKIT }
25805
+ );
25806
+ var genkitCoreChannels = defineChannels(
25807
+ "@genkit-ai/core",
25808
+ {
25809
+ actionSpan: channel({
25810
+ channelName: "action.span",
25811
+ kind: "async"
25812
+ })
25813
+ },
25814
+ { instrumentationName: INSTRUMENTATION_NAMES.GENKIT }
25815
+ );
24939
25816
 
24940
25817
  // src/instrumentation/plugins/genkit-plugin.ts
24941
25818
  var GenkitPlugin = class extends BasePlugin {
@@ -25120,12 +25997,17 @@ function startActionSpanState(args) {
25120
25997
  if (!shouldTraceAction(args.metadata, args.runStepName)) {
25121
25998
  return void 0;
25122
25999
  }
25123
- const span = startSpan({
25124
- name: actionSpanName(args.metadata, args.runStepName),
25125
- spanAttributes: {
25126
- type: actionSpanType(args.metadata)
25127
- }
25128
- });
26000
+ const span = startSpan(
26001
+ withSpanInstrumentationName(
26002
+ {
26003
+ name: actionSpanName(args.metadata, args.runStepName),
26004
+ spanAttributes: {
26005
+ type: actionSpanType(args.metadata)
26006
+ }
26007
+ },
26008
+ INSTRUMENTATION_NAMES.GENKIT
26009
+ )
26010
+ );
25129
26011
  const startTime = getCurrentUnixTimestamp();
25130
26012
  span.log({
25131
26013
  input: args.input,
@@ -25486,20 +26368,24 @@ function stringValue(value) {
25486
26368
  }
25487
26369
 
25488
26370
  // src/instrumentation/plugins/github-copilot-channels.ts
25489
- var gitHubCopilotChannels = defineChannels("@github/copilot-sdk", {
25490
- createSession: channel({
25491
- channelName: "client.createSession",
25492
- kind: "async"
25493
- }),
25494
- resumeSession: channel({
25495
- channelName: "client.resumeSession",
25496
- kind: "async"
25497
- }),
25498
- sendAndWait: channel({
25499
- channelName: "session.sendAndWait",
25500
- kind: "async"
25501
- })
25502
- });
26371
+ var gitHubCopilotChannels = defineChannels(
26372
+ "@github/copilot-sdk",
26373
+ {
26374
+ createSession: channel({
26375
+ channelName: "client.createSession",
26376
+ kind: "async"
26377
+ }),
26378
+ resumeSession: channel({
26379
+ channelName: "client.resumeSession",
26380
+ kind: "async"
26381
+ }),
26382
+ sendAndWait: channel({
26383
+ channelName: "session.sendAndWait",
26384
+ kind: "async"
26385
+ })
26386
+ },
26387
+ { instrumentationName: INSTRUMENTATION_NAMES.GITHUB_COPILOT }
26388
+ );
25503
26389
 
25504
26390
  // src/instrumentation/plugins/github-copilot-plugin.ts
25505
26391
  var ROOT_AGENT_KEY = "__root__";
@@ -25590,11 +26476,16 @@ async function handleTurnStart(state, agentId) {
25590
26476
  return;
25591
26477
  }
25592
26478
  const parentId = await getParentIdForAgent(state, agentId);
25593
- const span = startSpan({
25594
- name: "Copilot Turn",
25595
- parent: parentId,
25596
- spanAttributes: { type: "task" /* TASK */ }
25597
- });
26479
+ const span = startSpan(
26480
+ withSpanInstrumentationName(
26481
+ {
26482
+ name: "Copilot Turn",
26483
+ parent: parentId,
26484
+ spanAttributes: { type: "task" /* TASK */ }
26485
+ },
26486
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
26487
+ )
26488
+ );
25598
26489
  const pendingUserMessage = state.pendingUserMessages.get(key);
25599
26490
  if (pendingUserMessage) {
25600
26491
  span.log({ input: pendingUserMessage });
@@ -25625,11 +26516,16 @@ async function handleUsage(state, agentId, usage) {
25625
26516
  const parentId = turn ? await turn.id : await state.session.id;
25626
26517
  const content = state.currentMessageContent.get(key);
25627
26518
  const { metrics, metadata } = extractMetricsFromUsage(usage);
25628
- const llmSpan = startSpan({
25629
- name: "github.copilot.llm",
25630
- parent: parentId,
25631
- spanAttributes: { type: "llm" /* LLM */ }
25632
- });
26519
+ const llmSpan = startSpan(
26520
+ withSpanInstrumentationName(
26521
+ {
26522
+ name: "github.copilot.llm",
26523
+ parent: parentId,
26524
+ spanAttributes: { type: "llm" /* LLM */ }
26525
+ },
26526
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
26527
+ )
26528
+ );
25633
26529
  llmSpan.log({
25634
26530
  output: content ?? void 0,
25635
26531
  metadata,
@@ -25655,11 +26551,16 @@ async function handleToolStart(state, agentId, toolCallId, toolName, args, mcpSe
25655
26551
  }
25656
26552
  const parentId = await getToolParentId(state, agentId);
25657
26553
  const displayName = mcpServerName ? `tool: ${mcpServerName}/${toolName}` : `tool: ${toolName}`;
25658
- const span = startSpan({
25659
- name: displayName,
25660
- parent: parentId,
25661
- spanAttributes: { type: "tool" /* TOOL */ }
25662
- });
26554
+ const span = startSpan(
26555
+ withSpanInstrumentationName(
26556
+ {
26557
+ name: displayName,
26558
+ parent: parentId,
26559
+ spanAttributes: { type: "tool" /* TOOL */ }
26560
+ },
26561
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
26562
+ )
26563
+ );
25663
26564
  const metadata = {
25664
26565
  "gen_ai.tool.name": toolName,
25665
26566
  "gen_ai.tool.call.id": toolCallId
@@ -25695,11 +26596,16 @@ async function handleSubagentStarted(state, agentId, toolCallId, agentDisplayNam
25695
26596
  }
25696
26597
  const tool = state.activeTools.get(toolCallId);
25697
26598
  const parentId = tool ? await tool.id : await state.session.id;
25698
- const span = startSpan({
25699
- name: `Agent: ${agentDisplayName}`,
25700
- parent: parentId,
25701
- spanAttributes: { type: "task" /* TASK */ }
25702
- });
26599
+ const span = startSpan(
26600
+ withSpanInstrumentationName(
26601
+ {
26602
+ name: `Agent: ${agentDisplayName}`,
26603
+ parent: parentId,
26604
+ spanAttributes: { type: "task" /* TASK */ }
26605
+ },
26606
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
26607
+ )
26608
+ );
25703
26609
  span.log({
25704
26610
  metadata: {
25705
26611
  "github_copilot.agent_name": agentDisplayName,
@@ -25925,10 +26831,15 @@ function makeSessionHandlers(sessionStates, configArgIndex, includeProviderMetad
25925
26831
  if (!config || typeof config !== "object") {
25926
26832
  return;
25927
26833
  }
25928
- const sessionSpan = startSpan({
25929
- name: "Copilot Session",
25930
- spanAttributes: { type: "task" /* TASK */ }
25931
- });
26834
+ const sessionSpan = startSpan(
26835
+ withSpanInstrumentationName(
26836
+ {
26837
+ name: "Copilot Session",
26838
+ spanAttributes: { type: "task" /* TASK */ }
26839
+ },
26840
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
26841
+ )
26842
+ );
25932
26843
  const metadata = {};
25933
26844
  if (config.model) {
25934
26845
  metadata["github_copilot.model"] = config.model;
@@ -26016,12 +26927,16 @@ var GitHubCopilotPlugin = class extends BasePlugin {
26016
26927
  };
26017
26928
 
26018
26929
  // src/instrumentation/plugins/flue-channels.ts
26019
- var flueChannels = defineChannels("@flue/runtime", {
26020
- createContext: channel({
26021
- channelName: "createFlueContext",
26022
- kind: "sync-stream"
26023
- })
26024
- });
26930
+ var flueChannels = defineChannels(
26931
+ "@flue/runtime",
26932
+ {
26933
+ createContext: channel({
26934
+ channelName: "createFlueContext",
26935
+ kind: "sync-stream"
26936
+ })
26937
+ },
26938
+ { instrumentationName: INSTRUMENTATION_NAMES.FLUE }
26939
+ );
26025
26940
 
26026
26941
  // src/instrumentation/plugins/flue-plugin.ts
26027
26942
  var FLUE_AUTO_STATE = /* @__PURE__ */ Symbol.for("braintrust.flue.auto-state");
@@ -26364,15 +27279,20 @@ var FlueObserveBridge = class {
26364
27279
  safeLog3(existing.span, { input, metadata });
26365
27280
  return;
26366
27281
  }
26367
- const span = startSpan({
26368
- name: `workflow:${workflowName}`,
26369
- spanAttributes: { type: "task" /* TASK */ },
26370
- startTime: eventTime(event.startedAt ?? event.timestamp),
26371
- event: {
26372
- input,
26373
- metadata
26374
- }
26375
- });
27282
+ const span = startSpan(
27283
+ withSpanInstrumentationName(
27284
+ {
27285
+ name: `workflow:${workflowName}`,
27286
+ spanAttributes: { type: "task" /* TASK */ },
27287
+ startTime: eventTime(event.startedAt ?? event.timestamp),
27288
+ event: {
27289
+ input,
27290
+ metadata
27291
+ }
27292
+ },
27293
+ INSTRUMENTATION_NAMES.FLUE
27294
+ )
27295
+ );
26376
27296
  this.runsById.set(event.runId, { metadata, span });
26377
27297
  }
26378
27298
  handleRunResume(event, ctx) {
@@ -26392,12 +27312,17 @@ var FlueObserveBridge = class {
26392
27312
  safeLog3(existing.span, { metadata });
26393
27313
  return;
26394
27314
  }
26395
- const span = startSpan({
26396
- name: `workflow:${workflowName}`,
26397
- spanAttributes: { type: "task" /* TASK */ },
26398
- startTime: eventTime(event.startedAt ?? event.timestamp),
26399
- event: { metadata }
26400
- });
27315
+ const span = startSpan(
27316
+ withSpanInstrumentationName(
27317
+ {
27318
+ name: `workflow:${workflowName}`,
27319
+ spanAttributes: { type: "task" /* TASK */ },
27320
+ startTime: eventTime(event.startedAt ?? event.timestamp),
27321
+ event: { metadata }
27322
+ },
27323
+ INSTRUMENTATION_NAMES.FLUE
27324
+ )
27325
+ );
26401
27326
  this.runsById.set(event.runId, { metadata, span });
26402
27327
  }
26403
27328
  handleRunEnd(event) {
@@ -27036,7 +27961,14 @@ function stateMatchesRun(state, runId) {
27036
27961
  return state.metadata["flue.run_id"] === runId;
27037
27962
  }
27038
27963
  function startFlueSpan(parent, args) {
27039
- return parent ? withCurrent(parent, () => startSpan(args)) : startSpan(args);
27964
+ return parent ? withCurrent(
27965
+ parent,
27966
+ () => startSpan(
27967
+ withSpanInstrumentationName(args, INSTRUMENTATION_NAMES.FLUE)
27968
+ )
27969
+ ) : startSpan(
27970
+ withSpanInstrumentationName(args, INSTRUMENTATION_NAMES.FLUE)
27971
+ );
27040
27972
  }
27041
27973
  function runWithCurrentSpanStore(span, next) {
27042
27974
  const state = _internalGetGlobalState();
@@ -27126,9 +28058,13 @@ var BraintrustLangChainCallbackHandler = class {
27126
28058
  ...this.options.debug ? { runId, parentRunId } : {}
27127
28059
  }
27128
28060
  };
27129
- let span = parentSpan.startSpan(args);
28061
+ const spanArgs = withSpanInstrumentationName(
28062
+ args,
28063
+ INSTRUMENTATION_NAMES.LANGCHAIN
28064
+ );
28065
+ let span = parentSpan.startSpan(spanArgs);
27130
28066
  if (!Object.is(this.options.logger, NOOP_SPAN) && Object.is(span, NOOP_SPAN)) {
27131
- span = initLogger().startSpan(args);
28067
+ span = initLogger().startSpan(spanArgs);
27132
28068
  }
27133
28069
  this.spans.set(runId, span);
27134
28070
  }
@@ -27425,16 +28361,20 @@ function isRecord(value) {
27425
28361
  }
27426
28362
 
27427
28363
  // src/instrumentation/plugins/langchain-channels.ts
27428
- var langChainChannels = defineChannels("@langchain/core", {
27429
- configure: channel({
27430
- channelName: "CallbackManager.configure",
27431
- kind: "sync-stream"
27432
- }),
27433
- configureSync: channel({
27434
- channelName: "CallbackManager._configureSync",
27435
- kind: "sync-stream"
27436
- })
27437
- });
28364
+ var langChainChannels = defineChannels(
28365
+ "@langchain/core",
28366
+ {
28367
+ configure: channel({
28368
+ channelName: "CallbackManager.configure",
28369
+ kind: "sync-stream"
28370
+ }),
28371
+ configureSync: channel({
28372
+ channelName: "CallbackManager._configureSync",
28373
+ kind: "sync-stream"
28374
+ })
28375
+ },
28376
+ { instrumentationName: INSTRUMENTATION_NAMES.LANGCHAIN }
28377
+ );
27438
28378
 
27439
28379
  // src/instrumentation/plugins/langchain-plugin.ts
27440
28380
  var LangChainPlugin = class extends BasePlugin {
@@ -27522,20 +28462,24 @@ function isBraintrustHandler(handler) {
27522
28462
  }
27523
28463
 
27524
28464
  // src/instrumentation/plugins/langsmith-channels.ts
27525
- var langSmithChannels = defineChannels("langsmith", {
27526
- createRun: channel({
27527
- channelName: "Client.createRun",
27528
- kind: "async"
27529
- }),
27530
- updateRun: channel({
27531
- channelName: "Client.updateRun",
27532
- kind: "async"
27533
- }),
27534
- batchIngestRuns: channel({
27535
- channelName: "Client.batchIngestRuns",
27536
- kind: "async"
27537
- })
27538
- });
28465
+ var langSmithChannels = defineChannels(
28466
+ "langsmith",
28467
+ {
28468
+ createRun: channel({
28469
+ channelName: "Client.createRun",
28470
+ kind: "async"
28471
+ }),
28472
+ updateRun: channel({
28473
+ channelName: "Client.updateRun",
28474
+ kind: "async"
28475
+ }),
28476
+ batchIngestRuns: channel({
28477
+ channelName: "Client.batchIngestRuns",
28478
+ kind: "async"
28479
+ })
28480
+ },
28481
+ { instrumentationName: INSTRUMENTATION_NAMES.LANGSMITH }
28482
+ );
27539
28483
 
27540
28484
  // src/instrumentation/plugins/langsmith-plugin.ts
27541
28485
  var MAX_COMPLETED_RUNS = 1e4;
@@ -27699,19 +28643,24 @@ var LangSmithPlugin = class extends BasePlugin {
27699
28643
  const traceId = stringValue2(ownValue(run, "trace_id")) ?? id;
27700
28644
  const parentId = stringValue2(ownValue(run, "parent_run_id")) ?? stringValue2(ownValue(ownValue(run, "parent_run"), "id"));
27701
28645
  const startTime = timestampSeconds(ownValue(run, "start_time"));
27702
- return startSpan({
27703
- name: stringValue2(ownValue(run, "name")) ?? "LangSmith run",
27704
- spanId: id,
27705
- parentSpanIds: {
27706
- parentSpanIds: parentId ? [parentId] : [],
27707
- rootSpanId: traceId
27708
- },
27709
- spanAttributes: {
27710
- type: mapRunType(ownValue(run, "run_type"))
27711
- },
27712
- ...startTime === void 0 ? {} : { startTime },
27713
- event: { id }
27714
- });
28646
+ return startSpan(
28647
+ withSpanInstrumentationName(
28648
+ {
28649
+ name: stringValue2(ownValue(run, "name")) ?? "LangSmith run",
28650
+ spanId: id,
28651
+ parentSpanIds: {
28652
+ parentSpanIds: parentId ? [parentId] : [],
28653
+ rootSpanId: traceId
28654
+ },
28655
+ spanAttributes: {
28656
+ type: mapRunType(ownValue(run, "run_type"))
28657
+ },
28658
+ ...startTime === void 0 ? {} : { startTime },
28659
+ event: { id }
28660
+ },
28661
+ INSTRUMENTATION_NAMES.LANGSMITH
28662
+ )
28663
+ );
27715
28664
  }
27716
28665
  logRun(span, run, previous, includeOutput) {
27717
28666
  const inputs = preferOwnValue(run, previous, "inputs");
@@ -27969,7 +28918,8 @@ var piCodingAgentChannels = defineChannels(
27969
28918
  channelName: "AgentSession.prompt",
27970
28919
  kind: "async"
27971
28920
  })
27972
- }
28921
+ },
28922
+ { instrumentationName: INSTRUMENTATION_NAMES.PI_CODING_AGENT }
27973
28923
  );
27974
28924
 
27975
28925
  // src/instrumentation/plugins/pi-coding-agent-plugin.ts
@@ -28053,14 +29003,19 @@ function startPiPromptRun(event, onFinalize) {
28053
29003
  ...session.model?.id || agent.state?.model?.id ? { model: session.model?.id ?? agent.state?.model?.id } : {},
28054
29004
  ...event.moduleVersion ? { "pi_coding_agent.version": event.moduleVersion } : {}
28055
29005
  };
28056
- const span = startSpan({
28057
- event: {
28058
- input: extractPromptInput(event.arguments[0], event.arguments[1]),
28059
- metadata
28060
- },
28061
- name: "AgentSession.prompt",
28062
- spanAttributes: { type: "task" /* TASK */ }
28063
- });
29006
+ const span = startSpan(
29007
+ withSpanInstrumentationName(
29008
+ {
29009
+ event: {
29010
+ input: extractPromptInput(event.arguments[0], event.arguments[1]),
29011
+ metadata
29012
+ },
29013
+ name: "AgentSession.prompt",
29014
+ spanAttributes: { type: "task" /* TASK */ }
29015
+ },
29016
+ INSTRUMENTATION_NAMES.PI_CODING_AGENT
29017
+ )
29018
+ );
28064
29019
  const streamPatchState = installPiStreamPatch(agent);
28065
29020
  const options = event.arguments[1];
28066
29021
  const promptText = event.arguments[0];
@@ -28230,15 +29185,20 @@ async function startPiLlmSpan(state, model, context, options) {
28230
29185
  ...extractToolMetadata(context.tools),
28231
29186
  "pi_coding_agent.operation": "agent.streamFn"
28232
29187
  };
28233
- const span = startSpan({
28234
- event: {
28235
- input: processInputAttachments(normalizePiContextInput(context)),
28236
- metadata
28237
- },
28238
- name: getLlmSpanName(model),
28239
- parent: await state.span.export(),
28240
- spanAttributes: { type: "llm" /* LLM */ }
28241
- });
29188
+ const span = startSpan(
29189
+ withSpanInstrumentationName(
29190
+ {
29191
+ event: {
29192
+ input: processInputAttachments(normalizePiContextInput(context)),
29193
+ metadata
29194
+ },
29195
+ name: getLlmSpanName(model),
29196
+ parent: await state.span.export(),
29197
+ spanAttributes: { type: "llm" /* LLM */ }
29198
+ },
29199
+ INSTRUMENTATION_NAMES.PI_CODING_AGENT
29200
+ )
29201
+ );
28242
29202
  const llmState = {
28243
29203
  finalized: false,
28244
29204
  metadata,
@@ -28406,15 +29366,20 @@ async function startPiToolSpan(state, event) {
28406
29366
  "pi_coding_agent.tool.name": event.toolName
28407
29367
  };
28408
29368
  try {
28409
- const span = startSpan({
28410
- event: {
28411
- input: event.args,
28412
- metadata
28413
- },
28414
- name: event.toolName || "tool",
28415
- parent: await state.span.export(),
28416
- spanAttributes: { type: "tool" /* TOOL */ }
28417
- });
29369
+ const span = startSpan(
29370
+ withSpanInstrumentationName(
29371
+ {
29372
+ event: {
29373
+ input: event.args,
29374
+ metadata
29375
+ },
29376
+ name: event.toolName || "tool",
29377
+ parent: await state.span.export(),
29378
+ spanAttributes: { type: "tool" /* TOOL */ }
29379
+ },
29380
+ INSTRUMENTATION_NAMES.PI_CODING_AGENT
29381
+ )
29382
+ );
28418
29383
  state.activeToolSpans.set(event.toolCallId, {
28419
29384
  restoreAutoInstrumentation,
28420
29385
  span
@@ -28846,20 +29811,24 @@ function logInstrumentationError4(context, error) {
28846
29811
  }
28847
29812
 
28848
29813
  // src/instrumentation/plugins/strands-agent-sdk-channels.ts
28849
- var strandsAgentSDKChannels = defineChannels("@strands-agents/sdk", {
28850
- agentStream: channel({
28851
- channelName: "Agent.stream",
28852
- kind: "sync-stream"
28853
- }),
28854
- graphStream: channel({
28855
- channelName: "Graph.stream",
28856
- kind: "sync-stream"
28857
- }),
28858
- swarmStream: channel({
28859
- channelName: "Swarm.stream",
28860
- kind: "sync-stream"
28861
- })
28862
- });
29814
+ var strandsAgentSDKChannels = defineChannels(
29815
+ "@strands-agents/sdk",
29816
+ {
29817
+ agentStream: channel({
29818
+ channelName: "Agent.stream",
29819
+ kind: "sync-stream"
29820
+ }),
29821
+ graphStream: channel({
29822
+ channelName: "Graph.stream",
29823
+ kind: "sync-stream"
29824
+ }),
29825
+ swarmStream: channel({
29826
+ channelName: "Swarm.stream",
29827
+ kind: "sync-stream"
29828
+ })
29829
+ },
29830
+ { instrumentationName: INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK }
29831
+ );
28863
29832
 
28864
29833
  // src/instrumentation/plugins/strands-agent-sdk-plugin.ts
28865
29834
  var MAX_STRANDS_STRING_ATTACHMENT_CACHE_ENTRIES = 32;
@@ -29014,22 +29983,32 @@ function startAgentStream(event, activeChildParents) {
29014
29983
  );
29015
29984
  const span = parentSpan ? withCurrent(
29016
29985
  parentSpan,
29017
- () => startSpan({
29018
- event: {
29019
- input,
29020
- metadata
29986
+ () => startSpan(
29987
+ withSpanInstrumentationName(
29988
+ {
29989
+ event: {
29990
+ input,
29991
+ metadata
29992
+ },
29993
+ name: formatAgentSpanName(agent),
29994
+ spanAttributes: { type: "task" /* TASK */ }
29995
+ },
29996
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
29997
+ )
29998
+ )
29999
+ ) : startSpan(
30000
+ withSpanInstrumentationName(
30001
+ {
30002
+ event: {
30003
+ input,
30004
+ metadata
30005
+ },
30006
+ name: formatAgentSpanName(agent),
30007
+ spanAttributes: { type: "task" /* TASK */ }
29021
30008
  },
29022
- name: formatAgentSpanName(agent),
29023
- spanAttributes: { type: "task" /* TASK */ }
29024
- })
29025
- ) : startSpan({
29026
- event: {
29027
- input,
29028
- metadata
29029
- },
29030
- name: formatAgentSpanName(agent),
29031
- spanAttributes: { type: "task" /* TASK */ }
29032
- });
30009
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
30010
+ )
30011
+ );
29033
30012
  return {
29034
30013
  activeTools: /* @__PURE__ */ new Map(),
29035
30014
  attachmentCache,
@@ -29051,22 +30030,32 @@ function startMultiAgentStream(event, operation, activeChildParents) {
29051
30030
  const input = processStrandsInputAttachments(event.arguments[0]);
29052
30031
  const span = parentSpan ? withCurrent(
29053
30032
  parentSpan,
29054
- () => startSpan({
29055
- event: {
29056
- input,
29057
- metadata
30033
+ () => startSpan(
30034
+ withSpanInstrumentationName(
30035
+ {
30036
+ event: {
30037
+ input,
30038
+ metadata
30039
+ },
30040
+ name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
30041
+ spanAttributes: { type: "task" /* TASK */ }
30042
+ },
30043
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
30044
+ )
30045
+ )
30046
+ ) : startSpan(
30047
+ withSpanInstrumentationName(
30048
+ {
30049
+ event: {
30050
+ input,
30051
+ metadata
30052
+ },
30053
+ name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
30054
+ spanAttributes: { type: "task" /* TASK */ }
29058
30055
  },
29059
- name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
29060
- spanAttributes: { type: "task" /* TASK */ }
29061
- })
29062
- ) : startSpan({
29063
- event: {
29064
- input,
29065
- metadata
29066
- },
29067
- name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
29068
- spanAttributes: { type: "task" /* TASK */ }
29069
- });
30056
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
30057
+ )
30058
+ );
29070
30059
  return {
29071
30060
  activeNodes: /* @__PURE__ */ new Map(),
29072
30061
  finalized: false,
@@ -29168,17 +30157,22 @@ function startModelSpan(state, event) {
29168
30157
  };
29169
30158
  const span = withCurrent(
29170
30159
  state.span,
29171
- () => startSpan({
29172
- event: {
29173
- input: Array.isArray(event.agent?.messages) ? processStrandsInputAttachments(
29174
- event.agent.messages,
29175
- state.attachmentCache
29176
- ) : void 0,
29177
- metadata
29178
- },
29179
- name: formatModelSpanName(model),
29180
- spanAttributes: { type: "llm" /* LLM */ }
29181
- })
30160
+ () => startSpan(
30161
+ withSpanInstrumentationName(
30162
+ {
30163
+ event: {
30164
+ input: Array.isArray(event.agent?.messages) ? processStrandsInputAttachments(
30165
+ event.agent.messages,
30166
+ state.attachmentCache
30167
+ ) : void 0,
30168
+ metadata
30169
+ },
30170
+ name: formatModelSpanName(model),
30171
+ spanAttributes: { type: "llm" /* LLM */ }
30172
+ },
30173
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
30174
+ )
30175
+ )
29182
30176
  );
29183
30177
  state.activeModel = {
29184
30178
  metadata,
@@ -29230,20 +30224,25 @@ function startToolSpan2(state, event) {
29230
30224
  const name = extractToolName3(toolUse, event.tool);
29231
30225
  const span = withCurrent(
29232
30226
  state.span,
29233
- () => startSpan({
29234
- event: {
29235
- input: toolUse?.input,
29236
- metadata: {
29237
- "gen_ai.tool.call.id": toolUse?.toolUseId,
29238
- "gen_ai.tool.name": name,
29239
- "strands.operation": "tool.call",
29240
- "strands.tool.name": name,
29241
- provider: "strands"
29242
- }
29243
- },
29244
- name: `tool: ${name}`,
29245
- spanAttributes: { type: "tool" /* TOOL */ }
29246
- })
30227
+ () => startSpan(
30228
+ withSpanInstrumentationName(
30229
+ {
30230
+ event: {
30231
+ input: toolUse?.input,
30232
+ metadata: {
30233
+ "gen_ai.tool.call.id": toolUse?.toolUseId,
30234
+ "gen_ai.tool.name": name,
30235
+ "strands.operation": "tool.call",
30236
+ "strands.tool.name": name,
30237
+ provider: "strands"
30238
+ }
30239
+ },
30240
+ name: `tool: ${name}`,
30241
+ spanAttributes: { type: "tool" /* TOOL */ }
30242
+ },
30243
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
30244
+ )
30245
+ )
29247
30246
  );
29248
30247
  state.activeTools.set(key, {
29249
30248
  span,
@@ -29314,11 +30313,16 @@ function startNodeSpan(state, event, activeChildParents) {
29314
30313
  };
29315
30314
  const span = withCurrent(
29316
30315
  state.span,
29317
- () => startSpan({
29318
- event: { metadata },
29319
- name: `node: ${nodeId}`,
29320
- spanAttributes: { type: "task" /* TASK */ }
29321
- })
30316
+ () => startSpan(
30317
+ withSpanInstrumentationName(
30318
+ {
30319
+ event: { metadata },
30320
+ name: `node: ${nodeId}`,
30321
+ spanAttributes: { type: "task" /* TASK */ }
30322
+ },
30323
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
30324
+ )
30325
+ )
29322
30326
  );
29323
30327
  const nodeState = {
29324
30328
  ...child ? { child } : {},
@@ -30132,7 +31136,12 @@ var EveBridge = class {
30132
31136
  };
30133
31137
  const span = withCurrent(
30134
31138
  NOOP_SPAN,
30135
- () => _internalStartSpanWithInitialMerge({ ...args, startTime })
31139
+ () => _internalStartSpanWithInitialMerge(
31140
+ withSpanInstrumentationName(
31141
+ { ...args, startTime },
31142
+ INSTRUMENTATION_NAMES.EVE
31143
+ )
31144
+ )
30136
31145
  );
30137
31146
  if (typeof rowId !== "string") {
30138
31147
  return span;