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
@@ -5142,7 +5142,51 @@ var SpanCache = class {
5142
5142
  };
5143
5143
 
5144
5144
  // src/span-origin.ts
5145
- var SDK_VERSION = true ? "3.24.0" : "0.0.0";
5145
+ var INSTRUMENTATION_NAMES = {
5146
+ AI_SDK: "ai-sdk",
5147
+ ANTHROPIC: "anthropic",
5148
+ BEDROCK_RUNTIME: "bedrock-runtime",
5149
+ BRAINTRUST_JS_LOGGER: "braintrust-js-logger",
5150
+ CLAUDE_AGENT_SDK: "claude-agent-sdk",
5151
+ COHERE: "cohere",
5152
+ CURSOR_SDK: "cursor-sdk",
5153
+ EVE: "eve",
5154
+ FLUE: "flue",
5155
+ GENKIT: "genkit",
5156
+ GITHUB_COPILOT: "github-copilot",
5157
+ GOOGLE_ADK: "google-adk",
5158
+ GOOGLE_GENAI: "google-genai",
5159
+ GROQ: "groq",
5160
+ HUGGINGFACE: "huggingface",
5161
+ LANGCHAIN: "langchain",
5162
+ LANGSMITH: "langsmith",
5163
+ MASTRA: "mastra",
5164
+ MISTRAL: "mistral",
5165
+ OPENAI: "openai",
5166
+ OPENAI_AGENTS: "openai-agents",
5167
+ OPENAI_CODEX: "openai-codex",
5168
+ OPENROUTER: "openrouter",
5169
+ OPENROUTER_AGENT: "openrouter-agent",
5170
+ PI_CODING_AGENT: "pi-coding-agent",
5171
+ STRANDS_AGENT_SDK: "strands-agent-sdk"
5172
+ };
5173
+ var INTERNAL_SPAN_INSTRUMENTATION_NAME = /* @__PURE__ */ Symbol.for(
5174
+ "braintrust.spanInstrumentationName"
5175
+ );
5176
+ var SDK_VERSION = true ? "3.25.0" : "0.0.0";
5177
+ function withSpanInstrumentationName(args, instrumentationName) {
5178
+ return {
5179
+ ...args,
5180
+ [INTERNAL_SPAN_INSTRUMENTATION_NAME]: instrumentationName
5181
+ };
5182
+ }
5183
+ function getSpanInstrumentationName(args) {
5184
+ if (typeof args !== "object" || args === null) {
5185
+ return void 0;
5186
+ }
5187
+ const value = args[INTERNAL_SPAN_INSTRUMENTATION_NAME];
5188
+ return isSpanInstrumentationName(value) ? value : void 0;
5189
+ }
5146
5190
  function detectSpanOriginEnvironment(explicit) {
5147
5191
  if (explicit) return explicit;
5148
5192
  const envType = isomorph_default.getEnv("BRAINTRUST_ENVIRONMENT_TYPE");
@@ -5214,6 +5258,9 @@ function mergeSpanOriginContext(context, instrumentationName, environment) {
5214
5258
  };
5215
5259
  return next;
5216
5260
  }
5261
+ function isSpanInstrumentationName(value) {
5262
+ return Object.values(INSTRUMENTATION_NAMES).some((name) => name === value);
5263
+ }
5217
5264
  function firstPresent(entries) {
5218
5265
  return entries.find(([key]) => Boolean(isomorph_default.getEnv(key)))?.[1];
5219
5266
  }
@@ -5508,6 +5555,7 @@ var BraintrustState = class _BraintrustState {
5508
5555
  });
5509
5556
  this.spanCache = new SpanCache({ disabled: loginParams.disableSpanCache });
5510
5557
  this.spanOriginEnvironment = detectSpanOriginEnvironment();
5558
+ this._internalSetTraceContextSigningSecret(loginParams.apiKey);
5511
5559
  }
5512
5560
  loginParams;
5513
5561
  id;
@@ -5545,6 +5593,18 @@ var BraintrustState = class _BraintrustState {
5545
5593
  _contextManager = null;
5546
5594
  _otelFlushCallback = null;
5547
5595
  spanOriginEnvironment;
5596
+ traceContextSigningSecret;
5597
+ /** @internal */
5598
+ _internalSetTraceContextSigningSecret(secret) {
5599
+ const normalizedSecret = secret?.trim();
5600
+ if (normalizedSecret) {
5601
+ this.traceContextSigningSecret = normalizedSecret;
5602
+ }
5603
+ }
5604
+ /** @internal */
5605
+ _internalGetTraceContextSigningSecret() {
5606
+ return (this.traceContextSigningSecret ?? this.loginToken ?? isomorph_default.getEnv("BRAINTRUST_API_KEY"))?.trim();
5607
+ }
5548
5608
  resetLoginInfo() {
5549
5609
  this.appUrl = null;
5550
5610
  this.appPublicUrl = null;
@@ -5605,6 +5665,7 @@ var BraintrustState = class _BraintrustState {
5605
5665
  this.gitMetadataSettings = other.gitMetadataSettings;
5606
5666
  this.debugLogLevel = other.debugLogLevel;
5607
5667
  this.debugLogLevelConfigured = other.debugLogLevelConfigured;
5668
+ this.traceContextSigningSecret = other.traceContextSigningSecret;
5608
5669
  setGlobalDebugLogLevel(
5609
5670
  this.debugLogLevelConfigured ? this.debugLogLevel ?? false : void 0
5610
5671
  );
@@ -5692,6 +5753,7 @@ var BraintrustState = class _BraintrustState {
5692
5753
  return this.debugLogLevelConfigured;
5693
5754
  }
5694
5755
  async login(loginParams) {
5756
+ this._internalSetTraceContextSigningSecret(loginParams.apiKey);
5695
5757
  this.setDebugLogLevel(loginParams.debugLogLevel);
5696
5758
  if (this.apiUrl && !loginParams.forceLogin) {
5697
5759
  return;
@@ -6356,6 +6418,28 @@ function updateSpanImpl({
6356
6418
  }));
6357
6419
  state.bgLogger().log([record]);
6358
6420
  }
6421
+ function updateSpan({
6422
+ exported,
6423
+ state,
6424
+ ...event
6425
+ }) {
6426
+ const resolvedState = state ?? _globalState;
6427
+ const components = SpanComponentsV4.fromStr(exported);
6428
+ if (!components.data.row_id) {
6429
+ throw new Error("Exported span must have a row id");
6430
+ }
6431
+ updateSpanImpl({
6432
+ state: resolvedState,
6433
+ parentObjectType: components.data.object_type,
6434
+ parentObjectId: new LazyValue(
6435
+ spanComponentsToObjectIdLambda(resolvedState, components)
6436
+ ),
6437
+ id: components.data.row_id,
6438
+ root_span_id: components.data.root_span_id,
6439
+ span_id: components.data.span_id,
6440
+ event
6441
+ });
6442
+ }
6359
6443
  function spanComponentsToObjectIdLambda(state, components) {
6360
6444
  if (components.data.object_id) {
6361
6445
  const ret = components.data.object_id;
@@ -7442,6 +7526,7 @@ function init(projectOrOptions, optionalOptions) {
7442
7526
  throw new Error("Cannot open and update an experiment at the same time");
7443
7527
  }
7444
7528
  const state = stateArg ?? _globalState;
7529
+ state._internalSetTraceContextSigningSecret(apiKey);
7445
7530
  state.enforceQueueSizeLimit(false);
7446
7531
  if (open2) {
7447
7532
  if (isEmpty2(experiment)) {
@@ -7914,6 +7999,7 @@ function initLogger(options = {}) {
7914
7999
  project_id: projectId
7915
8000
  };
7916
8001
  const state = stateArg ?? _globalState;
8002
+ state._internalSetTraceContextSigningSecret(apiKey);
7917
8003
  state.setDebugLogLevel(debugLogLevel);
7918
8004
  state.spanOriginEnvironment = detectSpanOriginEnvironment(environment);
7919
8005
  state.enforceQueueSizeLimit(true);
@@ -8343,6 +8429,12 @@ function traced(callback, args) {
8343
8429
  function startSpan(args) {
8344
8430
  return startSpanAndIsLogger(args).span;
8345
8431
  }
8432
+ function _internalStartSpanWithInitialMerge(args) {
8433
+ return startSpanAndIsLogger({
8434
+ ...args,
8435
+ [INITIAL_SPAN_WRITE_AS_MERGE]: true
8436
+ }).span;
8437
+ }
8346
8438
  async function flush(options) {
8347
8439
  const state = options?.state ?? _globalState;
8348
8440
  return await state.bgLogger().flush();
@@ -8494,7 +8586,9 @@ function deepCopyEvent(event) {
8494
8586
  const ATTACHMENT_MARKER_KEY = "_bt_internal_saved_attachment_marker";
8495
8587
  const attachmentMarker = ++deepCopyEventMarkerCounter;
8496
8588
  const serialized = JSON.stringify(event, (_k, v) => {
8497
- if (v instanceof SpanImpl || v instanceof NoopSpan) {
8589
+ if (v instanceof Error) {
8590
+ return v.message;
8591
+ } else if (v instanceof SpanImpl || v instanceof NoopSpan) {
8498
8592
  return `<span>`;
8499
8593
  } else if (v instanceof Experiment2) {
8500
8594
  return `<experiment>`;
@@ -9162,6 +9256,7 @@ var SpanImpl = class _SpanImpl {
9162
9256
  constructor(args) {
9163
9257
  this._state = args.state;
9164
9258
  this._propagatedState = args.propagatedState;
9259
+ const instrumentationName = getSpanInstrumentationName(args) ?? INSTRUMENTATION_NAMES.BRAINTRUST_JS_LOGGER;
9165
9260
  const spanAttributes = args.spanAttributes ?? {};
9166
9261
  const rawEvent = args.event ?? {};
9167
9262
  const type = args.type ?? (args.parentSpanIds ? void 0 : args.defaultRootType);
@@ -9193,7 +9288,7 @@ var SpanImpl = class _SpanImpl {
9193
9288
  },
9194
9289
  context: mergeSpanOriginContext(
9195
9290
  { ...callerLocation },
9196
- "braintrust-js-logger",
9291
+ instrumentationName,
9197
9292
  this._state.spanOriginEnvironment
9198
9293
  ),
9199
9294
  span_attributes: {
@@ -11079,15 +11174,25 @@ function hasChoices(value) {
11079
11174
  function normalizeMetadata(metadata) {
11080
11175
  return isObject(metadata) ? metadata : void 0;
11081
11176
  }
11082
- function startSpanForEvent(config, event, channelName) {
11177
+ function startSpanForEvent(config, event, channelName, instrumentationName) {
11083
11178
  const { name, spanAttributes, spanInfoMetadata } = buildStartSpanArgs(
11084
11179
  config,
11085
11180
  event
11086
11181
  );
11087
- const span = startSpan({
11088
- name,
11089
- spanAttributes
11090
- });
11182
+ const spanArgs = withSpanInstrumentationName(
11183
+ {
11184
+ name,
11185
+ spanAttributes
11186
+ },
11187
+ instrumentationName
11188
+ );
11189
+ let span;
11190
+ try {
11191
+ span = config.startSpan?.(spanArgs) ?? startSpan(spanArgs);
11192
+ } catch (error) {
11193
+ debugLogger.error(`Error starting span for ${channelName}:`, error);
11194
+ span = startSpan(spanArgs);
11195
+ }
11091
11196
  const startTime = getCurrentUnixTimestamp();
11092
11197
  try {
11093
11198
  const { input, metadata } = config.extractInput(
@@ -11118,7 +11223,7 @@ function shouldTraceEvent(config, event, channelName) {
11118
11223
  return true;
11119
11224
  }
11120
11225
  }
11121
- function ensureSpanStateForEvent(states, config, event, channelName) {
11226
+ function ensureSpanStateForEvent(states, config, event, channelName, instrumentationName) {
11122
11227
  const key = event;
11123
11228
  const existing = states.get(key);
11124
11229
  if (existing) {
@@ -11127,11 +11232,16 @@ function ensureSpanStateForEvent(states, config, event, channelName) {
11127
11232
  if (!shouldTraceEvent(config, event, channelName)) {
11128
11233
  return void 0;
11129
11234
  }
11130
- const created = startSpanForEvent(config, event, channelName);
11235
+ const created = startSpanForEvent(
11236
+ config,
11237
+ event,
11238
+ channelName,
11239
+ instrumentationName
11240
+ );
11131
11241
  states.set(key, created);
11132
11242
  return created;
11133
11243
  }
11134
- function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelName) {
11244
+ function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelName, instrumentationName) {
11135
11245
  const state = _internalGetGlobalState();
11136
11246
  const startChannel = tracingChannel2.start;
11137
11247
  const contextManager = state?.contextManager;
@@ -11149,7 +11259,8 @@ function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelNam
11149
11259
  states,
11150
11260
  config,
11151
11261
  event,
11152
- channelName
11262
+ channelName,
11263
+ instrumentationName
11153
11264
  );
11154
11265
  return spanState ? contextManager.wrapSpanForStore(spanState.span) : currentSpanStore.getStore();
11155
11266
  }
@@ -11158,15 +11269,21 @@ function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelNam
11158
11269
  startChannel.unbindStore(currentSpanStore);
11159
11270
  };
11160
11271
  }
11161
- function logErrorAndEnd(states, event) {
11272
+ function logErrorAndEnd(states, event, channelName) {
11162
11273
  const spanData = states.get(event);
11163
11274
  if (!spanData) {
11164
11275
  return;
11165
11276
  }
11166
- spanData.span.log({
11167
- error: event.error.message
11168
- });
11169
- spanData.span.end();
11277
+ try {
11278
+ spanData.span.log({ error: event.error });
11279
+ } catch (error) {
11280
+ debugLogger.error(`Error logging failure for ${channelName}:`, error);
11281
+ }
11282
+ try {
11283
+ spanData.span.end();
11284
+ } catch (error) {
11285
+ debugLogger.error(`Error ending span for ${channelName}:`, error);
11286
+ }
11170
11287
  states.delete(event);
11171
11288
  }
11172
11289
  function runStreamingCompletionHook(args) {
@@ -11216,7 +11333,8 @@ function traceAsyncChannel(channel2, config) {
11216
11333
  tracingChannel2,
11217
11334
  states,
11218
11335
  config,
11219
- channelName
11336
+ channelName,
11337
+ channel2.instrumentationName
11220
11338
  );
11221
11339
  const handlers = {
11222
11340
  start: (event) => {
@@ -11227,7 +11345,8 @@ function traceAsyncChannel(channel2, config) {
11227
11345
  states,
11228
11346
  config,
11229
11347
  event,
11230
- channelName
11348
+ channelName,
11349
+ channel2.instrumentationName
11231
11350
  );
11232
11351
  },
11233
11352
  asyncEnd: (event) => {
@@ -11264,7 +11383,7 @@ function traceAsyncChannel(channel2, config) {
11264
11383
  }
11265
11384
  },
11266
11385
  error: (event) => {
11267
- logErrorAndEnd(states, event);
11386
+ logErrorAndEnd(states, event, channelName);
11268
11387
  }
11269
11388
  };
11270
11389
  tracingChannel2.subscribe(handlers);
@@ -11281,7 +11400,8 @@ function traceStreamingChannel(channel2, config) {
11281
11400
  tracingChannel2,
11282
11401
  states,
11283
11402
  config,
11284
- channelName
11403
+ channelName,
11404
+ channel2.instrumentationName
11285
11405
  );
11286
11406
  const handlers = {
11287
11407
  start: (event) => {
@@ -11292,7 +11412,8 @@ function traceStreamingChannel(channel2, config) {
11292
11412
  states,
11293
11413
  config,
11294
11414
  event,
11295
- channelName
11415
+ channelName,
11416
+ channel2.instrumentationName
11296
11417
  );
11297
11418
  },
11298
11419
  asyncEnd: (event) => {
@@ -11311,6 +11432,7 @@ function traceStreamingChannel(channel2, config) {
11311
11432
  }
11312
11433
  },
11313
11434
  onComplete: (chunks) => {
11435
+ let completion2;
11314
11436
  try {
11315
11437
  let output;
11316
11438
  let metrics;
@@ -11341,18 +11463,11 @@ function traceStreamingChannel(channel2, config) {
11341
11463
  } else if (metrics.time_to_first_token === void 0 && chunks.length > 0) {
11342
11464
  metrics.time_to_first_token = getCurrentUnixTimestamp() - startTime;
11343
11465
  }
11344
- runStreamingCompletionHook({
11345
- channelName,
11346
- chunks,
11347
- config,
11348
- endEvent: asyncEndEvent,
11466
+ completion2 = {
11349
11467
  ...metadata !== void 0 ? { metadata } : {},
11350
11468
  metrics,
11351
- output,
11352
- result: asyncEndEvent.result,
11353
- span,
11354
- startTime
11355
- });
11469
+ output
11470
+ };
11356
11471
  span.log({
11357
11472
  output,
11358
11473
  ...metadata !== void 0 ? { metadata } : {},
@@ -11364,11 +11479,49 @@ function traceStreamingChannel(channel2, config) {
11364
11479
  error
11365
11480
  );
11366
11481
  } finally {
11367
- span.end();
11482
+ try {
11483
+ span.end();
11484
+ } catch (error) {
11485
+ debugLogger.error(
11486
+ `Error ending span for ${channelName}:`,
11487
+ error
11488
+ );
11489
+ }
11368
11490
  states.delete(event);
11369
11491
  }
11492
+ if (completion2) {
11493
+ runStreamingCompletionHook({
11494
+ channelName,
11495
+ chunks,
11496
+ config,
11497
+ endEvent: asyncEndEvent,
11498
+ ...completion2.metadata !== void 0 ? { metadata: completion2.metadata } : {},
11499
+ metrics: completion2.metrics,
11500
+ output: completion2.output,
11501
+ result: asyncEndEvent.result,
11502
+ span,
11503
+ startTime
11504
+ });
11505
+ }
11370
11506
  },
11371
11507
  onError: (error) => {
11508
+ try {
11509
+ span.log({ error });
11510
+ } catch (loggingError) {
11511
+ debugLogger.error(
11512
+ `Error logging failure for ${channelName}:`,
11513
+ loggingError
11514
+ );
11515
+ }
11516
+ try {
11517
+ span.end();
11518
+ } catch (endingError) {
11519
+ debugLogger.error(
11520
+ `Error ending span for ${channelName}:`,
11521
+ endingError
11522
+ );
11523
+ }
11524
+ states.delete(event);
11372
11525
  runStreamingErrorHook({
11373
11526
  channelName,
11374
11527
  config,
@@ -11377,11 +11530,6 @@ function traceStreamingChannel(channel2, config) {
11377
11530
  span,
11378
11531
  startTime
11379
11532
  });
11380
- span.log({
11381
- error: error.message
11382
- });
11383
- span.end();
11384
- states.delete(event);
11385
11533
  }
11386
11534
  });
11387
11535
  return;
@@ -11396,6 +11544,7 @@ function traceStreamingChannel(channel2, config) {
11396
11544
  states.delete(event);
11397
11545
  return;
11398
11546
  }
11547
+ let completion;
11399
11548
  try {
11400
11549
  const output = config.extractOutput(
11401
11550
  asyncEndEvent.result,
@@ -11410,17 +11559,11 @@ function traceStreamingChannel(channel2, config) {
11410
11559
  asyncEndEvent.result,
11411
11560
  asyncEndEvent
11412
11561
  );
11413
- runStreamingCompletionHook({
11414
- channelName,
11415
- config,
11416
- endEvent: asyncEndEvent,
11562
+ completion = {
11417
11563
  ...normalizeMetadata(metadata) !== void 0 ? { metadata: normalizeMetadata(metadata) } : {},
11418
11564
  metrics,
11419
- output,
11420
- result: asyncEndEvent.result,
11421
- span,
11422
- startTime
11423
- });
11565
+ output
11566
+ };
11424
11567
  span.log({
11425
11568
  output,
11426
11569
  ...normalizeMetadata(metadata) !== void 0 ? { metadata: normalizeMetadata(metadata) } : {},
@@ -11429,12 +11572,30 @@ function traceStreamingChannel(channel2, config) {
11429
11572
  } catch (error) {
11430
11573
  debugLogger.error(`Error extracting output for ${channelName}:`, error);
11431
11574
  } finally {
11432
- span.end();
11575
+ try {
11576
+ span.end();
11577
+ } catch (error) {
11578
+ debugLogger.error(`Error ending span for ${channelName}:`, error);
11579
+ }
11433
11580
  states.delete(event);
11434
11581
  }
11582
+ if (completion) {
11583
+ runStreamingCompletionHook({
11584
+ channelName,
11585
+ config,
11586
+ endEvent: asyncEndEvent,
11587
+ ...completion.metadata !== void 0 ? { metadata: completion.metadata } : {},
11588
+ metrics: completion.metrics,
11589
+ output: completion.output,
11590
+ result: asyncEndEvent.result,
11591
+ span,
11592
+ startTime
11593
+ });
11594
+ }
11435
11595
  },
11436
11596
  error: (event) => {
11437
11597
  const spanData = states.get(event);
11598
+ logErrorAndEnd(states, event, channelName);
11438
11599
  if (spanData) {
11439
11600
  runStreamingErrorHook({
11440
11601
  channelName,
@@ -11445,7 +11606,6 @@ function traceStreamingChannel(channel2, config) {
11445
11606
  startTime: spanData.startTime
11446
11607
  });
11447
11608
  }
11448
- logErrorAndEnd(states, event);
11449
11609
  }
11450
11610
  };
11451
11611
  tracingChannel2.subscribe(handlers);
@@ -11462,7 +11622,8 @@ function traceSyncStreamChannel(channel2, config) {
11462
11622
  tracingChannel2,
11463
11623
  states,
11464
11624
  config,
11465
- channelName
11625
+ channelName,
11626
+ channel2.instrumentationName
11466
11627
  );
11467
11628
  const handlers = {
11468
11629
  start: (event) => {
@@ -11473,7 +11634,8 @@ function traceSyncStreamChannel(channel2, config) {
11473
11634
  states,
11474
11635
  config,
11475
11636
  event,
11476
- channelName
11637
+ channelName,
11638
+ channel2.instrumentationName
11477
11639
  );
11478
11640
  },
11479
11641
  end: (event) => {
@@ -11567,7 +11729,7 @@ function traceSyncStreamChannel(channel2, config) {
11567
11729
  handleResolvedResult(endEvent.result);
11568
11730
  },
11569
11731
  error: (event) => {
11570
- logErrorAndEnd(states, event);
11732
+ logErrorAndEnd(states, event, channelName);
11571
11733
  }
11572
11734
  };
11573
11735
  tracingChannel2.subscribe(handlers);
@@ -11746,7 +11908,8 @@ function processInputAttachments(input) {
11746
11908
  function channel(spec) {
11747
11909
  return spec;
11748
11910
  }
11749
- function defineChannels(pkg, channels) {
11911
+ function defineChannels(pkg, channels, options) {
11912
+ const { instrumentationName } = options;
11750
11913
  return Object.fromEntries(
11751
11914
  Object.entries(channels).map(([key, spec]) => {
11752
11915
  const fullChannelName = `orchestrion:${pkg}:${spec.channelName}`;
@@ -11759,6 +11922,7 @@ function defineChannels(pkg, channels) {
11759
11922
  key,
11760
11923
  {
11761
11924
  ...asyncSpec,
11925
+ instrumentationName,
11762
11926
  tracingChannel: tracingChannel3,
11763
11927
  tracePromise: (fn, context) => tracingChannel3().tracePromise(
11764
11928
  fn,
@@ -11776,6 +11940,7 @@ function defineChannels(pkg, channels) {
11776
11940
  key,
11777
11941
  {
11778
11942
  ...syncSpec,
11943
+ instrumentationName,
11779
11944
  tracingChannel: tracingChannel2,
11780
11945
  traceSync: (fn, context) => tracingChannel2().traceSync(
11781
11946
  fn,
@@ -11789,44 +11954,48 @@ function defineChannels(pkg, channels) {
11789
11954
  }
11790
11955
 
11791
11956
  // src/instrumentation/plugins/openai-channels.ts
11792
- var openAIChannels = defineChannels("openai", {
11793
- chatCompletionsCreate: channel({
11794
- channelName: "chat.completions.create",
11795
- kind: "async"
11796
- }),
11797
- embeddingsCreate: channel({
11798
- channelName: "embeddings.create",
11799
- kind: "async"
11800
- }),
11801
- betaChatCompletionsParse: channel({
11802
- channelName: "beta.chat.completions.parse",
11803
- kind: "async"
11804
- }),
11805
- betaChatCompletionsStream: channel({
11806
- channelName: "beta.chat.completions.stream",
11807
- kind: "sync-stream"
11808
- }),
11809
- moderationsCreate: channel({
11810
- channelName: "moderations.create",
11811
- kind: "async"
11812
- }),
11813
- responsesCreate: channel({
11814
- channelName: "responses.create",
11815
- kind: "async"
11816
- }),
11817
- responsesStream: channel({
11818
- channelName: "responses.stream",
11819
- kind: "sync-stream"
11820
- }),
11821
- responsesParse: channel({
11822
- channelName: "responses.parse",
11823
- kind: "async"
11824
- }),
11825
- responsesCompact: channel({
11826
- channelName: "responses.compact",
11827
- kind: "async"
11828
- })
11829
- });
11957
+ var openAIChannels = defineChannels(
11958
+ "openai",
11959
+ {
11960
+ chatCompletionsCreate: channel({
11961
+ channelName: "chat.completions.create",
11962
+ kind: "async"
11963
+ }),
11964
+ embeddingsCreate: channel({
11965
+ channelName: "embeddings.create",
11966
+ kind: "async"
11967
+ }),
11968
+ betaChatCompletionsParse: channel({
11969
+ channelName: "beta.chat.completions.parse",
11970
+ kind: "async"
11971
+ }),
11972
+ betaChatCompletionsStream: channel({
11973
+ channelName: "beta.chat.completions.stream",
11974
+ kind: "sync-stream"
11975
+ }),
11976
+ moderationsCreate: channel({
11977
+ channelName: "moderations.create",
11978
+ kind: "async"
11979
+ }),
11980
+ responsesCreate: channel({
11981
+ channelName: "responses.create",
11982
+ kind: "async"
11983
+ }),
11984
+ responsesStream: channel({
11985
+ channelName: "responses.stream",
11986
+ kind: "sync-stream"
11987
+ }),
11988
+ responsesParse: channel({
11989
+ channelName: "responses.parse",
11990
+ kind: "async"
11991
+ }),
11992
+ responsesCompact: channel({
11993
+ channelName: "responses.compact",
11994
+ kind: "async"
11995
+ })
11996
+ },
11997
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENAI }
11998
+ );
11830
11999
 
11831
12000
  // src/openai-utils.ts
11832
12001
  var BRAINTRUST_CACHED_STREAM_METRIC = "__braintrust_cached_metric";
@@ -12341,16 +12510,20 @@ function aggregateResponseStreamEvents(chunks, _streamResult, endEvent) {
12341
12510
  }
12342
12511
 
12343
12512
  // src/instrumentation/plugins/openai-codex-channels.ts
12344
- var openAICodexChannels = defineChannels("@openai/codex-sdk", {
12345
- run: channel({
12346
- channelName: "Thread.run",
12347
- kind: "async"
12348
- }),
12349
- runStreamed: channel({
12350
- channelName: "Thread.runStreamed",
12351
- kind: "async"
12352
- })
12353
- });
12513
+ var openAICodexChannels = defineChannels(
12514
+ "@openai/codex-sdk",
12515
+ {
12516
+ run: channel({
12517
+ channelName: "Thread.run",
12518
+ kind: "async"
12519
+ }),
12520
+ runStreamed: channel({
12521
+ channelName: "Thread.runStreamed",
12522
+ kind: "async"
12523
+ })
12524
+ },
12525
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENAI_CODEX }
12526
+ );
12354
12527
 
12355
12528
  // src/instrumentation/plugins/openai-codex-plugin.ts
12356
12529
  var PATCHED_STREAMED_TURN = /* @__PURE__ */ Symbol.for(
@@ -12438,10 +12611,15 @@ function startCodexRun(event, operation) {
12438
12611
  provider: "openai",
12439
12612
  ...event.moduleVersion ? { "openai_codex.version": event.moduleVersion } : {}
12440
12613
  };
12441
- const span = startSpan({
12442
- name: "OpenAI Codex",
12443
- spanAttributes: { type: "task" /* TASK */ }
12444
- });
12614
+ const span = startSpan(
12615
+ withSpanInstrumentationName(
12616
+ {
12617
+ name: "OpenAI Codex",
12618
+ spanAttributes: { type: "task" /* TASK */ }
12619
+ },
12620
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
12621
+ )
12622
+ );
12445
12623
  const startTime = getCurrentUnixTimestamp();
12446
12624
  safeLog(span, {
12447
12625
  input: sanitizedInput,
@@ -12590,7 +12768,12 @@ async function createCompletedItemSpan(state, item) {
12590
12768
  if (!spanArgs) {
12591
12769
  return;
12592
12770
  }
12593
- const span = startSpan(spanArgs.start);
12771
+ const span = startSpan(
12772
+ withSpanInstrumentationName(
12773
+ spanArgs.start,
12774
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
12775
+ )
12776
+ );
12594
12777
  safeLog(span, spanArgs.end);
12595
12778
  span.end();
12596
12779
  }
@@ -12632,15 +12815,20 @@ async function ensureActiveLlmSpan(state) {
12632
12815
  ...state.metadata["openai_codex.thread_id"] ? { "openai_codex.thread_id": state.metadata["openai_codex.thread_id"] } : {},
12633
12816
  "openai_codex.llm_sequence": sequence
12634
12817
  };
12635
- const span = startSpan({
12636
- event: {
12637
- ...sequence === 1 ? { input: state.input } : {},
12638
- metadata
12639
- },
12640
- name: "OpenAI Codex LLM",
12641
- parent: await state.span.export(),
12642
- spanAttributes: { type: "llm" /* LLM */ }
12643
- });
12818
+ const span = startSpan(
12819
+ withSpanInstrumentationName(
12820
+ {
12821
+ event: {
12822
+ ...sequence === 1 ? { input: state.input } : {},
12823
+ metadata
12824
+ },
12825
+ name: "OpenAI Codex LLM",
12826
+ parent: await state.span.export(),
12827
+ spanAttributes: { type: "llm" /* LLM */ }
12828
+ },
12829
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
12830
+ )
12831
+ );
12644
12832
  state.activeLlmSpan = {
12645
12833
  anonymousMessages: [],
12646
12834
  anonymousReasoning: [],
@@ -12686,7 +12874,15 @@ async function startCodexItemSpan(state, item) {
12686
12874
  if (!spanArgs) {
12687
12875
  return;
12688
12876
  }
12689
- state.activeItemSpans.set(itemId, startSpan(spanArgs.start));
12877
+ state.activeItemSpans.set(
12878
+ itemId,
12879
+ startSpan(
12880
+ withSpanInstrumentationName(
12881
+ spanArgs.start,
12882
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
12883
+ )
12884
+ )
12885
+ );
12690
12886
  }
12691
12887
  function updateCodexItem(state, item) {
12692
12888
  if (item.type === "agent_message" && typeof item.text === "string") {
@@ -12996,20 +13192,24 @@ function extractAnthropicCacheTokens(cacheReadTokens = 0, cacheCreationTokens =
12996
13192
  }
12997
13193
 
12998
13194
  // src/instrumentation/plugins/anthropic-channels.ts
12999
- var anthropicChannels = defineChannels("@anthropic-ai/sdk", {
13000
- messagesCreate: channel({
13001
- channelName: "messages.create",
13002
- kind: "async"
13003
- }),
13004
- betaMessagesCreate: channel({
13005
- channelName: "beta.messages.create",
13006
- kind: "async"
13007
- }),
13008
- betaMessagesToolRunner: channel({
13009
- channelName: "beta.messages.toolRunner",
13010
- kind: "sync-stream"
13011
- })
13012
- });
13195
+ var anthropicChannels = defineChannels(
13196
+ "@anthropic-ai/sdk",
13197
+ {
13198
+ messagesCreate: channel({
13199
+ channelName: "messages.create",
13200
+ kind: "async"
13201
+ }),
13202
+ betaMessagesCreate: channel({
13203
+ channelName: "beta.messages.create",
13204
+ kind: "async"
13205
+ }),
13206
+ betaMessagesToolRunner: channel({
13207
+ channelName: "beta.messages.toolRunner",
13208
+ kind: "sync-stream"
13209
+ })
13210
+ },
13211
+ { instrumentationName: INSTRUMENTATION_NAMES.ANTHROPIC }
13212
+ );
13013
13213
 
13014
13214
  // src/instrumentation/plugins/anthropic-plugin.ts
13015
13215
  var ANTHROPIC_TOOL_RUNNER_TOOL_WRAPPED = /* @__PURE__ */ Symbol.for(
@@ -13082,12 +13282,17 @@ var AnthropicPlugin = class extends BasePlugin {
13082
13282
  return;
13083
13283
  }
13084
13284
  const params = event.arguments[0] ?? {};
13085
- const span = startSpan({
13086
- name: "anthropic.beta.messages.toolRunner",
13087
- spanAttributes: {
13088
- type: "task" /* TASK */
13089
- }
13090
- });
13285
+ const span = startSpan(
13286
+ withSpanInstrumentationName(
13287
+ {
13288
+ name: "anthropic.beta.messages.toolRunner",
13289
+ spanAttributes: {
13290
+ type: "task" /* TASK */
13291
+ }
13292
+ },
13293
+ INSTRUMENTATION_NAMES.ANTHROPIC
13294
+ )
13295
+ );
13091
13296
  span.log({
13092
13297
  input: processAttachmentsInInput(
13093
13298
  coalesceInput(params.messages ?? [], params.system)
@@ -13228,19 +13433,22 @@ function wrapAnthropicToolRunnerTool(tool, index, state) {
13228
13433
  return finalizeError(error);
13229
13434
  }
13230
13435
  },
13231
- {
13232
- event: {
13233
- input: getAnthropicToolRunnerInput(args),
13234
- metadata: {
13235
- "gen_ai.tool.name": toolName,
13236
- provider: "anthropic"
13436
+ withSpanInstrumentationName(
13437
+ {
13438
+ event: {
13439
+ input: getAnthropicToolRunnerInput(args),
13440
+ metadata: {
13441
+ "gen_ai.tool.name": toolName,
13442
+ provider: "anthropic"
13443
+ }
13444
+ },
13445
+ name: `tool: ${toolName}`,
13446
+ spanAttributes: {
13447
+ type: "tool" /* TOOL */
13237
13448
  }
13238
13449
  },
13239
- name: `tool: ${toolName}`,
13240
- spanAttributes: {
13241
- type: "tool" /* TOOL */
13242
- }
13243
- }
13450
+ INSTRUMENTATION_NAMES.ANTHROPIC
13451
+ )
13244
13452
  );
13245
13453
  },
13246
13454
  writable: runDescriptor?.writable ?? true
@@ -13835,48 +14043,312 @@ function currentWorkflowAgentWrapperSpan() {
13835
14043
  return void 0;
13836
14044
  }
13837
14045
 
13838
- // src/wrappers/ai-sdk/telemetry.ts
13839
- function braintrustAISDKTelemetry() {
13840
- const operations = /* @__PURE__ */ new Map();
13841
- const operationKeysByCallId = /* @__PURE__ */ new Map();
13842
- const workflowOperationKeyStore = isomorph_default.newAsyncLocalStorage();
13843
- const modelSpans = /* @__PURE__ */ new Map();
13844
- const objectSpans = /* @__PURE__ */ new Map();
13845
- const embedSpans = /* @__PURE__ */ new Map();
13846
- const rerankSpans = /* @__PURE__ */ new Map();
13847
- const toolSpans = /* @__PURE__ */ new Map();
13848
- let workflowAgentOperationCounter = 0;
13849
- const runSafely = (name, callback) => {
13850
- try {
13851
- callback();
13852
- } catch (error) {
13853
- console.error(`Error in Braintrust AI SDK telemetry ${name}:`, error);
13854
- }
13855
- };
13856
- const startChildSpan = (operationKey, name, type, event) => {
13857
- const parent = operations.get(operationKey)?.span;
13858
- const spanArgs = {
13859
- name,
13860
- spanAttributes: { type },
13861
- ...event ? { event } : {}
13862
- };
13863
- const span = parent ? parent.startSpan(spanArgs) : startSpan(spanArgs);
13864
- const state = operations.get(operationKey);
13865
- if (state && type === "llm" /* LLM */) {
13866
- state.hadModelChild = true;
13867
- }
13868
- return span;
13869
- };
13870
- const registerOperation = (state) => {
13871
- operations.set(state.operationKey, state);
13872
- const keys = operationKeysByCallId.get(state.callId) ?? [];
13873
- keys.push(state.operationKey);
13874
- operationKeysByCallId.set(state.callId, keys);
14046
+ // src/wrappers/ai-sdk/harness-agent-context.ts
14047
+ var BRAINTRUST_TURN_CONTEXT_KEY = "__braintrust_trace_context";
14048
+ var sessionTurnParents = /* @__PURE__ */ new WeakMap();
14049
+ var wrapperTurnParents = /* @__PURE__ */ new WeakMap();
14050
+ var patchedLifecycleMethods = /* @__PURE__ */ new WeakMap();
14051
+ var harnessTurnParentStore;
14052
+ function serializedTurnContext(value) {
14053
+ if (!isObject(value)) {
14054
+ return void 0;
14055
+ }
14056
+ const context = value[BRAINTRUST_TURN_CONTEXT_KEY];
14057
+ if (!isObject(context) || typeof context.parent !== "string" || typeof context.sessionId !== "string" || typeof context.signature !== "string") {
14058
+ return void 0;
14059
+ }
14060
+ const expectedSignature = signTurnContext({
14061
+ parent: context.parent,
14062
+ sessionId: context.sessionId
14063
+ });
14064
+ if (!expectedSignature || !isomorph_default.timingSafeEqual?.(context.signature, expectedSignature)) {
14065
+ return void 0;
14066
+ }
14067
+ const parent = SpanComponentsV4.fromStr(context.parent);
14068
+ if (!parent.data.row_id || !parent.data.root_span_id || !parent.data.span_id) {
14069
+ return void 0;
14070
+ }
14071
+ return {
14072
+ parent: context.parent,
14073
+ sessionId: context.sessionId
13875
14074
  };
13876
- const deleteOperation = (operationKey) => {
13877
- const state = operations.get(operationKey);
13878
- if (!state) {
13879
- return;
14075
+ }
14076
+ function signTurnContext(context) {
14077
+ const secret = _internalGetGlobalState()._internalGetTraceContextSigningSecret();
14078
+ return secret ? isomorph_default.hmacSha256?.(
14079
+ secret,
14080
+ JSON.stringify([BRAINTRUST_TURN_CONTEXT_KEY, context])
14081
+ ) : void 0;
14082
+ }
14083
+ function continuationParentFromCreateSessionParams(params) {
14084
+ if (!isObject(params)) {
14085
+ return void 0;
14086
+ }
14087
+ const continuation = params.continueFrom ?? (isObject(params.resumeFrom) ? params.resumeFrom.continueFrom : void 0);
14088
+ const context = serializedTurnContext(continuation);
14089
+ if (!context) {
14090
+ return void 0;
14091
+ }
14092
+ if (params.sessionId !== context.sessionId) {
14093
+ return void 0;
14094
+ }
14095
+ return context.parent;
14096
+ }
14097
+ function exportSpanSynchronously(span) {
14098
+ const parentInfo = span.getParentInfo();
14099
+ if (!parentInfo) {
14100
+ return void 0;
14101
+ }
14102
+ const objectId = parentInfo.objectId.getSync().value;
14103
+ if (!objectId && !parentInfo.computeObjectMetadataArgs) {
14104
+ return void 0;
14105
+ }
14106
+ return new SpanComponentsV4({
14107
+ object_type: parentInfo.objectType,
14108
+ ...objectId ? { object_id: objectId } : {
14109
+ compute_object_metadata_args: parentInfo.computeObjectMetadataArgs ?? {}
14110
+ },
14111
+ row_id: span.id,
14112
+ root_span_id: span.rootSpanId,
14113
+ span_id: span.spanId
14114
+ }).toStr();
14115
+ }
14116
+ function exportedParent(parent) {
14117
+ return typeof parent === "string" ? parent : exportSpanSynchronously(parent);
14118
+ }
14119
+ function addSerializedContext(args) {
14120
+ if (!isObject(args.continuation) || args.sessionId === void 0) {
14121
+ return;
14122
+ }
14123
+ const parent = exportedParent(args.parent);
14124
+ if (!parent) {
14125
+ return;
14126
+ }
14127
+ const context = {
14128
+ parent,
14129
+ sessionId: args.sessionId
14130
+ };
14131
+ const signature = signTurnContext(context);
14132
+ if (!signature) {
14133
+ return;
14134
+ }
14135
+ Object.defineProperty(args.continuation, BRAINTRUST_TURN_CONTEXT_KEY, {
14136
+ configurable: true,
14137
+ enumerable: true,
14138
+ value: {
14139
+ ...context,
14140
+ signature
14141
+ },
14142
+ writable: true
14143
+ });
14144
+ }
14145
+ function lifecycleMethodDescriptor(session, method) {
14146
+ let owner = session;
14147
+ while (owner) {
14148
+ const descriptor = Object.getOwnPropertyDescriptor(owner, method);
14149
+ if (descriptor) {
14150
+ return { descriptor, owner };
14151
+ }
14152
+ owner = Object.getPrototypeOf(owner);
14153
+ }
14154
+ return void 0;
14155
+ }
14156
+ function patchLifecycleMethod(session, method) {
14157
+ let resolvedDescriptor;
14158
+ try {
14159
+ resolvedDescriptor = lifecycleMethodDescriptor(session, method);
14160
+ } catch {
14161
+ return;
14162
+ }
14163
+ if (!resolvedDescriptor || !("value" in resolvedDescriptor.descriptor) || typeof resolvedDescriptor.descriptor.value !== "function") {
14164
+ return;
14165
+ }
14166
+ const { descriptor, owner } = resolvedDescriptor;
14167
+ const patched = patchedLifecycleMethods.get(owner);
14168
+ if (patched?.has(method)) {
14169
+ return;
14170
+ }
14171
+ const original = descriptor.value;
14172
+ const replacement = function(...args) {
14173
+ const result = Reflect.apply(original, this, args);
14174
+ const addContext = (state) => {
14175
+ try {
14176
+ const parent = sessionTurnParents.get(this);
14177
+ if (!parent) {
14178
+ return;
14179
+ }
14180
+ const continuation = method === "suspendTurn" ? state : isObject(state) ? state.continueFrom : void 0;
14181
+ addSerializedContext({
14182
+ continuation,
14183
+ parent,
14184
+ sessionId: typeof this.sessionId === "string" ? this.sessionId : void 0
14185
+ });
14186
+ } catch {
14187
+ }
14188
+ };
14189
+ try {
14190
+ if (isObject(result) && typeof result.then === "function") {
14191
+ void Promise.resolve(result).then(addContext, () => {
14192
+ });
14193
+ } else {
14194
+ addContext(result);
14195
+ }
14196
+ } catch {
14197
+ }
14198
+ return result;
14199
+ };
14200
+ try {
14201
+ Object.defineProperty(owner, method, {
14202
+ ...descriptor,
14203
+ value: replacement
14204
+ });
14205
+ const ownerMethods = patched ?? /* @__PURE__ */ new Set();
14206
+ ownerMethods.add(method);
14207
+ if (!patched) {
14208
+ patchedLifecycleMethods.set(owner, ownerMethods);
14209
+ }
14210
+ } catch {
14211
+ }
14212
+ }
14213
+ function patchLifecycleMethods(session) {
14214
+ patchLifecycleMethod(session, "suspendTurn");
14215
+ patchLifecycleMethod(session, "detach");
14216
+ patchLifecycleMethod(session, "stop");
14217
+ }
14218
+ function registerHarnessTurnSpan(args) {
14219
+ if (!isObject(args.session)) {
14220
+ return;
14221
+ }
14222
+ const session = args.session;
14223
+ sessionTurnParents.set(session, args.span);
14224
+ wrapperTurnParents.set(args.span, args.span);
14225
+ patchLifecycleMethods(session);
14226
+ }
14227
+ function harnessContinuationParent(session) {
14228
+ return isObject(session) ? sessionTurnParents.get(session) : void 0;
14229
+ }
14230
+ function captureHarnessCreateSessionParent(params) {
14231
+ try {
14232
+ return continuationParentFromCreateSessionParams(params);
14233
+ } catch {
14234
+ return void 0;
14235
+ }
14236
+ }
14237
+ function registerHarnessSessionParent(session, parent) {
14238
+ if (!parent || !isObject(session)) {
14239
+ return;
14240
+ }
14241
+ const harnessSession = session;
14242
+ sessionTurnParents.set(harnessSession, parent);
14243
+ patchLifecycleMethods(harnessSession);
14244
+ }
14245
+ function currentHarnessTurnParent() {
14246
+ return harnessTurnParentStore?.getStore() ?? wrapperTurnParents.get(currentSpan());
14247
+ }
14248
+ function bindHarnessTurnParentToStart(tracingChannel2, parentFromEvent) {
14249
+ const startChannel = tracingChannel2.start;
14250
+ if (!startChannel) {
14251
+ return () => {
14252
+ };
14253
+ }
14254
+ harnessTurnParentStore ??= isomorph_default.newAsyncLocalStorage();
14255
+ const store = harnessTurnParentStore;
14256
+ startChannel.bindStore(
14257
+ store,
14258
+ (event) => parentFromEvent(event) ?? store.getStore()
14259
+ );
14260
+ return () => {
14261
+ startChannel.unbindStore(store);
14262
+ };
14263
+ }
14264
+ function startHarnessTurnChildSpan(parent, args) {
14265
+ const spanArgs = withSpanInstrumentationName(
14266
+ args,
14267
+ INSTRUMENTATION_NAMES.AI_SDK
14268
+ );
14269
+ return typeof parent === "string" ? startSpan({ ...spanArgs, parent }) : parent.startSpan(spanArgs);
14270
+ }
14271
+ function updateHarnessTurn(parent, update = {}) {
14272
+ if (!parent) {
14273
+ return;
14274
+ }
14275
+ const log2 = (event) => {
14276
+ if (typeof parent === "string") {
14277
+ updateSpan({ exported: parent, ...event });
14278
+ } else {
14279
+ parent.log(event);
14280
+ }
14281
+ };
14282
+ try {
14283
+ if (Object.prototype.hasOwnProperty.call(update, "output")) {
14284
+ log2({ output: null });
14285
+ }
14286
+ log2(update);
14287
+ } catch {
14288
+ }
14289
+ }
14290
+ function endHarnessTurn(parent) {
14291
+ const endTime = getCurrentUnixTimestamp();
14292
+ if (!parent) {
14293
+ return endTime;
14294
+ }
14295
+ try {
14296
+ const event = { metrics: { end: endTime } };
14297
+ if (typeof parent === "string") {
14298
+ updateSpan({ exported: parent, ...event });
14299
+ } else {
14300
+ parent.log(event);
14301
+ }
14302
+ } catch {
14303
+ }
14304
+ return endTime;
14305
+ }
14306
+
14307
+ // src/wrappers/ai-sdk/telemetry.ts
14308
+ function braintrustAISDKTelemetry() {
14309
+ const operations = /* @__PURE__ */ new Map();
14310
+ const operationKeysByCallId = /* @__PURE__ */ new Map();
14311
+ const workflowOperationKeyStore = isomorph_default.newAsyncLocalStorage();
14312
+ const modelSpans = /* @__PURE__ */ new Map();
14313
+ const objectSpans = /* @__PURE__ */ new Map();
14314
+ const embedSpans = /* @__PURE__ */ new Map();
14315
+ const rerankSpans = /* @__PURE__ */ new Map();
14316
+ const toolSpans = /* @__PURE__ */ new Map();
14317
+ let workflowAgentOperationCounter = 0;
14318
+ const runSafely = (name, callback) => {
14319
+ try {
14320
+ callback();
14321
+ } catch (error) {
14322
+ console.error(`Error in Braintrust AI SDK telemetry ${name}:`, error);
14323
+ }
14324
+ };
14325
+ const startChildSpan = (operationKey, name, type, event, parentOverride) => {
14326
+ const parent = operations.get(operationKey)?.span;
14327
+ const spanArgs = withSpanInstrumentationName(
14328
+ {
14329
+ name,
14330
+ spanAttributes: { type },
14331
+ ...event ? { event } : {}
14332
+ },
14333
+ INSTRUMENTATION_NAMES.AI_SDK
14334
+ );
14335
+ const span = parentOverride ? startHarnessTurnChildSpan(parentOverride, spanArgs) : parent ? parent.startSpan(spanArgs) : startSpan(spanArgs);
14336
+ const state = operations.get(operationKey);
14337
+ if (state && type === "llm" /* LLM */) {
14338
+ state.hadModelChild = true;
14339
+ }
14340
+ return span;
14341
+ };
14342
+ const registerOperation = (state) => {
14343
+ operations.set(state.operationKey, state);
14344
+ const keys = operationKeysByCallId.get(state.callId) ?? [];
14345
+ keys.push(state.operationKey);
14346
+ operationKeysByCallId.set(state.callId, keys);
14347
+ };
14348
+ const deleteOperation = (operationKey) => {
14349
+ const state = operations.get(operationKey);
14350
+ if (!state) {
14351
+ return;
13880
14352
  }
13881
14353
  operations.delete(operationKey);
13882
14354
  if (workflowOperationKeyStore.getStore() === operationKey) {
@@ -14140,14 +14612,30 @@ function braintrustAISDKTelemetry() {
14140
14612
  const workflowAgent = operationName === "WorkflowAgent.stream";
14141
14613
  const wrapperSpan = workflowAgent ? currentWorkflowAgentWrapperSpan() : void 0;
14142
14614
  const ownsSpan = !wrapperSpan;
14143
- const span = ownsSpan ? startSpan({
14144
- name: operationName,
14145
- spanAttributes: { type: "function" /* FUNCTION */ }
14146
- }) : wrapperSpan;
14615
+ const harnessTurnParent = currentHarnessTurnParent();
14616
+ const span = ownsSpan ? harnessTurnParent ? startHarnessTurnChildSpan(
14617
+ harnessTurnParent,
14618
+ withSpanInstrumentationName(
14619
+ {
14620
+ name: operationName,
14621
+ spanAttributes: { type: "function" /* FUNCTION */ }
14622
+ },
14623
+ INSTRUMENTATION_NAMES.AI_SDK
14624
+ )
14625
+ ) : startSpan(
14626
+ withSpanInstrumentationName(
14627
+ {
14628
+ name: operationName,
14629
+ spanAttributes: { type: "function" /* FUNCTION */ }
14630
+ },
14631
+ INSTRUMENTATION_NAMES.AI_SDK
14632
+ )
14633
+ ) : wrapperSpan;
14147
14634
  const operationKey = createOperationKey(event, operationName);
14148
14635
  registerOperation({
14149
14636
  callId: event.callId,
14150
14637
  hadModelChild: false,
14638
+ harnessTurnParent,
14151
14639
  loggedInput: false,
14152
14640
  operationName,
14153
14641
  operationKey,
@@ -14388,7 +14876,8 @@ function braintrustAISDKTelemetry() {
14388
14876
  toolCallId,
14389
14877
  ...typeof event.toolCall.toolName === "string" ? { toolName: event.toolCall.toolName } : {}
14390
14878
  }
14391
- }
14879
+ },
14880
+ state?.harnessTurnParent
14392
14881
  );
14393
14882
  toolSpans.set(toolCallId, { operationKey, span });
14394
14883
  });
@@ -14624,92 +15113,102 @@ function finishOutput(result, operationName) {
14624
15113
  }
14625
15114
 
14626
15115
  // src/instrumentation/plugins/ai-sdk-channels.ts
14627
- var aiSDKChannels = defineChannels("ai", {
14628
- generateText: channel({
14629
- channelName: "generateText",
14630
- kind: "async"
14631
- }),
14632
- streamText: channel({
14633
- channelName: "streamText",
14634
- kind: "async"
14635
- }),
14636
- streamTextSync: channel({
14637
- channelName: "streamText.sync",
14638
- kind: "sync-stream"
14639
- }),
14640
- generateObject: channel({
14641
- channelName: "generateObject",
14642
- kind: "async"
14643
- }),
14644
- streamObject: channel({
14645
- channelName: "streamObject",
14646
- kind: "async"
14647
- }),
14648
- streamObjectSync: channel({
14649
- channelName: "streamObject.sync",
14650
- kind: "sync-stream"
14651
- }),
14652
- embed: channel(
14653
- {
15116
+ var aiSDKChannels = defineChannels(
15117
+ "ai",
15118
+ {
15119
+ generateText: channel({
15120
+ channelName: "generateText",
15121
+ kind: "async"
15122
+ }),
15123
+ streamText: channel({
15124
+ channelName: "streamText",
15125
+ kind: "async"
15126
+ }),
15127
+ streamTextSync: channel({
15128
+ channelName: "streamText.sync",
15129
+ kind: "sync-stream"
15130
+ }),
15131
+ generateObject: channel({
15132
+ channelName: "generateObject",
15133
+ kind: "async"
15134
+ }),
15135
+ streamObject: channel({
15136
+ channelName: "streamObject",
15137
+ kind: "async"
15138
+ }),
15139
+ streamObjectSync: channel({
15140
+ channelName: "streamObject.sync",
15141
+ kind: "sync-stream"
15142
+ }),
15143
+ embed: channel({
14654
15144
  channelName: "embed",
14655
15145
  kind: "async"
14656
- }
14657
- ),
14658
- embedMany: channel({
14659
- channelName: "embedMany",
14660
- kind: "async"
14661
- }),
14662
- rerank: channel({
14663
- channelName: "rerank",
14664
- kind: "async"
14665
- }),
14666
- agentGenerate: channel({
14667
- channelName: "Agent.generate",
14668
- kind: "async"
14669
- }),
14670
- agentStream: channel({
14671
- channelName: "Agent.stream",
14672
- kind: "async"
14673
- }),
14674
- agentStreamSync: channel({
14675
- channelName: "Agent.stream.sync",
14676
- kind: "sync-stream"
14677
- }),
14678
- toolLoopAgentGenerate: channel({
14679
- channelName: "ToolLoopAgent.generate",
14680
- kind: "async"
14681
- }),
14682
- toolLoopAgentStream: channel({
14683
- channelName: "ToolLoopAgent.stream",
14684
- kind: "async"
14685
- }),
14686
- workflowAgentStream: channel({
14687
- channelName: "WorkflowAgent.stream",
14688
- kind: "async"
14689
- }),
14690
- v7CreateTelemetryDispatcher: channel({
14691
- channelName: "createTelemetryDispatcher",
14692
- kind: "sync-stream"
14693
- })
14694
- });
14695
- var harnessAgentChannels = defineChannels("@ai-sdk/harness", {
14696
- generate: channel({
14697
- channelName: "HarnessAgent.generate",
14698
- kind: "async"
14699
- }),
14700
- stream: channel({
14701
- channelName: "HarnessAgent.stream",
14702
- kind: "async"
14703
- }),
14704
- continueGenerate: channel({
14705
- channelName: "HarnessAgent.continueGenerate",
14706
- kind: "async"
14707
- }),
14708
- continueStream: channel({
14709
- channelName: "HarnessAgent.continueStream",
14710
- kind: "async"
14711
- })
14712
- });
15146
+ }),
15147
+ embedMany: channel({
15148
+ channelName: "embedMany",
15149
+ kind: "async"
15150
+ }),
15151
+ rerank: channel({
15152
+ channelName: "rerank",
15153
+ kind: "async"
15154
+ }),
15155
+ agentGenerate: channel({
15156
+ channelName: "Agent.generate",
15157
+ kind: "async"
15158
+ }),
15159
+ agentStream: channel({
15160
+ channelName: "Agent.stream",
15161
+ kind: "async"
15162
+ }),
15163
+ agentStreamSync: channel({
15164
+ channelName: "Agent.stream.sync",
15165
+ kind: "sync-stream"
15166
+ }),
15167
+ toolLoopAgentGenerate: channel({
15168
+ channelName: "ToolLoopAgent.generate",
15169
+ kind: "async"
15170
+ }),
15171
+ toolLoopAgentStream: channel({
15172
+ channelName: "ToolLoopAgent.stream",
15173
+ kind: "async"
15174
+ }),
15175
+ workflowAgentStream: channel({
15176
+ channelName: "WorkflowAgent.stream",
15177
+ kind: "async"
15178
+ }),
15179
+ v7CreateTelemetryDispatcher: channel({
15180
+ channelName: "createTelemetryDispatcher",
15181
+ kind: "sync-stream"
15182
+ })
15183
+ },
15184
+ { instrumentationName: INSTRUMENTATION_NAMES.AI_SDK }
15185
+ );
15186
+ var harnessAgentChannels = defineChannels(
15187
+ "@ai-sdk/harness",
15188
+ {
15189
+ createSession: channel({
15190
+ channelName: "HarnessAgent.createSession",
15191
+ kind: "async"
15192
+ }),
15193
+ generate: channel({
15194
+ channelName: "HarnessAgent.generate",
15195
+ kind: "async"
15196
+ }),
15197
+ stream: channel({
15198
+ channelName: "HarnessAgent.stream",
15199
+ kind: "async"
15200
+ }),
15201
+ continueGenerate: channel({
15202
+ channelName: "HarnessAgent.continueGenerate",
15203
+ kind: "async"
15204
+ }),
15205
+ continueStream: channel({
15206
+ channelName: "HarnessAgent.continueStream",
15207
+ kind: "async"
15208
+ })
15209
+ },
15210
+ { instrumentationName: INSTRUMENTATION_NAMES.AI_SDK }
15211
+ );
14713
15212
 
14714
15213
  // src/instrumentation/plugins/ai-sdk-plugin.ts
14715
15214
  var DEFAULT_DENY_OUTPUT_PATHS = [
@@ -14786,6 +15285,17 @@ var AISDKPlugin = class extends BasePlugin {
14786
15285
  subscribeToAISDK() {
14787
15286
  const denyOutputPaths = this.config.denyOutputPaths || DEFAULT_DENY_OUTPUT_PATHS;
14788
15287
  this.unsubscribers.push(subscribeToAISDKV7TelemetryDispatcher());
15288
+ this.unsubscribers.push(subscribeToHarnessAgentCreateSession());
15289
+ this.unsubscribers.push(
15290
+ subscribeToHarnessContinuation(
15291
+ harnessAgentChannels.continueGenerate,
15292
+ denyOutputPaths
15293
+ ),
15294
+ subscribeToHarnessContinuation(
15295
+ harnessAgentChannels.continueStream,
15296
+ denyOutputPaths
15297
+ )
15298
+ );
14789
15299
  this.unsubscribers.push(
14790
15300
  traceStreamingChannel(aiSDKChannels.generateText, {
14791
15301
  name: "generateText",
@@ -14981,8 +15491,9 @@ var AISDKPlugin = class extends BasePlugin {
14981
15491
  this.unsubscribers.push(
14982
15492
  traceStreamingChannel(harnessAgentChannels.generate, {
14983
15493
  name: "HarnessAgent.generate",
15494
+ startSpan: _internalStartSpanWithInitialMerge,
14984
15495
  type: "task" /* TASK */,
14985
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
15496
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
14986
15497
  extractOutput: (result, endEvent) => processAISDKOutput(
14987
15498
  result,
14988
15499
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -14994,8 +15505,9 @@ var AISDKPlugin = class extends BasePlugin {
14994
15505
  this.unsubscribers.push(
14995
15506
  traceStreamingChannel(harnessAgentChannels.stream, {
14996
15507
  name: "HarnessAgent.stream",
15508
+ startSpan: _internalStartSpanWithInitialMerge,
14997
15509
  type: "task" /* TASK */,
14998
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
15510
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
14999
15511
  extractOutput: (result, endEvent) => processAISDKOutput(
15000
15512
  result,
15001
15513
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -15020,8 +15532,10 @@ var AISDKPlugin = class extends BasePlugin {
15020
15532
  this.unsubscribers.push(
15021
15533
  traceStreamingChannel(harnessAgentChannels.continueGenerate, {
15022
15534
  name: "HarnessAgent.continueGenerate",
15535
+ shouldTrace: (args) => !harnessContinuationParent(harnessSessionFromArguments(args)),
15536
+ startSpan: _internalStartSpanWithInitialMerge,
15023
15537
  type: "task" /* TASK */,
15024
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
15538
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
15025
15539
  extractOutput: (result, endEvent) => processAISDKOutput(
15026
15540
  result,
15027
15541
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -15033,8 +15547,10 @@ var AISDKPlugin = class extends BasePlugin {
15033
15547
  this.unsubscribers.push(
15034
15548
  traceStreamingChannel(harnessAgentChannels.continueStream, {
15035
15549
  name: "HarnessAgent.continueStream",
15550
+ shouldTrace: (args) => !harnessContinuationParent(harnessSessionFromArguments(args)),
15551
+ startSpan: _internalStartSpanWithInitialMerge,
15036
15552
  type: "task" /* TASK */,
15037
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
15553
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
15038
15554
  extractOutput: (result, endEvent) => processAISDKOutput(
15039
15555
  result,
15040
15556
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -15126,6 +15642,8 @@ var AISDKPlugin = class extends BasePlugin {
15126
15642
  defaultDenyOutputPaths: denyOutputPaths,
15127
15643
  endEvent,
15128
15644
  onComplete: () => unregisterWorkflowAgentWrapperSpan(span),
15645
+ onCancel: () => unregisterWorkflowAgentWrapperSpan(span),
15646
+ onError: () => unregisterWorkflowAgentWrapperSpan(span),
15129
15647
  result,
15130
15648
  span,
15131
15649
  startTime
@@ -15134,6 +15652,153 @@ var AISDKPlugin = class extends BasePlugin {
15134
15652
  );
15135
15653
  }
15136
15654
  };
15655
+ function subscribeToHarnessAgentCreateSession() {
15656
+ const channel2 = harnessAgentChannels.createSession.tracingChannel();
15657
+ const parents = /* @__PURE__ */ new WeakMap();
15658
+ const handlers = {
15659
+ start: (event) => {
15660
+ const parent = captureHarnessCreateSessionParent(event.arguments?.[0]);
15661
+ if (parent) {
15662
+ parents.set(event, parent);
15663
+ }
15664
+ },
15665
+ asyncEnd: (event) => {
15666
+ registerHarnessSessionParent(event.result, parents.get(event));
15667
+ parents.delete(event);
15668
+ },
15669
+ error: (event) => {
15670
+ parents.delete(event);
15671
+ }
15672
+ };
15673
+ channel2.subscribe(handlers);
15674
+ return () => channel2.unsubscribe(handlers);
15675
+ }
15676
+ function harnessContinuationParentFromEvent(event) {
15677
+ try {
15678
+ return harnessContinuationParent(event.arguments?.[0]?.session);
15679
+ } catch {
15680
+ return void 0;
15681
+ }
15682
+ }
15683
+ function subscribeToHarnessContinuation(continuationChannel, defaultDenyOutputPaths) {
15684
+ const channel2 = continuationChannel.tracingChannel();
15685
+ const parents = /* @__PURE__ */ new WeakMap();
15686
+ const startTimes = /* @__PURE__ */ new WeakMap();
15687
+ const unbindParentStore = bindHarnessTurnParentToStart(
15688
+ channel2,
15689
+ harnessContinuationParentFromEvent
15690
+ );
15691
+ const handlers = {
15692
+ start: (event) => {
15693
+ const parent = harnessContinuationParentFromEvent(event);
15694
+ if (!parent) {
15695
+ return;
15696
+ }
15697
+ parents.set(event, parent);
15698
+ startTimes.set(event, getCurrentUnixTimestamp());
15699
+ try {
15700
+ const params = event.arguments?.[0];
15701
+ if (params) {
15702
+ prepareAISDKHarnessAgentInput(params, event.self);
15703
+ }
15704
+ } catch (error) {
15705
+ debugLogger.error(
15706
+ "Error preparing Harness continuation telemetry:",
15707
+ error
15708
+ );
15709
+ }
15710
+ },
15711
+ asyncEnd: (event) => {
15712
+ const parent = parents.get(event);
15713
+ const startTime = startTimes.get(event) ?? getCurrentUnixTimestamp();
15714
+ parents.delete(event);
15715
+ startTimes.delete(event);
15716
+ if (!parent) {
15717
+ return;
15718
+ }
15719
+ const endEvent = event;
15720
+ const span = {
15721
+ end: () => endHarnessTurn(parent),
15722
+ log: (update) => updateHarnessTurn(
15723
+ parent,
15724
+ Object.prototype.hasOwnProperty.call(update, "error") && !Object.prototype.hasOwnProperty.call(update, "output") ? { ...update, output: null } : update
15725
+ )
15726
+ };
15727
+ try {
15728
+ if (isAsyncIterable(endEvent.result)) {
15729
+ patchStreamIfNeeded(endEvent.result, {
15730
+ onComplete: (chunks) => {
15731
+ try {
15732
+ const { metadata, metrics, output } = aggregateAISDKChunks(
15733
+ chunks,
15734
+ endEvent.result,
15735
+ endEvent
15736
+ );
15737
+ span.log({
15738
+ ...metadata ? { metadata } : {},
15739
+ metrics,
15740
+ output
15741
+ });
15742
+ } catch (error) {
15743
+ debugLogger.error(
15744
+ "Error aggregating Harness continuation stream:",
15745
+ error
15746
+ );
15747
+ } finally {
15748
+ span.end();
15749
+ }
15750
+ },
15751
+ onError: (error) => {
15752
+ span.log({ error: toLoggedError(error), output: null });
15753
+ span.end();
15754
+ }
15755
+ });
15756
+ return;
15757
+ }
15758
+ if (patchAISDKStreamingResult({
15759
+ defaultDenyOutputPaths,
15760
+ endEvent,
15761
+ result: endEvent.result,
15762
+ resolvePromiseUsage: true,
15763
+ span,
15764
+ startTime
15765
+ })) {
15766
+ return;
15767
+ }
15768
+ finalizeAISDKChildTracing(endEvent);
15769
+ span.log({
15770
+ metrics: extractTokenMetrics(endEvent.result),
15771
+ output: processAISDKOutput(
15772
+ endEvent.result,
15773
+ resolveDenyOutputPaths(endEvent, defaultDenyOutputPaths)
15774
+ )
15775
+ });
15776
+ span.end();
15777
+ } catch (error) {
15778
+ debugLogger.error("Error tracing Harness continuation:", error);
15779
+ span.end();
15780
+ }
15781
+ },
15782
+ error: (event) => {
15783
+ const parent = parents.get(event);
15784
+ parents.delete(event);
15785
+ startTimes.delete(event);
15786
+ if (!parent) {
15787
+ return;
15788
+ }
15789
+ updateHarnessTurn(parent, {
15790
+ error: toLoggedError(event.error),
15791
+ output: null
15792
+ });
15793
+ endHarnessTurn(parent);
15794
+ }
15795
+ };
15796
+ channel2.subscribe(handlers);
15797
+ return () => {
15798
+ unbindParentStore();
15799
+ channel2.unsubscribe(handlers);
15800
+ };
15801
+ }
15137
15802
  function subscribeToAISDKV7TelemetryDispatcher() {
15138
15803
  const channel2 = aiSDKChannels.v7CreateTelemetryDispatcher.tracingChannel();
15139
15804
  const telemetry = braintrustAISDKTelemetry();
@@ -15586,7 +16251,13 @@ function prepareAISDKCallInput(params, event, span, defaultDenyOutputPaths, chil
15586
16251
  metadata
15587
16252
  };
15588
16253
  }
15589
- function prepareAISDKHarnessAgentInput(params, self) {
16254
+ function prepareAISDKHarnessAgentInput(params, self, span) {
16255
+ if (span) {
16256
+ registerHarnessTurnSpan({
16257
+ session: params.session,
16258
+ span
16259
+ });
16260
+ }
15590
16261
  if (isObject(self)) {
15591
16262
  try {
15592
16263
  if (isObject(self.settings)) {
@@ -15625,6 +16296,10 @@ function prepareAISDKHarnessAgentInput(params, self) {
15625
16296
  metadata
15626
16297
  };
15627
16298
  }
16299
+ function harnessSessionFromArguments(args) {
16300
+ const params = args[0];
16301
+ return isObject(params) ? params.session : void 0;
16302
+ }
15628
16303
  function prepareAISDKWorkflowAgentStreamInput(params, event, span, defaultDenyOutputPaths) {
15629
16304
  registerWorkflowAgentWrapperSpan(span);
15630
16305
  const { input } = processAISDKWorkflowAgentCallInput(params);
@@ -16072,19 +16747,22 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
16072
16747
  activeEntry.openSpans.delete(span);
16073
16748
  }
16074
16749
  },
16075
- {
16076
- name: "doGenerate",
16077
- spanAttributes: {
16078
- type: "llm" /* LLM */
16750
+ withSpanInstrumentationName(
16751
+ {
16752
+ name: "doGenerate",
16753
+ spanAttributes: {
16754
+ type: "llm" /* LLM */
16755
+ },
16756
+ event: buildAISDKModelStartEvent(
16757
+ callOptions,
16758
+ activeEntry.baseMetadata,
16759
+ {
16760
+ workflowAgent: activeEntry.childTracingOptions.workflowAgent
16761
+ }
16762
+ )
16079
16763
  },
16080
- event: buildAISDKModelStartEvent(
16081
- callOptions,
16082
- activeEntry.baseMetadata,
16083
- {
16084
- workflowAgent: activeEntry.childTracingOptions.workflowAgent
16085
- }
16086
- )
16087
- }
16764
+ INSTRUMENTATION_NAMES.AI_SDK
16765
+ )
16088
16766
  );
16089
16767
  };
16090
16768
  if (originalDoStream) {
@@ -16094,19 +16772,24 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
16094
16772
  return Reflect.apply(originalDoStream, resolvedModel, [callOptions]);
16095
16773
  }
16096
16774
  closeOpenAISDKModelPatchSpans(activeEntry);
16097
- const span = activeEntry.parentSpan.startSpan({
16098
- name: "doStream",
16099
- spanAttributes: {
16100
- type: "llm" /* LLM */
16101
- },
16102
- event: buildAISDKModelStartEvent(
16103
- callOptions,
16104
- activeEntry.baseMetadata,
16775
+ const span = activeEntry.parentSpan.startSpan(
16776
+ withSpanInstrumentationName(
16105
16777
  {
16106
- workflowAgent: activeEntry.childTracingOptions.workflowAgent
16107
- }
16778
+ name: "doStream",
16779
+ spanAttributes: {
16780
+ type: "llm" /* LLM */
16781
+ },
16782
+ event: buildAISDKModelStartEvent(
16783
+ callOptions,
16784
+ activeEntry.baseMetadata,
16785
+ {
16786
+ workflowAgent: activeEntry.childTracingOptions.workflowAgent
16787
+ }
16788
+ )
16789
+ },
16790
+ INSTRUMENTATION_NAMES.AI_SDK
16108
16791
  )
16109
- });
16792
+ );
16110
16793
  activeEntry.openSpans.add(span);
16111
16794
  const streamStartTime = getCurrentUnixTimestamp();
16112
16795
  const result = await withCurrent(
@@ -16278,12 +16961,17 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
16278
16961
  }
16279
16962
  if (isAsyncGenerator(result)) {
16280
16963
  return (async function* () {
16281
- const span = activeEntry.parentSpan.startSpan({
16282
- name: activeEntry.name,
16283
- spanAttributes: {
16284
- type: "tool" /* TOOL */
16285
- }
16286
- });
16964
+ const span = activeEntry.parentSpan.startSpan(
16965
+ withSpanInstrumentationName(
16966
+ {
16967
+ name: activeEntry.name,
16968
+ spanAttributes: {
16969
+ type: "tool" /* TOOL */
16970
+ }
16971
+ },
16972
+ INSTRUMENTATION_NAMES.AI_SDK
16973
+ )
16974
+ );
16287
16975
  span.log({ input: serializeToolExecutionInput(args) });
16288
16976
  try {
16289
16977
  let lastValue;
@@ -16307,12 +16995,15 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
16307
16995
  span.log({ output: awaitedResult });
16308
16996
  return awaitedResult;
16309
16997
  },
16310
- {
16311
- name: activeEntry.name,
16312
- spanAttributes: {
16313
- type: "tool" /* TOOL */
16314
- }
16315
- }
16998
+ withSpanInstrumentationName(
16999
+ {
17000
+ name: activeEntry.name,
17001
+ spanAttributes: {
17002
+ type: "tool" /* TOOL */
17003
+ }
17004
+ },
17005
+ INSTRUMENTATION_NAMES.AI_SDK
17006
+ )
16316
17007
  );
16317
17008
  };
16318
17009
  cleanup.push(() => {
@@ -16471,6 +17162,8 @@ function patchAISDKStreamingResult(args) {
16471
17162
  defaultDenyOutputPaths,
16472
17163
  endEvent,
16473
17164
  onComplete,
17165
+ onCancel,
17166
+ onError,
16474
17167
  result,
16475
17168
  resolvePromiseUsage,
16476
17169
  span,
@@ -16482,14 +17175,43 @@ function patchAISDKStreamingResult(args) {
16482
17175
  const resultRecord = result;
16483
17176
  attachKnownResultPromiseHandlers(resultRecord);
16484
17177
  let finalized = false;
16485
- const finalize = () => {
17178
+ const finalize = (outcome) => {
16486
17179
  if (finalized) {
16487
17180
  return;
16488
17181
  }
16489
17182
  finalized = true;
16490
- finalizeAISDKChildTracing(endEvent);
16491
- span.end();
16492
- onComplete?.();
17183
+ try {
17184
+ finalizeAISDKChildTracing(endEvent);
17185
+ } catch (error) {
17186
+ debugLogger.error("Error finalizing AI SDK child tracing:", error);
17187
+ }
17188
+ try {
17189
+ span.end();
17190
+ } catch (error) {
17191
+ debugLogger.error("Error ending AI SDK streaming span:", error);
17192
+ }
17193
+ if (outcome && "error" in outcome) {
17194
+ try {
17195
+ onError?.(outcome.error);
17196
+ } catch (error) {
17197
+ debugLogger.error("Error in AI SDK streaming error hook:", error);
17198
+ }
17199
+ } else if (outcome) {
17200
+ try {
17201
+ onComplete?.(outcome);
17202
+ } catch (error) {
17203
+ debugLogger.error("Error in AI SDK streaming completion hook:", error);
17204
+ }
17205
+ } else {
17206
+ try {
17207
+ onCancel?.();
17208
+ } catch (error) {
17209
+ debugLogger.error(
17210
+ "Error in AI SDK streaming cancellation hook:",
17211
+ error
17212
+ );
17213
+ }
17214
+ }
16493
17215
  };
16494
17216
  let outputLogged = false;
16495
17217
  const logStreamingOutput = async (firstChunkTime) => {
@@ -16523,15 +17245,29 @@ function patchAISDKStreamingResult(args) {
16523
17245
  resolveDenyOutputPaths(endEvent, defaultDenyOutputPaths)
16524
17246
  );
16525
17247
  const metadata = buildResolvedMetadataPayload(result).metadata;
16526
- span.log({
16527
- output,
16528
- ...metadata ? { metadata } : {},
16529
- metrics
16530
- });
17248
+ try {
17249
+ span.log({
17250
+ output,
17251
+ ...metadata ? { metadata } : {},
17252
+ metrics
17253
+ });
17254
+ } catch (error) {
17255
+ debugLogger.error("Error logging AI SDK streaming output:", error);
17256
+ }
17257
+ finalize({ metrics, output });
16531
17258
  } catch (error) {
16532
- span.log({ error: toLoggedError(error) });
16533
- } finally {
16534
- finalize();
17259
+ const loggedError = toLoggedError(error);
17260
+ try {
17261
+ span.log({ error: loggedError });
17262
+ } catch (loggingError) {
17263
+ debugLogger.error(
17264
+ "Error logging AI SDK streaming failure:",
17265
+ loggingError
17266
+ );
17267
+ }
17268
+ finalize({
17269
+ error: error instanceof Error ? error : new Error(String(loggedError))
17270
+ });
16535
17271
  }
16536
17272
  };
16537
17273
  const createAsyncIterableHooks = () => {
@@ -16548,11 +17284,16 @@ function patchAISDKStreamingResult(args) {
16548
17284
  onError: (error) => {
16549
17285
  if (!outputLogged) {
16550
17286
  outputLogged = true;
16551
- span.log({
16552
- error: error.message
16553
- });
17287
+ try {
17288
+ span.log({ error });
17289
+ } catch (loggingError) {
17290
+ debugLogger.error(
17291
+ "Error logging AI SDK stream failure:",
17292
+ loggingError
17293
+ );
17294
+ }
16554
17295
  }
16555
- finalize();
17296
+ finalize({ error });
16556
17297
  },
16557
17298
  onCancel: finalize
16558
17299
  };
@@ -16638,8 +17379,18 @@ function patchAISDKStreamingResult(args) {
16638
17379
  }
16639
17380
  controller.enqueue(value);
16640
17381
  } catch (error) {
16641
- span.log({ error: toLoggedError(error) });
16642
- finalize();
17382
+ const loggedError = toLoggedError(error);
17383
+ try {
17384
+ span.log({ error: loggedError });
17385
+ } catch (loggingError) {
17386
+ debugLogger.error(
17387
+ "Error logging AI SDK base stream failure:",
17388
+ loggingError
17389
+ );
17390
+ }
17391
+ finalize({
17392
+ error: error instanceof Error ? error : new Error(String(loggedError))
17393
+ });
16643
17394
  controller.error(error);
16644
17395
  }
16645
17396
  },
@@ -17428,7 +18179,8 @@ var claudeAgentSDKChannels = defineChannels(
17428
18179
  channelName: "query",
17429
18180
  kind: "sync-stream"
17430
18181
  })
17431
- }
18182
+ },
18183
+ { instrumentationName: INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK }
17432
18184
  );
17433
18185
 
17434
18186
  // src/instrumentation/plugins/claude-agent-sdk-instrumentation-constants.ts
@@ -17576,22 +18328,27 @@ function wrapLocalClaudeToolHandler(handler, getMetadata) {
17576
18328
  const spanName = metadata.serverName ? `tool: ${metadata.serverName}/${metadata.toolName}` : `tool: ${metadata.toolName}`;
17577
18329
  const runWithResolvedParent = async () => {
17578
18330
  const parent = toolUseId && localToolParentResolver ? await localToolParentResolver(toolUseId).catch(() => void 0) : void 0;
17579
- const span = startSpan({
17580
- event: {
17581
- input: handlerArgs[0],
17582
- metadata: {
17583
- "claude_agent_sdk.raw_tool_name": rawToolName,
17584
- "gen_ai.tool.name": metadata.toolName,
17585
- ...toolUseId && { "gen_ai.tool.call.id": toolUseId },
17586
- ...metadata.serverName && {
17587
- "mcp.server": metadata.serverName
17588
- }
17589
- }
17590
- },
17591
- name: spanName,
17592
- ...parent && { parent },
17593
- spanAttributes: { type: "tool" /* TOOL */ }
17594
- });
18331
+ const span = startSpan(
18332
+ withSpanInstrumentationName(
18333
+ {
18334
+ event: {
18335
+ input: handlerArgs[0],
18336
+ metadata: {
18337
+ "claude_agent_sdk.raw_tool_name": rawToolName,
18338
+ "gen_ai.tool.name": metadata.toolName,
18339
+ ...toolUseId && { "gen_ai.tool.call.id": toolUseId },
18340
+ ...metadata.serverName && {
18341
+ "mcp.server": metadata.serverName
18342
+ }
18343
+ }
18344
+ },
18345
+ name: spanName,
18346
+ ...parent && { parent },
18347
+ spanAttributes: { type: "tool" /* TOOL */ }
18348
+ },
18349
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
18350
+ )
18351
+ );
17595
18352
  const runHandler = () => Reflect.apply(handler, this, handlerArgs);
17596
18353
  const finalizeSuccess = (result) => {
17597
18354
  span.log({ output: result });
@@ -17916,14 +18673,19 @@ async function createLLMSpanForMessages(messages, promptMessages, conversationHi
17916
18673
  ).filter(
17917
18674
  (c) => c !== void 0
17918
18675
  );
17919
- const span = existingSpan ?? startSpan({
17920
- name: "anthropic.messages.create",
17921
- parent: parentSpan,
17922
- spanAttributes: {
17923
- type: "llm" /* LLM */
17924
- },
17925
- startTime
17926
- });
18676
+ const span = existingSpan ?? startSpan(
18677
+ withSpanInstrumentationName(
18678
+ {
18679
+ name: "anthropic.messages.create",
18680
+ parent: parentSpan,
18681
+ spanAttributes: {
18682
+ type: "llm" /* LLM */
18683
+ },
18684
+ startTime
18685
+ },
18686
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
18687
+ )
18688
+ );
17927
18689
  span.log({
17928
18690
  input,
17929
18691
  metadata: model ? { model } : void 0,
@@ -18026,25 +18788,30 @@ function createToolTracingHooks(resolveParentSpan, activeToolSpans, mcpServers,
18026
18788
  return {};
18027
18789
  }
18028
18790
  const parsed = parseToolName(input.tool_name);
18029
- const toolSpan = startSpan({
18030
- event: {
18031
- input: input.tool_input,
18032
- metadata: {
18033
- "claude_agent_sdk.cwd": input.cwd,
18034
- "claude_agent_sdk.raw_tool_name": parsed.rawToolName,
18035
- "claude_agent_sdk.session_id": input.session_id,
18036
- "gen_ai.tool.call.id": toolUseID,
18037
- "gen_ai.tool.name": parsed.toolName,
18038
- ...parsed.mcpServer && { "mcp.server": parsed.mcpServer },
18039
- ...getMcpServerMetadata(parsed.mcpServer, mcpServers)
18040
- }
18041
- },
18042
- name: parsed.displayName,
18043
- parent: await resolveParentSpan(toolUseID, {
18044
- agentId: input.agent_id
18045
- }),
18046
- spanAttributes: { type: "tool" /* TOOL */ }
18047
- });
18791
+ const toolSpan = startSpan(
18792
+ withSpanInstrumentationName(
18793
+ {
18794
+ event: {
18795
+ input: input.tool_input,
18796
+ metadata: {
18797
+ "claude_agent_sdk.cwd": input.cwd,
18798
+ "claude_agent_sdk.raw_tool_name": parsed.rawToolName,
18799
+ "claude_agent_sdk.session_id": input.session_id,
18800
+ "gen_ai.tool.call.id": toolUseID,
18801
+ "gen_ai.tool.name": parsed.toolName,
18802
+ ...parsed.mcpServer && { "mcp.server": parsed.mcpServer },
18803
+ ...getMcpServerMetadata(parsed.mcpServer, mcpServers)
18804
+ }
18805
+ },
18806
+ name: parsed.displayName,
18807
+ parent: await resolveParentSpan(toolUseID, {
18808
+ agentId: input.agent_id
18809
+ }),
18810
+ spanAttributes: { type: "tool" /* TOOL */ }
18811
+ },
18812
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
18813
+ )
18814
+ );
18048
18815
  activeToolSpans.set(toolUseID, toolSpan);
18049
18816
  return {};
18050
18817
  };
@@ -18410,14 +19177,19 @@ async function ensureSubAgentSpan(subAgentDetailsByToolUseId, rootSpan, activeTo
18410
19177
  const spanName = formatSubAgentSpanName(details);
18411
19178
  const parentToolSpan = activeToolSpans.get(parentToolUseId);
18412
19179
  const parentSpan = parentToolSpan ? await parentToolSpan.export() : await rootSpan.export();
18413
- const subAgentSpan = startSpan({
18414
- event: {
18415
- metadata: subAgentDetailsToMetadata(details)
18416
- },
18417
- name: spanName,
18418
- parent: parentSpan,
18419
- spanAttributes: { type: "task" /* TASK */ }
18420
- });
19180
+ const subAgentSpan = startSpan(
19181
+ withSpanInstrumentationName(
19182
+ {
19183
+ event: {
19184
+ metadata: subAgentDetailsToMetadata(details)
19185
+ },
19186
+ name: spanName,
19187
+ parent: parentSpan,
19188
+ spanAttributes: { type: "task" /* TASK */ }
19189
+ },
19190
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
19191
+ )
19192
+ );
18421
19193
  subAgentSpans.set(parentToolUseId, subAgentSpan);
18422
19194
  return subAgentSpan;
18423
19195
  }
@@ -18438,14 +19210,19 @@ async function ensureActiveLlmSpanForParentToolUse(rootSpan, activeLlmSpansByPar
18438
19210
  );
18439
19211
  llmParentSpan = await subAgentSpan.export();
18440
19212
  }
18441
- const llmSpan = startSpan({
18442
- name: "anthropic.messages.create",
18443
- parent: llmParentSpan,
18444
- spanAttributes: {
18445
- type: "llm" /* LLM */
18446
- },
18447
- startTime
18448
- });
19213
+ const llmSpan = startSpan(
19214
+ withSpanInstrumentationName(
19215
+ {
19216
+ name: "anthropic.messages.create",
19217
+ parent: llmParentSpan,
19218
+ spanAttributes: {
19219
+ type: "llm" /* LLM */
19220
+ },
19221
+ startTime
19222
+ },
19223
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
19224
+ )
19225
+ );
18449
19226
  activeLlmSpansByParentToolUse.set(parentKey, llmSpan);
18450
19227
  return llmSpan;
18451
19228
  }
@@ -18714,12 +19491,17 @@ var ClaudeAgentSDKPlugin = class extends BasePlugin {
18714
19491
  }
18715
19492
  })();
18716
19493
  }
18717
- const span = startSpan({
18718
- name: "Claude Agent",
18719
- spanAttributes: {
18720
- type: "task" /* TASK */
18721
- }
18722
- });
19494
+ const span = startSpan(
19495
+ withSpanInstrumentationName(
19496
+ {
19497
+ name: "Claude Agent",
19498
+ spanAttributes: {
19499
+ type: "task" /* TASK */
19500
+ }
19501
+ },
19502
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
19503
+ )
19504
+ );
18723
19505
  const startTime = getCurrentUnixTimestamp();
18724
19506
  try {
18725
19507
  span.log({
@@ -18884,24 +19666,28 @@ var ClaudeAgentSDKPlugin = class extends BasePlugin {
18884
19666
  };
18885
19667
 
18886
19668
  // src/instrumentation/plugins/cursor-sdk-channels.ts
18887
- var cursorSDKChannels = defineChannels("@cursor/sdk", {
18888
- create: channel({
18889
- channelName: "Agent.create",
18890
- kind: "async"
18891
- }),
18892
- resume: channel({
18893
- channelName: "Agent.resume",
18894
- kind: "async"
18895
- }),
18896
- prompt: channel({
18897
- channelName: "Agent.prompt",
18898
- kind: "async"
18899
- }),
18900
- send: channel({
18901
- channelName: "agent.send",
18902
- kind: "async"
18903
- })
18904
- });
19669
+ var cursorSDKChannels = defineChannels(
19670
+ "@cursor/sdk",
19671
+ {
19672
+ create: channel({
19673
+ channelName: "Agent.create",
19674
+ kind: "async"
19675
+ }),
19676
+ resume: channel({
19677
+ channelName: "Agent.resume",
19678
+ kind: "async"
19679
+ }),
19680
+ prompt: channel({
19681
+ channelName: "Agent.prompt",
19682
+ kind: "async"
19683
+ }),
19684
+ send: channel({
19685
+ channelName: "agent.send",
19686
+ kind: "async"
19687
+ })
19688
+ },
19689
+ { instrumentationName: INSTRUMENTATION_NAMES.CURSOR_SDK }
19690
+ );
18905
19691
 
18906
19692
  // src/instrumentation/plugins/cursor-sdk-plugin.ts
18907
19693
  var PATCHED_AGENT = /* @__PURE__ */ Symbol.for("braintrust.cursor-sdk.auto-patched-agent");
@@ -18953,10 +19739,15 @@ var CursorSDKPlugin = class extends BasePlugin {
18953
19739
  provider: "cursor",
18954
19740
  ...event.moduleVersion ? { "cursor_sdk.version": event.moduleVersion } : {}
18955
19741
  };
18956
- const span = startSpan({
18957
- name: "Cursor Agent",
18958
- spanAttributes: { type: "task" /* TASK */ }
18959
- });
19742
+ const span = startSpan(
19743
+ withSpanInstrumentationName(
19744
+ {
19745
+ name: "Cursor Agent",
19746
+ spanAttributes: { type: "task" /* TASK */ }
19747
+ },
19748
+ INSTRUMENTATION_NAMES.CURSOR_SDK
19749
+ )
19750
+ );
18960
19751
  const startTime = getCurrentUnixTimestamp();
18961
19752
  safeLog2(span, {
18962
19753
  input: sanitizeUserMessage(message),
@@ -19018,10 +19809,15 @@ var CursorSDKPlugin = class extends BasePlugin {
19018
19809
  provider: "cursor",
19019
19810
  ...event.moduleVersion ? { "cursor_sdk.version": event.moduleVersion } : {}
19020
19811
  };
19021
- const span = startSpan({
19022
- name: "Cursor Agent",
19023
- spanAttributes: { type: "task" /* TASK */ }
19024
- });
19812
+ const span = startSpan(
19813
+ withSpanInstrumentationName(
19814
+ {
19815
+ name: "Cursor Agent",
19816
+ spanAttributes: { type: "task" /* TASK */ }
19817
+ },
19818
+ INSTRUMENTATION_NAMES.CURSOR_SDK
19819
+ )
19820
+ );
19025
19821
  const startTime = getCurrentUnixTimestamp();
19026
19822
  safeLog2(span, {
19027
19823
  input: sanitizeUserMessage(message),
@@ -19468,29 +20264,39 @@ async function startToolSpan(state, args) {
19468
20264
  if (args.truncated?.result !== void 0) {
19469
20265
  metadata["cursor_sdk.tool.result_truncated"] = args.truncated.result;
19470
20266
  }
19471
- const span = startSpan({
19472
- event: {
19473
- input: args.args,
19474
- metadata
19475
- },
19476
- name: `tool: ${name}`,
19477
- parent: await state.span.export(),
19478
- spanAttributes: { type: "tool" /* TOOL */ }
19479
- });
20267
+ const span = startSpan(
20268
+ withSpanInstrumentationName(
20269
+ {
20270
+ event: {
20271
+ input: args.args,
20272
+ metadata
20273
+ },
20274
+ name: `tool: ${name}`,
20275
+ parent: await state.span.export(),
20276
+ spanAttributes: { type: "tool" /* TOOL */ }
20277
+ },
20278
+ INSTRUMENTATION_NAMES.CURSOR_SDK
20279
+ )
20280
+ );
19480
20281
  let subAgentSpan;
19481
20282
  if (isSubAgentToolName(name)) {
19482
- subAgentSpan = startSpan({
19483
- event: {
19484
- input: args.args,
19485
- metadata: {
19486
- "cursor_sdk.subagent.tool_call_id": args.callId,
19487
- "gen_ai.tool.name": name
19488
- }
19489
- },
19490
- name: formatSubAgentSpanName2(args.toolCall, args.args),
19491
- parent: await span.export(),
19492
- spanAttributes: { type: "task" /* TASK */ }
19493
- });
20283
+ subAgentSpan = startSpan(
20284
+ withSpanInstrumentationName(
20285
+ {
20286
+ event: {
20287
+ input: args.args,
20288
+ metadata: {
20289
+ "cursor_sdk.subagent.tool_call_id": args.callId,
20290
+ "gen_ai.tool.name": name
20291
+ }
20292
+ },
20293
+ name: formatSubAgentSpanName2(args.toolCall, args.args),
20294
+ parent: await span.export(),
20295
+ spanAttributes: { type: "task" /* TASK */ }
20296
+ },
20297
+ INSTRUMENTATION_NAMES.CURSOR_SDK
20298
+ )
20299
+ );
19494
20300
  }
19495
20301
  return { span, subAgentSpan };
19496
20302
  }
@@ -19749,24 +20555,28 @@ function cleanMetrics2(metrics) {
19749
20555
  }
19750
20556
 
19751
20557
  // src/instrumentation/plugins/openai-agents-channels.ts
19752
- var openAIAgentsCoreChannels = defineChannels("@openai/agents-core", {
19753
- onTraceStart: channel({
19754
- channelName: "tracing.processor.onTraceStart",
19755
- kind: "async"
19756
- }),
19757
- onTraceEnd: channel({
19758
- channelName: "tracing.processor.onTraceEnd",
19759
- kind: "async"
19760
- }),
19761
- onSpanStart: channel({
19762
- channelName: "tracing.processor.onSpanStart",
19763
- kind: "async"
19764
- }),
19765
- onSpanEnd: channel({
19766
- channelName: "tracing.processor.onSpanEnd",
19767
- kind: "async"
19768
- })
19769
- });
20558
+ var openAIAgentsCoreChannels = defineChannels(
20559
+ "@openai/agents-core",
20560
+ {
20561
+ onTraceStart: channel({
20562
+ channelName: "tracing.processor.onTraceStart",
20563
+ kind: "async"
20564
+ }),
20565
+ onTraceEnd: channel({
20566
+ channelName: "tracing.processor.onTraceEnd",
20567
+ kind: "async"
20568
+ }),
20569
+ onSpanStart: channel({
20570
+ channelName: "tracing.processor.onSpanStart",
20571
+ kind: "async"
20572
+ }),
20573
+ onSpanEnd: channel({
20574
+ channelName: "tracing.processor.onSpanEnd",
20575
+ kind: "async"
20576
+ })
20577
+ },
20578
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENAI_AGENTS }
20579
+ );
19770
20580
 
19771
20581
  // src/instrumentation/plugins/openai-agents-trace-processor.ts
19772
20582
  function isSpanData(spanData, type) {
@@ -19882,16 +20692,19 @@ var OpenAIAgentsTraceProcessor = class _OpenAIAgentsTraceProcessor {
19882
20692
  this.evictOldestTrace();
19883
20693
  }
19884
20694
  const current = currentSpan();
19885
- const span = current && current !== NOOP_SPAN ? current.startSpan({
19886
- name: trace.name,
19887
- type: "task" /* TASK */
19888
- }) : this.logger ? this.logger.startSpan({
19889
- name: trace.name,
19890
- type: "task" /* TASK */
19891
- }) : startSpan({
19892
- name: trace.name,
19893
- type: "task" /* TASK */
19894
- });
20695
+ const spanArgs = withSpanInstrumentationName(
20696
+ {
20697
+ name: trace.name,
20698
+ type: "task" /* TASK */
20699
+ },
20700
+ INSTRUMENTATION_NAMES.OPENAI_AGENTS
20701
+ );
20702
+ const span = current && current !== NOOP_SPAN ? current.startSpan(spanArgs) : this.logger ? this.logger.startSpan(spanArgs) : startSpan(
20703
+ withSpanInstrumentationName(
20704
+ spanArgs,
20705
+ INSTRUMENTATION_NAMES.OPENAI_AGENTS
20706
+ )
20707
+ );
19895
20708
  span.log({
19896
20709
  input: "Agent workflow started",
19897
20710
  metadata: {
@@ -19942,10 +20755,15 @@ var OpenAIAgentsTraceProcessor = class _OpenAIAgentsTraceProcessor {
19942
20755
  if (!parentSpan) {
19943
20756
  return Promise.resolve();
19944
20757
  }
19945
- const childSpan = parentSpan.startSpan({
19946
- name: spanNameFromAgents(span),
19947
- type: spanTypeFromAgents(span)
19948
- });
20758
+ const childSpan = parentSpan.startSpan(
20759
+ withSpanInstrumentationName(
20760
+ {
20761
+ name: spanNameFromAgents(span),
20762
+ type: spanTypeFromAgents(span)
20763
+ },
20764
+ INSTRUMENTATION_NAMES.OPENAI_AGENTS
20765
+ )
20766
+ );
19949
20767
  traceData.childSpans.set(span.spanId, childSpan);
19950
20768
  return Promise.resolve();
19951
20769
  }
@@ -20210,24 +21028,28 @@ var OpenAIAgentsPlugin = class extends BasePlugin {
20210
21028
  };
20211
21029
 
20212
21030
  // src/instrumentation/plugins/google-genai-channels.ts
20213
- var googleGenAIChannels = defineChannels("@google/genai", {
20214
- generateContent: channel({
20215
- channelName: "models.generateContent",
20216
- kind: "async"
20217
- }),
20218
- generateContentStream: channel({
20219
- channelName: "models.generateContentStream",
20220
- kind: "async"
20221
- }),
20222
- embedContent: channel({
20223
- channelName: "models.embedContent",
20224
- kind: "async"
20225
- }),
20226
- interactionsCreate: channel({
20227
- channelName: "interactions.create",
20228
- kind: "async"
20229
- })
20230
- });
21031
+ var googleGenAIChannels = defineChannels(
21032
+ "@google/genai",
21033
+ {
21034
+ generateContent: channel({
21035
+ channelName: "models.generateContent",
21036
+ kind: "async"
21037
+ }),
21038
+ generateContentStream: channel({
21039
+ channelName: "models.generateContentStream",
21040
+ kind: "async"
21041
+ }),
21042
+ embedContent: channel({
21043
+ channelName: "models.embedContent",
21044
+ kind: "async"
21045
+ }),
21046
+ interactionsCreate: channel({
21047
+ channelName: "interactions.create",
21048
+ kind: "async"
21049
+ })
21050
+ },
21051
+ { instrumentationName: INSTRUMENTATION_NAMES.GOOGLE_GENAI }
21052
+ );
20231
21053
 
20232
21054
  // src/instrumentation/plugins/google-genai-plugin.ts
20233
21055
  var GOOGLE_GENAI_INTERNAL_CONTEXT = {
@@ -20265,13 +21087,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
20265
21087
  const params = event.arguments[0];
20266
21088
  const input = serializeGenerateContentInput(params);
20267
21089
  const metadata = extractGenerateContentMetadata(params);
20268
- const span = startSpan({
20269
- name: "generate_content",
20270
- spanAttributes: {
20271
- type: "llm" /* LLM */
20272
- },
20273
- event: createWrapperParityEvent({ input, metadata })
20274
- });
21090
+ const span = startSpan(
21091
+ withSpanInstrumentationName(
21092
+ {
21093
+ name: "generate_content",
21094
+ spanAttributes: {
21095
+ type: "llm" /* LLM */
21096
+ },
21097
+ event: createWrapperParityEvent({ input, metadata })
21098
+ },
21099
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
21100
+ )
21101
+ );
20275
21102
  return {
20276
21103
  span,
20277
21104
  startTime: getCurrentUnixTimestamp()
@@ -20284,13 +21111,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
20284
21111
  const params = event.arguments[0];
20285
21112
  const input = serializeGenerateContentInput(params);
20286
21113
  const metadata = extractGenerateContentMetadata(params);
20287
- const span = startSpan({
20288
- name: "generate_content",
20289
- spanAttributes: {
20290
- type: "llm" /* LLM */
20291
- },
20292
- event: createWrapperParityEvent({ input, metadata })
20293
- });
21114
+ const span = startSpan(
21115
+ withSpanInstrumentationName(
21116
+ {
21117
+ name: "generate_content",
21118
+ spanAttributes: {
21119
+ type: "llm" /* LLM */
21120
+ },
21121
+ event: createWrapperParityEvent({ input, metadata })
21122
+ },
21123
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
21124
+ )
21125
+ );
20294
21126
  return {
20295
21127
  span,
20296
21128
  startTime: getCurrentUnixTimestamp()
@@ -20366,13 +21198,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
20366
21198
  const params = event.arguments[0];
20367
21199
  const input = serializeEmbedContentInput(params);
20368
21200
  const metadata = extractEmbedContentMetadata(params);
20369
- const span = startSpan({
20370
- name: "embed_content",
20371
- spanAttributes: {
20372
- type: "llm" /* LLM */
20373
- },
20374
- event: createWrapperParityEvent({ input, metadata })
20375
- });
21201
+ const span = startSpan(
21202
+ withSpanInstrumentationName(
21203
+ {
21204
+ name: "embed_content",
21205
+ spanAttributes: {
21206
+ type: "llm" /* LLM */
21207
+ },
21208
+ event: createWrapperParityEvent({ input, metadata })
21209
+ },
21210
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
21211
+ )
21212
+ );
20376
21213
  return {
20377
21214
  span,
20378
21215
  startTime: getCurrentUnixTimestamp()
@@ -20385,13 +21222,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
20385
21222
  const params = event.arguments[0];
20386
21223
  const input = serializeEmbedContentInput(params);
20387
21224
  const metadata = extractEmbedContentMetadata(params);
20388
- const span = startSpan({
20389
- name: "embed_content",
20390
- spanAttributes: {
20391
- type: "llm" /* LLM */
20392
- },
20393
- event: createWrapperParityEvent({ input, metadata })
20394
- });
21225
+ const span = startSpan(
21226
+ withSpanInstrumentationName(
21227
+ {
21228
+ name: "embed_content",
21229
+ spanAttributes: {
21230
+ type: "llm" /* LLM */
21231
+ },
21232
+ event: createWrapperParityEvent({ input, metadata })
21233
+ },
21234
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
21235
+ )
21236
+ );
20395
21237
  return {
20396
21238
  span,
20397
21239
  startTime: getCurrentUnixTimestamp()
@@ -20502,16 +21344,21 @@ function patchGoogleGenAIStreamingResult(args) {
20502
21344
  const requestStartTime = startTime ?? getCurrentUnixTimestamp();
20503
21345
  const ensureSpan = () => {
20504
21346
  if (!span) {
20505
- span = startSpan({
20506
- name: "generate_content_stream",
20507
- spanAttributes: {
20508
- type: "llm" /* LLM */
20509
- },
20510
- event: {
20511
- input,
20512
- metadata
20513
- }
20514
- });
21347
+ span = startSpan(
21348
+ withSpanInstrumentationName(
21349
+ {
21350
+ name: "generate_content_stream",
21351
+ spanAttributes: {
21352
+ type: "llm" /* LLM */
21353
+ },
21354
+ event: {
21355
+ input,
21356
+ metadata
21357
+ }
21358
+ },
21359
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
21360
+ )
21361
+ );
20515
21362
  }
20516
21363
  return span;
20517
21364
  };
@@ -21279,28 +22126,32 @@ function tryToDict(obj) {
21279
22126
  }
21280
22127
 
21281
22128
  // src/instrumentation/plugins/huggingface-channels.ts
21282
- var huggingFaceChannels = defineChannels("@huggingface/inference", {
21283
- chatCompletion: channel({
21284
- channelName: "chatCompletion",
21285
- kind: "async"
21286
- }),
21287
- chatCompletionStream: channel({
21288
- channelName: "chatCompletionStream",
21289
- kind: "sync-stream"
21290
- }),
21291
- textGeneration: channel({
21292
- channelName: "textGeneration",
21293
- kind: "async"
21294
- }),
21295
- textGenerationStream: channel({
21296
- channelName: "textGenerationStream",
21297
- kind: "sync-stream"
21298
- }),
21299
- featureExtraction: channel({
21300
- channelName: "featureExtraction",
21301
- kind: "async"
21302
- })
21303
- });
22129
+ var huggingFaceChannels = defineChannels(
22130
+ "@huggingface/inference",
22131
+ {
22132
+ chatCompletion: channel({
22133
+ channelName: "chatCompletion",
22134
+ kind: "async"
22135
+ }),
22136
+ chatCompletionStream: channel({
22137
+ channelName: "chatCompletionStream",
22138
+ kind: "sync-stream"
22139
+ }),
22140
+ textGeneration: channel({
22141
+ channelName: "textGeneration",
22142
+ kind: "async"
22143
+ }),
22144
+ textGenerationStream: channel({
22145
+ channelName: "textGenerationStream",
22146
+ kind: "sync-stream"
22147
+ }),
22148
+ featureExtraction: channel({
22149
+ channelName: "featureExtraction",
22150
+ kind: "async"
22151
+ })
22152
+ },
22153
+ { instrumentationName: INSTRUMENTATION_NAMES.HUGGINGFACE }
22154
+ );
21304
22155
 
21305
22156
  // src/instrumentation/plugins/huggingface-plugin.ts
21306
22157
  var REQUEST_METADATA_ALLOWLIST = /* @__PURE__ */ new Set([
@@ -21727,20 +22578,24 @@ function extractTextGenerationStreamMetadata(chunks) {
21727
22578
  }
21728
22579
 
21729
22580
  // src/instrumentation/plugins/openrouter-agent-channels.ts
21730
- var openRouterAgentChannels = defineChannels("@openrouter/agent", {
21731
- callModel: channel({
21732
- channelName: "callModel",
21733
- kind: "sync-stream"
21734
- }),
21735
- callModelTurn: channel({
21736
- channelName: "callModel.turn",
21737
- kind: "async"
21738
- }),
21739
- toolExecute: channel({
21740
- channelName: "tool.execute",
21741
- kind: "async"
21742
- })
21743
- });
22581
+ var openRouterAgentChannels = defineChannels(
22582
+ "@openrouter/agent",
22583
+ {
22584
+ callModel: channel({
22585
+ channelName: "callModel",
22586
+ kind: "sync-stream"
22587
+ }),
22588
+ callModelTurn: channel({
22589
+ channelName: "callModel.turn",
22590
+ kind: "async"
22591
+ }),
22592
+ toolExecute: channel({
22593
+ channelName: "tool.execute",
22594
+ kind: "async"
22595
+ })
22596
+ },
22597
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENROUTER_AGENT }
22598
+ );
21744
22599
 
21745
22600
  // src/instrumentation/plugins/openrouter-agent-plugin.ts
21746
22601
  var OpenRouterAgentPlugin = class extends BasePlugin {
@@ -22510,38 +23365,40 @@ function normalizeError(error) {
22510
23365
  }
22511
23366
 
22512
23367
  // src/instrumentation/plugins/openrouter-channels.ts
22513
- var openRouterChannels = defineChannels("@openrouter/sdk", {
22514
- chatSend: channel({
22515
- channelName: "chat.send",
22516
- kind: "async"
22517
- }),
22518
- embeddingsGenerate: channel({
22519
- channelName: "embeddings.generate",
22520
- kind: "async"
22521
- }),
22522
- rerankRerank: channel(
22523
- {
23368
+ var openRouterChannels = defineChannels(
23369
+ "@openrouter/sdk",
23370
+ {
23371
+ chatSend: channel({
23372
+ channelName: "chat.send",
23373
+ kind: "async"
23374
+ }),
23375
+ embeddingsGenerate: channel({
23376
+ channelName: "embeddings.generate",
23377
+ kind: "async"
23378
+ }),
23379
+ rerankRerank: channel({
22524
23380
  channelName: "rerank.rerank",
22525
23381
  kind: "async"
22526
- }
22527
- ),
22528
- betaResponsesSend: channel({
22529
- channelName: "beta.responses.send",
22530
- kind: "async"
22531
- }),
22532
- callModel: channel({
22533
- channelName: "callModel",
22534
- kind: "sync-stream"
22535
- }),
22536
- callModelTurn: channel({
22537
- channelName: "callModel.turn",
22538
- kind: "async"
22539
- }),
22540
- toolExecute: channel({
22541
- channelName: "tool.execute",
22542
- kind: "async"
22543
- })
22544
- });
23382
+ }),
23383
+ betaResponsesSend: channel({
23384
+ channelName: "beta.responses.send",
23385
+ kind: "async"
23386
+ }),
23387
+ callModel: channel({
23388
+ channelName: "callModel",
23389
+ kind: "sync-stream"
23390
+ }),
23391
+ callModelTurn: channel({
23392
+ channelName: "callModel.turn",
23393
+ kind: "async"
23394
+ }),
23395
+ toolExecute: channel({
23396
+ channelName: "tool.execute",
23397
+ kind: "async"
23398
+ })
23399
+ },
23400
+ { instrumentationName: INSTRUMENTATION_NAMES.OPENROUTER }
23401
+ );
22545
23402
 
22546
23403
  // src/instrumentation/plugins/openrouter-plugin.ts
22547
23404
  var OpenRouterPlugin = class extends BasePlugin {
@@ -23581,52 +24438,56 @@ function normalizeError2(error) {
23581
24438
  }
23582
24439
 
23583
24440
  // src/instrumentation/plugins/mistral-channels.ts
23584
- var mistralChannels = defineChannels("@mistralai/mistralai", {
23585
- chatComplete: channel({
23586
- channelName: "chat.complete",
23587
- kind: "async"
23588
- }),
23589
- chatStream: channel({
23590
- channelName: "chat.stream",
23591
- kind: "async"
23592
- }),
23593
- embeddingsCreate: channel({
23594
- channelName: "embeddings.create",
23595
- kind: "async"
23596
- }),
23597
- classifiersModerate: channel({
23598
- channelName: "classifiers.moderate",
23599
- kind: "async"
23600
- }),
23601
- classifiersModerateChat: channel({
23602
- channelName: "classifiers.moderateChat",
23603
- kind: "async"
23604
- }),
23605
- classifiersClassify: channel({
23606
- channelName: "classifiers.classify",
23607
- kind: "async"
23608
- }),
23609
- classifiersClassifyChat: channel({
23610
- channelName: "classifiers.classifyChat",
23611
- kind: "async"
23612
- }),
23613
- fimComplete: channel({
23614
- channelName: "fim.complete",
23615
- kind: "async"
23616
- }),
23617
- fimStream: channel({
23618
- channelName: "fim.stream",
23619
- kind: "async"
23620
- }),
23621
- agentsComplete: channel({
23622
- channelName: "agents.complete",
23623
- kind: "async"
23624
- }),
23625
- agentsStream: channel({
23626
- channelName: "agents.stream",
23627
- kind: "async"
23628
- })
23629
- });
24441
+ var mistralChannels = defineChannels(
24442
+ "@mistralai/mistralai",
24443
+ {
24444
+ chatComplete: channel({
24445
+ channelName: "chat.complete",
24446
+ kind: "async"
24447
+ }),
24448
+ chatStream: channel({
24449
+ channelName: "chat.stream",
24450
+ kind: "async"
24451
+ }),
24452
+ embeddingsCreate: channel({
24453
+ channelName: "embeddings.create",
24454
+ kind: "async"
24455
+ }),
24456
+ classifiersModerate: channel({
24457
+ channelName: "classifiers.moderate",
24458
+ kind: "async"
24459
+ }),
24460
+ classifiersModerateChat: channel({
24461
+ channelName: "classifiers.moderateChat",
24462
+ kind: "async"
24463
+ }),
24464
+ classifiersClassify: channel({
24465
+ channelName: "classifiers.classify",
24466
+ kind: "async"
24467
+ }),
24468
+ classifiersClassifyChat: channel({
24469
+ channelName: "classifiers.classifyChat",
24470
+ kind: "async"
24471
+ }),
24472
+ fimComplete: channel({
24473
+ channelName: "fim.complete",
24474
+ kind: "async"
24475
+ }),
24476
+ fimStream: channel({
24477
+ channelName: "fim.stream",
24478
+ kind: "async"
24479
+ }),
24480
+ agentsComplete: channel({
24481
+ channelName: "agents.complete",
24482
+ kind: "async"
24483
+ }),
24484
+ agentsStream: channel({
24485
+ channelName: "agents.stream",
24486
+ kind: "async"
24487
+ })
24488
+ },
24489
+ { instrumentationName: INSTRUMENTATION_NAMES.MISTRAL }
24490
+ );
23630
24491
 
23631
24492
  // src/instrumentation/plugins/mistral-plugin.ts
23632
24493
  var MistralPlugin = class extends BasePlugin {
@@ -24246,20 +25107,24 @@ function aggregateMistralStreamChunks(chunks) {
24246
25107
  }
24247
25108
 
24248
25109
  // src/instrumentation/plugins/google-adk-channels.ts
24249
- var googleADKChannels = defineChannels("@google/adk", {
24250
- runnerRunAsync: channel({
24251
- channelName: "runner.runAsync",
24252
- kind: "sync-stream"
24253
- }),
24254
- agentRunAsync: channel({
24255
- channelName: "agent.runAsync",
24256
- kind: "sync-stream"
24257
- }),
24258
- toolRunAsync: channel({
24259
- channelName: "tool.runAsync",
24260
- kind: "async"
24261
- })
24262
- });
25110
+ var googleADKChannels = defineChannels(
25111
+ "@google/adk",
25112
+ {
25113
+ runnerRunAsync: channel({
25114
+ channelName: "runner.runAsync",
25115
+ kind: "sync-stream"
25116
+ }),
25117
+ agentRunAsync: channel({
25118
+ channelName: "agent.runAsync",
25119
+ kind: "sync-stream"
25120
+ }),
25121
+ toolRunAsync: channel({
25122
+ channelName: "tool.runAsync",
25123
+ kind: "async"
25124
+ })
25125
+ },
25126
+ { instrumentationName: INSTRUMENTATION_NAMES.GOOGLE_ADK }
25127
+ );
24263
25128
 
24264
25129
  // src/instrumentation/plugins/google-adk-plugin.ts
24265
25130
  var GoogleADKPlugin = class extends BasePlugin {
@@ -24284,12 +25149,17 @@ var GoogleADKPlugin = class extends BasePlugin {
24284
25149
  const createState = (event) => {
24285
25150
  const params = event.arguments[0] ?? {};
24286
25151
  const contextKey = extractRunnerContextKey(params);
24287
- const span = startSpan({
24288
- name: "Google ADK Runner",
24289
- spanAttributes: {
24290
- type: "task" /* TASK */
24291
- }
24292
- });
25152
+ const span = startSpan(
25153
+ withSpanInstrumentationName(
25154
+ {
25155
+ name: "Google ADK Runner",
25156
+ spanAttributes: {
25157
+ type: "task" /* TASK */
25158
+ }
25159
+ },
25160
+ INSTRUMENTATION_NAMES.GOOGLE_ADK
25161
+ )
25162
+ );
24293
25163
  const startTime = getCurrentUnixTimestamp();
24294
25164
  try {
24295
25165
  const metadata = extractRunnerMetadata(params);
@@ -24375,18 +25245,23 @@ var GoogleADKPlugin = class extends BasePlugin {
24375
25245
  this.activeRunnerSpans
24376
25246
  );
24377
25247
  const contextKey = extractInvocationContextKey(parentContext);
24378
- const span = startSpan({
24379
- name: agentName ? `Agent: ${agentName}` : "Google ADK Agent",
24380
- spanAttributes: {
24381
- type: "task" /* TASK */
24382
- },
24383
- ...runnerParentSpan ? {
24384
- parentSpanIds: {
24385
- spanId: runnerParentSpan.spanId,
24386
- rootSpanId: runnerParentSpan.rootSpanId
24387
- }
24388
- } : {}
24389
- });
25248
+ const span = startSpan(
25249
+ withSpanInstrumentationName(
25250
+ {
25251
+ name: agentName ? `Agent: ${agentName}` : "Google ADK Agent",
25252
+ spanAttributes: {
25253
+ type: "task" /* TASK */
25254
+ },
25255
+ ...runnerParentSpan ? {
25256
+ parentSpanIds: {
25257
+ spanId: runnerParentSpan.spanId,
25258
+ rootSpanId: runnerParentSpan.rootSpanId
25259
+ }
25260
+ } : {}
25261
+ },
25262
+ INSTRUMENTATION_NAMES.GOOGLE_ADK
25263
+ )
25264
+ );
24390
25265
  const startTime = getCurrentUnixTimestamp();
24391
25266
  try {
24392
25267
  const metadata = {
@@ -24479,22 +25354,27 @@ var GoogleADKPlugin = class extends BasePlugin {
24479
25354
  this.activeAgentSpans,
24480
25355
  this.activeRunnerSpans
24481
25356
  );
24482
- const createSpan = () => startSpan({
24483
- name: toolName ? `tool: ${toolName}` : "Google ADK Tool",
24484
- spanAttributes: {
24485
- type: "tool" /* TOOL */
24486
- },
24487
- event: {
24488
- input: req.args,
24489
- metadata: {
24490
- provider: "google-adk",
24491
- ...toolName && { "google_adk.tool_name": toolName },
24492
- ...extractToolCallId(req) && {
24493
- "google_adk.tool_call_id": extractToolCallId(req)
25357
+ const createSpan = () => startSpan(
25358
+ withSpanInstrumentationName(
25359
+ {
25360
+ name: toolName ? `tool: ${toolName}` : "Google ADK Tool",
25361
+ spanAttributes: {
25362
+ type: "tool" /* TOOL */
25363
+ },
25364
+ event: {
25365
+ input: req.args,
25366
+ metadata: {
25367
+ provider: "google-adk",
25368
+ ...toolName && { "google_adk.tool_name": toolName },
25369
+ ...extractToolCallId(req) && {
25370
+ "google_adk.tool_call_id": extractToolCallId(req)
25371
+ }
25372
+ }
24494
25373
  }
24495
- }
24496
- }
24497
- });
25374
+ },
25375
+ INSTRUMENTATION_NAMES.GOOGLE_ADK
25376
+ )
25377
+ );
24498
25378
  const span = parentSpan ? withCurrent(parentSpan, () => createSpan()) : createSpan();
24499
25379
  const startTime = getCurrentUnixTimestamp();
24500
25380
  states.set(event, { span, startTime });
@@ -24893,24 +25773,28 @@ function cleanMetrics4(metrics) {
24893
25773
  }
24894
25774
 
24895
25775
  // src/instrumentation/plugins/cohere-channels.ts
24896
- var cohereChannels = defineChannels("cohere-ai", {
24897
- chat: channel({
24898
- channelName: "chat",
24899
- kind: "async"
24900
- }),
24901
- chatStream: channel({
24902
- channelName: "chatStream",
24903
- kind: "async"
24904
- }),
24905
- embed: channel({
24906
- channelName: "embed",
24907
- kind: "async"
24908
- }),
24909
- rerank: channel({
24910
- channelName: "rerank",
24911
- kind: "async"
24912
- })
24913
- });
25776
+ var cohereChannels = defineChannels(
25777
+ "cohere-ai",
25778
+ {
25779
+ chat: channel({
25780
+ channelName: "chat",
25781
+ kind: "async"
25782
+ }),
25783
+ chatStream: channel({
25784
+ channelName: "chatStream",
25785
+ kind: "async"
25786
+ }),
25787
+ embed: channel({
25788
+ channelName: "embed",
25789
+ kind: "async"
25790
+ }),
25791
+ rerank: channel({
25792
+ channelName: "rerank",
25793
+ kind: "async"
25794
+ })
25795
+ },
25796
+ { instrumentationName: INSTRUMENTATION_NAMES.COHERE }
25797
+ );
24914
25798
 
24915
25799
  // src/instrumentation/plugins/cohere-plugin.ts
24916
25800
  var CoherePlugin = class extends BasePlugin {
@@ -25579,18 +26463,20 @@ function aggregateCohereChatStreamChunks(chunks) {
25579
26463
  }
25580
26464
 
25581
26465
  // src/instrumentation/plugins/groq-channels.ts
25582
- var groqChannels = defineChannels("groq-sdk", {
25583
- chatCompletionsCreate: channel({
25584
- channelName: "chat.completions.create",
25585
- kind: "async"
25586
- }),
25587
- embeddingsCreate: channel(
25588
- {
26466
+ var groqChannels = defineChannels(
26467
+ "groq-sdk",
26468
+ {
26469
+ chatCompletionsCreate: channel({
26470
+ channelName: "chat.completions.create",
26471
+ kind: "async"
26472
+ }),
26473
+ embeddingsCreate: channel({
25589
26474
  channelName: "embeddings.create",
25590
26475
  kind: "async"
25591
- }
25592
- )
25593
- });
26476
+ })
26477
+ },
26478
+ { instrumentationName: INSTRUMENTATION_NAMES.GROQ }
26479
+ );
25594
26480
 
25595
26481
  // src/instrumentation/plugins/groq-plugin.ts
25596
26482
  var GroqPlugin = class extends BasePlugin {
@@ -25693,15 +26579,27 @@ var clientSendChannel = channel({
25693
26579
  channelName: "client.send",
25694
26580
  kind: "async"
25695
26581
  });
25696
- var bedrockRuntimeChannels = defineChannels("aws-bedrock-runtime", {
25697
- clientSend: clientSendChannel
25698
- });
25699
- var smithyCoreChannels = defineChannels("@smithy/core", {
25700
- clientSend: clientSendChannel
25701
- });
25702
- var smithyClientChannels = defineChannels("@smithy/smithy-client", {
25703
- clientSend: clientSendChannel
25704
- });
26582
+ var bedrockRuntimeChannels = defineChannels(
26583
+ "aws-bedrock-runtime",
26584
+ {
26585
+ clientSend: clientSendChannel
26586
+ },
26587
+ { instrumentationName: INSTRUMENTATION_NAMES.BEDROCK_RUNTIME }
26588
+ );
26589
+ var smithyCoreChannels = defineChannels(
26590
+ "@smithy/core",
26591
+ {
26592
+ clientSend: clientSendChannel
26593
+ },
26594
+ { instrumentationName: INSTRUMENTATION_NAMES.BEDROCK_RUNTIME }
26595
+ );
26596
+ var smithyClientChannels = defineChannels(
26597
+ "@smithy/smithy-client",
26598
+ {
26599
+ clientSend: clientSendChannel
26600
+ },
26601
+ { instrumentationName: INSTRUMENTATION_NAMES.BEDROCK_RUNTIME }
26602
+ );
25705
26603
 
25706
26604
  // src/instrumentation/plugins/bedrock-runtime-common.ts
25707
26605
  var BEDROCK_RUNTIME_COMMAND_OPERATIONS = {
@@ -26335,38 +27233,46 @@ function extractTextFromJsonLike(value) {
26335
27233
  }
26336
27234
 
26337
27235
  // src/instrumentation/plugins/genkit-channels.ts
26338
- var genkitChannels = defineChannels("@genkit-ai/ai", {
26339
- generate: channel({
26340
- channelName: "generate",
26341
- kind: "async"
26342
- }),
26343
- generateStream: channel({
26344
- channelName: "generateStream",
26345
- kind: "sync-stream"
26346
- }),
26347
- embed: channel({
26348
- channelName: "embed",
26349
- kind: "async"
26350
- }),
26351
- embedMany: channel({
26352
- channelName: "embedMany",
26353
- kind: "async"
26354
- }),
26355
- actionRun: channel({
26356
- channelName: "action.run",
26357
- kind: "async"
26358
- }),
26359
- actionStream: channel({
26360
- channelName: "action.stream",
26361
- kind: "sync-stream"
26362
- })
26363
- });
26364
- var genkitCoreChannels = defineChannels("@genkit-ai/core", {
26365
- actionSpan: channel({
26366
- channelName: "action.span",
26367
- kind: "async"
26368
- })
26369
- });
27236
+ var genkitChannels = defineChannels(
27237
+ "@genkit-ai/ai",
27238
+ {
27239
+ generate: channel({
27240
+ channelName: "generate",
27241
+ kind: "async"
27242
+ }),
27243
+ generateStream: channel({
27244
+ channelName: "generateStream",
27245
+ kind: "sync-stream"
27246
+ }),
27247
+ embed: channel({
27248
+ channelName: "embed",
27249
+ kind: "async"
27250
+ }),
27251
+ embedMany: channel({
27252
+ channelName: "embedMany",
27253
+ kind: "async"
27254
+ }),
27255
+ actionRun: channel({
27256
+ channelName: "action.run",
27257
+ kind: "async"
27258
+ }),
27259
+ actionStream: channel({
27260
+ channelName: "action.stream",
27261
+ kind: "sync-stream"
27262
+ })
27263
+ },
27264
+ { instrumentationName: INSTRUMENTATION_NAMES.GENKIT }
27265
+ );
27266
+ var genkitCoreChannels = defineChannels(
27267
+ "@genkit-ai/core",
27268
+ {
27269
+ actionSpan: channel({
27270
+ channelName: "action.span",
27271
+ kind: "async"
27272
+ })
27273
+ },
27274
+ { instrumentationName: INSTRUMENTATION_NAMES.GENKIT }
27275
+ );
26370
27276
 
26371
27277
  // src/instrumentation/plugins/genkit-plugin.ts
26372
27278
  var GenkitPlugin = class extends BasePlugin {
@@ -26551,12 +27457,17 @@ function startActionSpanState(args) {
26551
27457
  if (!shouldTraceAction(args.metadata, args.runStepName)) {
26552
27458
  return void 0;
26553
27459
  }
26554
- const span = startSpan({
26555
- name: actionSpanName(args.metadata, args.runStepName),
26556
- spanAttributes: {
26557
- type: actionSpanType(args.metadata)
26558
- }
26559
- });
27460
+ const span = startSpan(
27461
+ withSpanInstrumentationName(
27462
+ {
27463
+ name: actionSpanName(args.metadata, args.runStepName),
27464
+ spanAttributes: {
27465
+ type: actionSpanType(args.metadata)
27466
+ }
27467
+ },
27468
+ INSTRUMENTATION_NAMES.GENKIT
27469
+ )
27470
+ );
26560
27471
  const startTime = getCurrentUnixTimestamp();
26561
27472
  span.log({
26562
27473
  input: args.input,
@@ -26917,20 +27828,24 @@ function stringValue(value) {
26917
27828
  }
26918
27829
 
26919
27830
  // src/instrumentation/plugins/github-copilot-channels.ts
26920
- var gitHubCopilotChannels = defineChannels("@github/copilot-sdk", {
26921
- createSession: channel({
26922
- channelName: "client.createSession",
26923
- kind: "async"
26924
- }),
26925
- resumeSession: channel({
26926
- channelName: "client.resumeSession",
26927
- kind: "async"
26928
- }),
26929
- sendAndWait: channel({
26930
- channelName: "session.sendAndWait",
26931
- kind: "async"
26932
- })
26933
- });
27831
+ var gitHubCopilotChannels = defineChannels(
27832
+ "@github/copilot-sdk",
27833
+ {
27834
+ createSession: channel({
27835
+ channelName: "client.createSession",
27836
+ kind: "async"
27837
+ }),
27838
+ resumeSession: channel({
27839
+ channelName: "client.resumeSession",
27840
+ kind: "async"
27841
+ }),
27842
+ sendAndWait: channel({
27843
+ channelName: "session.sendAndWait",
27844
+ kind: "async"
27845
+ })
27846
+ },
27847
+ { instrumentationName: INSTRUMENTATION_NAMES.GITHUB_COPILOT }
27848
+ );
26934
27849
 
26935
27850
  // src/instrumentation/plugins/github-copilot-plugin.ts
26936
27851
  var ROOT_AGENT_KEY = "__root__";
@@ -27021,11 +27936,16 @@ async function handleTurnStart(state, agentId) {
27021
27936
  return;
27022
27937
  }
27023
27938
  const parentId = await getParentIdForAgent(state, agentId);
27024
- const span = startSpan({
27025
- name: "Copilot Turn",
27026
- parent: parentId,
27027
- spanAttributes: { type: "task" /* TASK */ }
27028
- });
27939
+ const span = startSpan(
27940
+ withSpanInstrumentationName(
27941
+ {
27942
+ name: "Copilot Turn",
27943
+ parent: parentId,
27944
+ spanAttributes: { type: "task" /* TASK */ }
27945
+ },
27946
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
27947
+ )
27948
+ );
27029
27949
  const pendingUserMessage = state.pendingUserMessages.get(key);
27030
27950
  if (pendingUserMessage) {
27031
27951
  span.log({ input: pendingUserMessage });
@@ -27056,11 +27976,16 @@ async function handleUsage(state, agentId, usage) {
27056
27976
  const parentId = turn ? await turn.id : await state.session.id;
27057
27977
  const content = state.currentMessageContent.get(key);
27058
27978
  const { metrics, metadata } = extractMetricsFromUsage(usage);
27059
- const llmSpan = startSpan({
27060
- name: "github.copilot.llm",
27061
- parent: parentId,
27062
- spanAttributes: { type: "llm" /* LLM */ }
27063
- });
27979
+ const llmSpan = startSpan(
27980
+ withSpanInstrumentationName(
27981
+ {
27982
+ name: "github.copilot.llm",
27983
+ parent: parentId,
27984
+ spanAttributes: { type: "llm" /* LLM */ }
27985
+ },
27986
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
27987
+ )
27988
+ );
27064
27989
  llmSpan.log({
27065
27990
  output: content ?? void 0,
27066
27991
  metadata,
@@ -27086,11 +28011,16 @@ async function handleToolStart(state, agentId, toolCallId, toolName, args, mcpSe
27086
28011
  }
27087
28012
  const parentId = await getToolParentId(state, agentId);
27088
28013
  const displayName = mcpServerName ? `tool: ${mcpServerName}/${toolName}` : `tool: ${toolName}`;
27089
- const span = startSpan({
27090
- name: displayName,
27091
- parent: parentId,
27092
- spanAttributes: { type: "tool" /* TOOL */ }
27093
- });
28014
+ const span = startSpan(
28015
+ withSpanInstrumentationName(
28016
+ {
28017
+ name: displayName,
28018
+ parent: parentId,
28019
+ spanAttributes: { type: "tool" /* TOOL */ }
28020
+ },
28021
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
28022
+ )
28023
+ );
27094
28024
  const metadata = {
27095
28025
  "gen_ai.tool.name": toolName,
27096
28026
  "gen_ai.tool.call.id": toolCallId
@@ -27126,11 +28056,16 @@ async function handleSubagentStarted(state, agentId, toolCallId, agentDisplayNam
27126
28056
  }
27127
28057
  const tool = state.activeTools.get(toolCallId);
27128
28058
  const parentId = tool ? await tool.id : await state.session.id;
27129
- const span = startSpan({
27130
- name: `Agent: ${agentDisplayName}`,
27131
- parent: parentId,
27132
- spanAttributes: { type: "task" /* TASK */ }
27133
- });
28059
+ const span = startSpan(
28060
+ withSpanInstrumentationName(
28061
+ {
28062
+ name: `Agent: ${agentDisplayName}`,
28063
+ parent: parentId,
28064
+ spanAttributes: { type: "task" /* TASK */ }
28065
+ },
28066
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
28067
+ )
28068
+ );
27134
28069
  span.log({
27135
28070
  metadata: {
27136
28071
  "github_copilot.agent_name": agentDisplayName,
@@ -27356,10 +28291,15 @@ function makeSessionHandlers(sessionStates, configArgIndex, includeProviderMetad
27356
28291
  if (!config || typeof config !== "object") {
27357
28292
  return;
27358
28293
  }
27359
- const sessionSpan = startSpan({
27360
- name: "Copilot Session",
27361
- spanAttributes: { type: "task" /* TASK */ }
27362
- });
28294
+ const sessionSpan = startSpan(
28295
+ withSpanInstrumentationName(
28296
+ {
28297
+ name: "Copilot Session",
28298
+ spanAttributes: { type: "task" /* TASK */ }
28299
+ },
28300
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
28301
+ )
28302
+ );
27363
28303
  const metadata = {};
27364
28304
  if (config.model) {
27365
28305
  metadata["github_copilot.model"] = config.model;
@@ -27447,12 +28387,16 @@ var GitHubCopilotPlugin = class extends BasePlugin {
27447
28387
  };
27448
28388
 
27449
28389
  // src/instrumentation/plugins/flue-channels.ts
27450
- var flueChannels = defineChannels("@flue/runtime", {
27451
- createContext: channel({
27452
- channelName: "createFlueContext",
27453
- kind: "sync-stream"
27454
- })
27455
- });
28390
+ var flueChannels = defineChannels(
28391
+ "@flue/runtime",
28392
+ {
28393
+ createContext: channel({
28394
+ channelName: "createFlueContext",
28395
+ kind: "sync-stream"
28396
+ })
28397
+ },
28398
+ { instrumentationName: INSTRUMENTATION_NAMES.FLUE }
28399
+ );
27456
28400
 
27457
28401
  // src/instrumentation/plugins/flue-plugin.ts
27458
28402
  var FLUE_AUTO_STATE = /* @__PURE__ */ Symbol.for("braintrust.flue.auto-state");
@@ -27795,15 +28739,20 @@ var FlueObserveBridge = class {
27795
28739
  safeLog3(existing.span, { input, metadata });
27796
28740
  return;
27797
28741
  }
27798
- const span = startSpan({
27799
- name: `workflow:${workflowName}`,
27800
- spanAttributes: { type: "task" /* TASK */ },
27801
- startTime: eventTime(event.startedAt ?? event.timestamp),
27802
- event: {
27803
- input,
27804
- metadata
27805
- }
27806
- });
28742
+ const span = startSpan(
28743
+ withSpanInstrumentationName(
28744
+ {
28745
+ name: `workflow:${workflowName}`,
28746
+ spanAttributes: { type: "task" /* TASK */ },
28747
+ startTime: eventTime(event.startedAt ?? event.timestamp),
28748
+ event: {
28749
+ input,
28750
+ metadata
28751
+ }
28752
+ },
28753
+ INSTRUMENTATION_NAMES.FLUE
28754
+ )
28755
+ );
27807
28756
  this.runsById.set(event.runId, { metadata, span });
27808
28757
  }
27809
28758
  handleRunResume(event, ctx) {
@@ -27823,12 +28772,17 @@ var FlueObserveBridge = class {
27823
28772
  safeLog3(existing.span, { metadata });
27824
28773
  return;
27825
28774
  }
27826
- const span = startSpan({
27827
- name: `workflow:${workflowName}`,
27828
- spanAttributes: { type: "task" /* TASK */ },
27829
- startTime: eventTime(event.startedAt ?? event.timestamp),
27830
- event: { metadata }
27831
- });
28775
+ const span = startSpan(
28776
+ withSpanInstrumentationName(
28777
+ {
28778
+ name: `workflow:${workflowName}`,
28779
+ spanAttributes: { type: "task" /* TASK */ },
28780
+ startTime: eventTime(event.startedAt ?? event.timestamp),
28781
+ event: { metadata }
28782
+ },
28783
+ INSTRUMENTATION_NAMES.FLUE
28784
+ )
28785
+ );
27832
28786
  this.runsById.set(event.runId, { metadata, span });
27833
28787
  }
27834
28788
  handleRunEnd(event) {
@@ -28467,7 +29421,14 @@ function stateMatchesRun(state, runId) {
28467
29421
  return state.metadata["flue.run_id"] === runId;
28468
29422
  }
28469
29423
  function startFlueSpan(parent, args) {
28470
- return parent ? withCurrent(parent, () => startSpan(args)) : startSpan(args);
29424
+ return parent ? withCurrent(
29425
+ parent,
29426
+ () => startSpan(
29427
+ withSpanInstrumentationName(args, INSTRUMENTATION_NAMES.FLUE)
29428
+ )
29429
+ ) : startSpan(
29430
+ withSpanInstrumentationName(args, INSTRUMENTATION_NAMES.FLUE)
29431
+ );
28471
29432
  }
28472
29433
  function runWithCurrentSpanStore(span, next) {
28473
29434
  const state = _internalGetGlobalState();
@@ -28557,9 +29518,13 @@ var BraintrustLangChainCallbackHandler = class {
28557
29518
  ...this.options.debug ? { runId, parentRunId } : {}
28558
29519
  }
28559
29520
  };
28560
- let span = parentSpan.startSpan(args);
29521
+ const spanArgs = withSpanInstrumentationName(
29522
+ args,
29523
+ INSTRUMENTATION_NAMES.LANGCHAIN
29524
+ );
29525
+ let span = parentSpan.startSpan(spanArgs);
28561
29526
  if (!Object.is(this.options.logger, NOOP_SPAN) && Object.is(span, NOOP_SPAN)) {
28562
- span = initLogger().startSpan(args);
29527
+ span = initLogger().startSpan(spanArgs);
28563
29528
  }
28564
29529
  this.spans.set(runId, span);
28565
29530
  }
@@ -28856,16 +29821,20 @@ function isRecord(value) {
28856
29821
  }
28857
29822
 
28858
29823
  // src/instrumentation/plugins/langchain-channels.ts
28859
- var langChainChannels = defineChannels("@langchain/core", {
28860
- configure: channel({
28861
- channelName: "CallbackManager.configure",
28862
- kind: "sync-stream"
28863
- }),
28864
- configureSync: channel({
28865
- channelName: "CallbackManager._configureSync",
28866
- kind: "sync-stream"
28867
- })
28868
- });
29824
+ var langChainChannels = defineChannels(
29825
+ "@langchain/core",
29826
+ {
29827
+ configure: channel({
29828
+ channelName: "CallbackManager.configure",
29829
+ kind: "sync-stream"
29830
+ }),
29831
+ configureSync: channel({
29832
+ channelName: "CallbackManager._configureSync",
29833
+ kind: "sync-stream"
29834
+ })
29835
+ },
29836
+ { instrumentationName: INSTRUMENTATION_NAMES.LANGCHAIN }
29837
+ );
28869
29838
 
28870
29839
  // src/instrumentation/plugins/langchain-plugin.ts
28871
29840
  var LangChainPlugin = class extends BasePlugin {
@@ -28953,20 +29922,24 @@ function isBraintrustHandler(handler) {
28953
29922
  }
28954
29923
 
28955
29924
  // src/instrumentation/plugins/langsmith-channels.ts
28956
- var langSmithChannels = defineChannels("langsmith", {
28957
- createRun: channel({
28958
- channelName: "Client.createRun",
28959
- kind: "async"
28960
- }),
28961
- updateRun: channel({
28962
- channelName: "Client.updateRun",
28963
- kind: "async"
28964
- }),
28965
- batchIngestRuns: channel({
28966
- channelName: "Client.batchIngestRuns",
28967
- kind: "async"
28968
- })
28969
- });
29925
+ var langSmithChannels = defineChannels(
29926
+ "langsmith",
29927
+ {
29928
+ createRun: channel({
29929
+ channelName: "Client.createRun",
29930
+ kind: "async"
29931
+ }),
29932
+ updateRun: channel({
29933
+ channelName: "Client.updateRun",
29934
+ kind: "async"
29935
+ }),
29936
+ batchIngestRuns: channel({
29937
+ channelName: "Client.batchIngestRuns",
29938
+ kind: "async"
29939
+ })
29940
+ },
29941
+ { instrumentationName: INSTRUMENTATION_NAMES.LANGSMITH }
29942
+ );
28970
29943
 
28971
29944
  // src/instrumentation/plugins/langsmith-plugin.ts
28972
29945
  var MAX_COMPLETED_RUNS = 1e4;
@@ -29130,19 +30103,24 @@ var LangSmithPlugin = class extends BasePlugin {
29130
30103
  const traceId = stringValue2(ownValue(run, "trace_id")) ?? id;
29131
30104
  const parentId = stringValue2(ownValue(run, "parent_run_id")) ?? stringValue2(ownValue(ownValue(run, "parent_run"), "id"));
29132
30105
  const startTime = timestampSeconds(ownValue(run, "start_time"));
29133
- return startSpan({
29134
- name: stringValue2(ownValue(run, "name")) ?? "LangSmith run",
29135
- spanId: id,
29136
- parentSpanIds: {
29137
- parentSpanIds: parentId ? [parentId] : [],
29138
- rootSpanId: traceId
29139
- },
29140
- spanAttributes: {
29141
- type: mapRunType(ownValue(run, "run_type"))
29142
- },
29143
- ...startTime === void 0 ? {} : { startTime },
29144
- event: { id }
29145
- });
30106
+ return startSpan(
30107
+ withSpanInstrumentationName(
30108
+ {
30109
+ name: stringValue2(ownValue(run, "name")) ?? "LangSmith run",
30110
+ spanId: id,
30111
+ parentSpanIds: {
30112
+ parentSpanIds: parentId ? [parentId] : [],
30113
+ rootSpanId: traceId
30114
+ },
30115
+ spanAttributes: {
30116
+ type: mapRunType(ownValue(run, "run_type"))
30117
+ },
30118
+ ...startTime === void 0 ? {} : { startTime },
30119
+ event: { id }
30120
+ },
30121
+ INSTRUMENTATION_NAMES.LANGSMITH
30122
+ )
30123
+ );
29146
30124
  }
29147
30125
  logRun(span, run, previous, includeOutput) {
29148
30126
  const inputs = preferOwnValue(run, previous, "inputs");
@@ -29400,7 +30378,8 @@ var piCodingAgentChannels = defineChannels(
29400
30378
  channelName: "AgentSession.prompt",
29401
30379
  kind: "async"
29402
30380
  })
29403
- }
30381
+ },
30382
+ { instrumentationName: INSTRUMENTATION_NAMES.PI_CODING_AGENT }
29404
30383
  );
29405
30384
 
29406
30385
  // src/instrumentation/plugins/pi-coding-agent-plugin.ts
@@ -29484,14 +30463,19 @@ function startPiPromptRun(event, onFinalize) {
29484
30463
  ...session.model?.id || agent.state?.model?.id ? { model: session.model?.id ?? agent.state?.model?.id } : {},
29485
30464
  ...event.moduleVersion ? { "pi_coding_agent.version": event.moduleVersion } : {}
29486
30465
  };
29487
- const span = startSpan({
29488
- event: {
29489
- input: extractPromptInput(event.arguments[0], event.arguments[1]),
29490
- metadata
29491
- },
29492
- name: "AgentSession.prompt",
29493
- spanAttributes: { type: "task" /* TASK */ }
29494
- });
30466
+ const span = startSpan(
30467
+ withSpanInstrumentationName(
30468
+ {
30469
+ event: {
30470
+ input: extractPromptInput(event.arguments[0], event.arguments[1]),
30471
+ metadata
30472
+ },
30473
+ name: "AgentSession.prompt",
30474
+ spanAttributes: { type: "task" /* TASK */ }
30475
+ },
30476
+ INSTRUMENTATION_NAMES.PI_CODING_AGENT
30477
+ )
30478
+ );
29495
30479
  const streamPatchState = installPiStreamPatch(agent);
29496
30480
  const options = event.arguments[1];
29497
30481
  const promptText = event.arguments[0];
@@ -29661,15 +30645,20 @@ async function startPiLlmSpan(state, model, context, options) {
29661
30645
  ...extractToolMetadata(context.tools),
29662
30646
  "pi_coding_agent.operation": "agent.streamFn"
29663
30647
  };
29664
- const span = startSpan({
29665
- event: {
29666
- input: processInputAttachments(normalizePiContextInput(context)),
29667
- metadata
29668
- },
29669
- name: getLlmSpanName(model),
29670
- parent: await state.span.export(),
29671
- spanAttributes: { type: "llm" /* LLM */ }
29672
- });
30648
+ const span = startSpan(
30649
+ withSpanInstrumentationName(
30650
+ {
30651
+ event: {
30652
+ input: processInputAttachments(normalizePiContextInput(context)),
30653
+ metadata
30654
+ },
30655
+ name: getLlmSpanName(model),
30656
+ parent: await state.span.export(),
30657
+ spanAttributes: { type: "llm" /* LLM */ }
30658
+ },
30659
+ INSTRUMENTATION_NAMES.PI_CODING_AGENT
30660
+ )
30661
+ );
29673
30662
  const llmState = {
29674
30663
  finalized: false,
29675
30664
  metadata,
@@ -29837,15 +30826,20 @@ async function startPiToolSpan(state, event) {
29837
30826
  "pi_coding_agent.tool.name": event.toolName
29838
30827
  };
29839
30828
  try {
29840
- const span = startSpan({
29841
- event: {
29842
- input: event.args,
29843
- metadata
29844
- },
29845
- name: event.toolName || "tool",
29846
- parent: await state.span.export(),
29847
- spanAttributes: { type: "tool" /* TOOL */ }
29848
- });
30829
+ const span = startSpan(
30830
+ withSpanInstrumentationName(
30831
+ {
30832
+ event: {
30833
+ input: event.args,
30834
+ metadata
30835
+ },
30836
+ name: event.toolName || "tool",
30837
+ parent: await state.span.export(),
30838
+ spanAttributes: { type: "tool" /* TOOL */ }
30839
+ },
30840
+ INSTRUMENTATION_NAMES.PI_CODING_AGENT
30841
+ )
30842
+ );
29849
30843
  state.activeToolSpans.set(event.toolCallId, {
29850
30844
  restoreAutoInstrumentation,
29851
30845
  span
@@ -30277,20 +31271,24 @@ function logInstrumentationError4(context, error) {
30277
31271
  }
30278
31272
 
30279
31273
  // src/instrumentation/plugins/strands-agent-sdk-channels.ts
30280
- var strandsAgentSDKChannels = defineChannels("@strands-agents/sdk", {
30281
- agentStream: channel({
30282
- channelName: "Agent.stream",
30283
- kind: "sync-stream"
30284
- }),
30285
- graphStream: channel({
30286
- channelName: "Graph.stream",
30287
- kind: "sync-stream"
30288
- }),
30289
- swarmStream: channel({
30290
- channelName: "Swarm.stream",
30291
- kind: "sync-stream"
30292
- })
30293
- });
31274
+ var strandsAgentSDKChannels = defineChannels(
31275
+ "@strands-agents/sdk",
31276
+ {
31277
+ agentStream: channel({
31278
+ channelName: "Agent.stream",
31279
+ kind: "sync-stream"
31280
+ }),
31281
+ graphStream: channel({
31282
+ channelName: "Graph.stream",
31283
+ kind: "sync-stream"
31284
+ }),
31285
+ swarmStream: channel({
31286
+ channelName: "Swarm.stream",
31287
+ kind: "sync-stream"
31288
+ })
31289
+ },
31290
+ { instrumentationName: INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK }
31291
+ );
30294
31292
 
30295
31293
  // src/instrumentation/plugins/strands-agent-sdk-plugin.ts
30296
31294
  var MAX_STRANDS_STRING_ATTACHMENT_CACHE_ENTRIES = 32;
@@ -30445,22 +31443,32 @@ function startAgentStream(event, activeChildParents) {
30445
31443
  );
30446
31444
  const span = parentSpan ? withCurrent(
30447
31445
  parentSpan,
30448
- () => startSpan({
30449
- event: {
30450
- input,
30451
- metadata
31446
+ () => startSpan(
31447
+ withSpanInstrumentationName(
31448
+ {
31449
+ event: {
31450
+ input,
31451
+ metadata
31452
+ },
31453
+ name: formatAgentSpanName(agent),
31454
+ spanAttributes: { type: "task" /* TASK */ }
31455
+ },
31456
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
31457
+ )
31458
+ )
31459
+ ) : startSpan(
31460
+ withSpanInstrumentationName(
31461
+ {
31462
+ event: {
31463
+ input,
31464
+ metadata
31465
+ },
31466
+ name: formatAgentSpanName(agent),
31467
+ spanAttributes: { type: "task" /* TASK */ }
30452
31468
  },
30453
- name: formatAgentSpanName(agent),
30454
- spanAttributes: { type: "task" /* TASK */ }
30455
- })
30456
- ) : startSpan({
30457
- event: {
30458
- input,
30459
- metadata
30460
- },
30461
- name: formatAgentSpanName(agent),
30462
- spanAttributes: { type: "task" /* TASK */ }
30463
- });
31469
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
31470
+ )
31471
+ );
30464
31472
  return {
30465
31473
  activeTools: /* @__PURE__ */ new Map(),
30466
31474
  attachmentCache,
@@ -30482,22 +31490,32 @@ function startMultiAgentStream(event, operation, activeChildParents) {
30482
31490
  const input = processStrandsInputAttachments(event.arguments[0]);
30483
31491
  const span = parentSpan ? withCurrent(
30484
31492
  parentSpan,
30485
- () => startSpan({
30486
- event: {
30487
- input,
30488
- metadata
31493
+ () => startSpan(
31494
+ withSpanInstrumentationName(
31495
+ {
31496
+ event: {
31497
+ input,
31498
+ metadata
31499
+ },
31500
+ name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
31501
+ spanAttributes: { type: "task" /* TASK */ }
31502
+ },
31503
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
31504
+ )
31505
+ )
31506
+ ) : startSpan(
31507
+ withSpanInstrumentationName(
31508
+ {
31509
+ event: {
31510
+ input,
31511
+ metadata
31512
+ },
31513
+ name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
31514
+ spanAttributes: { type: "task" /* TASK */ }
30489
31515
  },
30490
- name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
30491
- spanAttributes: { type: "task" /* TASK */ }
30492
- })
30493
- ) : startSpan({
30494
- event: {
30495
- input,
30496
- metadata
30497
- },
30498
- name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
30499
- spanAttributes: { type: "task" /* TASK */ }
30500
- });
31516
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
31517
+ )
31518
+ );
30501
31519
  return {
30502
31520
  activeNodes: /* @__PURE__ */ new Map(),
30503
31521
  finalized: false,
@@ -30599,17 +31617,22 @@ function startModelSpan(state, event) {
30599
31617
  };
30600
31618
  const span = withCurrent(
30601
31619
  state.span,
30602
- () => startSpan({
30603
- event: {
30604
- input: Array.isArray(event.agent?.messages) ? processStrandsInputAttachments(
30605
- event.agent.messages,
30606
- state.attachmentCache
30607
- ) : void 0,
30608
- metadata
30609
- },
30610
- name: formatModelSpanName(model),
30611
- spanAttributes: { type: "llm" /* LLM */ }
30612
- })
31620
+ () => startSpan(
31621
+ withSpanInstrumentationName(
31622
+ {
31623
+ event: {
31624
+ input: Array.isArray(event.agent?.messages) ? processStrandsInputAttachments(
31625
+ event.agent.messages,
31626
+ state.attachmentCache
31627
+ ) : void 0,
31628
+ metadata
31629
+ },
31630
+ name: formatModelSpanName(model),
31631
+ spanAttributes: { type: "llm" /* LLM */ }
31632
+ },
31633
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
31634
+ )
31635
+ )
30613
31636
  );
30614
31637
  state.activeModel = {
30615
31638
  metadata,
@@ -30661,20 +31684,25 @@ function startToolSpan2(state, event) {
30661
31684
  const name = extractToolName3(toolUse, event.tool);
30662
31685
  const span = withCurrent(
30663
31686
  state.span,
30664
- () => startSpan({
30665
- event: {
30666
- input: toolUse?.input,
30667
- metadata: {
30668
- "gen_ai.tool.call.id": toolUse?.toolUseId,
30669
- "gen_ai.tool.name": name,
30670
- "strands.operation": "tool.call",
30671
- "strands.tool.name": name,
30672
- provider: "strands"
30673
- }
30674
- },
30675
- name: `tool: ${name}`,
30676
- spanAttributes: { type: "tool" /* TOOL */ }
30677
- })
31687
+ () => startSpan(
31688
+ withSpanInstrumentationName(
31689
+ {
31690
+ event: {
31691
+ input: toolUse?.input,
31692
+ metadata: {
31693
+ "gen_ai.tool.call.id": toolUse?.toolUseId,
31694
+ "gen_ai.tool.name": name,
31695
+ "strands.operation": "tool.call",
31696
+ "strands.tool.name": name,
31697
+ provider: "strands"
31698
+ }
31699
+ },
31700
+ name: `tool: ${name}`,
31701
+ spanAttributes: { type: "tool" /* TOOL */ }
31702
+ },
31703
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
31704
+ )
31705
+ )
30678
31706
  );
30679
31707
  state.activeTools.set(key, {
30680
31708
  span,
@@ -30745,11 +31773,16 @@ function startNodeSpan(state, event, activeChildParents) {
30745
31773
  };
30746
31774
  const span = withCurrent(
30747
31775
  state.span,
30748
- () => startSpan({
30749
- event: { metadata },
30750
- name: `node: ${nodeId}`,
30751
- spanAttributes: { type: "task" /* TASK */ }
30752
- })
31776
+ () => startSpan(
31777
+ withSpanInstrumentationName(
31778
+ {
31779
+ event: { metadata },
31780
+ name: `node: ${nodeId}`,
31781
+ spanAttributes: { type: "task" /* TASK */ }
31782
+ },
31783
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
31784
+ )
31785
+ )
30753
31786
  );
30754
31787
  const nodeState = {
30755
31788
  ...child ? { child } : {},
@@ -31863,17 +32896,20 @@ var BraintrustObservabilityExporter = class {
31863
32896
  }
31864
32897
  onStart(exported) {
31865
32898
  if (this.spans.has(exported.id)) return;
31866
- const args = {
31867
- name: exported.name,
31868
- spanAttributes: { type: spanTypeFor(exported.type) },
31869
- startTime: epochSeconds(exported.startTime),
31870
- // Use the Mastra span id as the Braintrust row id so that
31871
- // `logFeedback({ id: <mastra span id> })` (and Mastra's score events)
31872
- // attach to the right row. Without this, `SpanImpl` auto-generates a
31873
- // row id (`this._id = eventId ?? idGenerator.getSpanId()`) that no
31874
- // external caller could know.
31875
- event: { id: exported.id }
31876
- };
32899
+ const args = withSpanInstrumentationName(
32900
+ {
32901
+ name: exported.name,
32902
+ spanAttributes: { type: spanTypeFor(exported.type) },
32903
+ startTime: epochSeconds(exported.startTime),
32904
+ // Use the Mastra span id as the Braintrust row id so that
32905
+ // `logFeedback({ id: <mastra span id> })` (and Mastra's score events)
32906
+ // attach to the right row. Without this, `SpanImpl` auto-generates a
32907
+ // row id (`this._id = eventId ?? idGenerator.getSpanId()`) that no
32908
+ // external caller could know.
32909
+ event: { id: exported.id }
32910
+ },
32911
+ INSTRUMENTATION_NAMES.MASTRA
32912
+ );
31877
32913
  const parentRecord = exported.parentSpanId ? this.spans.get(exported.parentSpanId) : void 0;
31878
32914
  if (!this.capturedParent) {
31879
32915
  const probe = currentSpan();
@@ -32030,6 +33066,12 @@ function configureNode() {
32030
33066
  isomorph_default.gzip = promisify(zlib.gzip);
32031
33067
  isomorph_default.gunzip = promisify(zlib.gunzip);
32032
33068
  isomorph_default.hash = (data) => crypto.createHash("sha256").update(data).digest("hex");
33069
+ isomorph_default.hmacSha256 = (key, data) => crypto.createHmac("sha256", key).update(data).digest("hex");
33070
+ isomorph_default.timingSafeEqual = (left, right) => {
33071
+ const leftBuffer = Buffer.from(left);
33072
+ const rightBuffer = Buffer.from(right);
33073
+ return leftBuffer.length === rightBuffer.length && crypto.timingSafeEqual(leftBuffer, rightBuffer);
33074
+ };
32033
33075
  _internalSetInitialState();
32034
33076
  const disabled = readDisabledInstrumentationEnvConfig(
32035
33077
  isomorph_default.getEnv("BRAINTRUST_DISABLE_INSTRUMENTATION")
@@ -34352,26 +35394,30 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
34352
35394
  }
34353
35395
  }
34354
35396
  })();
35397
+ let timeoutId;
35398
+ let abortHandler;
35399
+ const cleanupCancellation = () => {
35400
+ if (timeoutId !== void 0) {
35401
+ clearTimeout(timeoutId);
35402
+ timeoutId = void 0;
35403
+ }
35404
+ if (abortHandler && evaluator.signal) {
35405
+ evaluator.signal.removeEventListener("abort", abortHandler);
35406
+ abortHandler = void 0;
35407
+ }
35408
+ };
34355
35409
  const cancel = async () => {
34356
35410
  await new Promise((_, reject2) => {
34357
35411
  if (cancelled) {
34358
35412
  reject2(new InternalAbortError("Evaluator already cancelled"));
34359
35413
  return;
34360
35414
  }
34361
- let timeoutId;
34362
- let abortHandler;
34363
35415
  const rejectOnce = (error) => {
34364
35416
  if (cancelled) {
34365
35417
  return;
34366
35418
  }
34367
35419
  cancelled = true;
34368
- if (timeoutId) {
34369
- clearTimeout(timeoutId);
34370
- timeoutId = void 0;
34371
- }
34372
- if (abortHandler && evaluator.signal) {
34373
- evaluator.signal.removeEventListener("abort", abortHandler);
34374
- }
35420
+ cleanupCancellation();
34375
35421
  reject2(error);
34376
35422
  };
34377
35423
  if (evaluator.timeout) {
@@ -34411,6 +35457,7 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
34411
35457
  }
34412
35458
  throw e;
34413
35459
  } finally {
35460
+ cleanupCancellation();
34414
35461
  if (!collectResults) {
34415
35462
  collectedResults.length = 0;
34416
35463
  }