braintrust 3.23.1 → 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 (51) hide show
  1. package/dev/dist/index.d.mts +11 -0
  2. package/dev/dist/index.d.ts +11 -0
  3. package/dev/dist/index.js +2881 -1518
  4. package/dev/dist/index.mjs +2298 -935
  5. package/dist/apply-auto-instrumentation.js +218 -195
  6. package/dist/apply-auto-instrumentation.mjs +30 -7
  7. package/dist/auto-instrumentations/bundler/esbuild.cjs +618 -444
  8. package/dist/auto-instrumentations/bundler/esbuild.mjs +2 -2
  9. package/dist/auto-instrumentations/bundler/next.cjs +618 -444
  10. package/dist/auto-instrumentations/bundler/next.mjs +3 -3
  11. package/dist/auto-instrumentations/bundler/rollup.cjs +618 -444
  12. package/dist/auto-instrumentations/bundler/rollup.mjs +2 -2
  13. package/dist/auto-instrumentations/bundler/vite.cjs +618 -444
  14. package/dist/auto-instrumentations/bundler/vite.d.mts +1 -1
  15. package/dist/auto-instrumentations/bundler/vite.d.ts +1 -1
  16. package/dist/auto-instrumentations/bundler/vite.mjs +2 -2
  17. package/dist/auto-instrumentations/bundler/webpack-loader.cjs +618 -444
  18. package/dist/auto-instrumentations/bundler/webpack.cjs +618 -444
  19. package/dist/auto-instrumentations/bundler/webpack.mjs +3 -3
  20. package/dist/auto-instrumentations/{chunk-KIMLYPRW.mjs → chunk-7P6563SW.mjs} +1 -1
  21. package/dist/auto-instrumentations/{chunk-YXLNSAMJ.mjs → chunk-CZ24KNHT.mjs} +591 -424
  22. package/dist/auto-instrumentations/{chunk-EXY7QCJD.mjs → chunk-JPVCUKTY.mjs} +30 -21
  23. package/dist/auto-instrumentations/hook.mjs +778 -457
  24. package/dist/auto-instrumentations/index.cjs +590 -424
  25. package/dist/auto-instrumentations/index.mjs +1 -1
  26. package/dist/browser.d.mts +138 -9
  27. package/dist/browser.d.ts +138 -9
  28. package/dist/browser.js +2700 -1011
  29. package/dist/browser.mjs +2700 -1011
  30. package/dist/{chunk-RBXD2KYN.mjs → chunk-2SANLSWX.mjs} +1577 -513
  31. package/dist/{chunk-36IPYKMG.mjs → chunk-ABR2QWDP.mjs} +704 -438
  32. package/dist/{chunk-B6ZQIAK3.js → chunk-GSIDVFE6.js} +2361 -1297
  33. package/dist/{chunk-CDIKAHDZ.js → chunk-P25IOOU4.js} +706 -440
  34. package/dist/cli.js +2307 -940
  35. package/dist/edge-light.js +2700 -1011
  36. package/dist/edge-light.mjs +2700 -1011
  37. package/dist/index.d.mts +138 -9
  38. package/dist/index.d.ts +138 -9
  39. package/dist/index.js +955 -551
  40. package/dist/index.mjs +493 -89
  41. package/dist/instrumentation/index.d.mts +135 -9
  42. package/dist/instrumentation/index.d.ts +135 -9
  43. package/dist/instrumentation/index.js +2554 -1009
  44. package/dist/instrumentation/index.mjs +2554 -1009
  45. package/dist/vitest-evals-reporter.js +17 -16
  46. package/dist/vitest-evals-reporter.mjs +3 -2
  47. package/dist/workerd.js +2700 -1011
  48. package/dist/workerd.mjs +2700 -1011
  49. package/package.json +4 -4
  50. package/util/dist/index.js +4 -0
  51. package/util/dist/index.mjs +4 -0
@@ -115,6 +115,7 @@ var DefaultChannel = class {
115
115
  constructor(name) {
116
116
  this.name = name;
117
117
  }
118
+ name;
118
119
  hasSubscribers = false;
119
120
  subscribe(_subscription) {
120
121
  }
@@ -1381,6 +1382,7 @@ var SpanComponentsV3 = class _SpanComponentsV3 {
1381
1382
  constructor(data) {
1382
1383
  this.data = data;
1383
1384
  }
1385
+ data;
1384
1386
  toStr() {
1385
1387
  const jsonObj = {
1386
1388
  compute_object_metadata_args: this.data.compute_object_metadata_args || void 0,
@@ -1892,6 +1894,7 @@ var SpanComponentsV4 = class _SpanComponentsV4 {
1892
1894
  constructor(data) {
1893
1895
  this.data = data;
1894
1896
  }
1897
+ data;
1895
1898
  toStr() {
1896
1899
  const jsonObj = {
1897
1900
  compute_object_metadata_args: this.data.compute_object_metadata_args || void 0,
@@ -5138,6 +5141,144 @@ var SpanCache = class {
5138
5141
  }
5139
5142
  };
5140
5143
 
5144
+ // src/span-origin.ts
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
+ }
5190
+ function detectSpanOriginEnvironment(explicit) {
5191
+ if (explicit) return explicit;
5192
+ const envType = isomorph_default.getEnv("BRAINTRUST_ENVIRONMENT_TYPE");
5193
+ const envName = isomorph_default.getEnv("BRAINTRUST_ENVIRONMENT_NAME");
5194
+ if (envType || envName) {
5195
+ return {
5196
+ ...envType ? { type: envType } : {},
5197
+ ...envName ? { name: envName } : {}
5198
+ };
5199
+ }
5200
+ const ci = firstPresent([
5201
+ ["GITHUB_ACTIONS", "github_actions"],
5202
+ ["GITLAB_CI", "gitlab_ci"],
5203
+ ["CIRCLECI", "circleci"],
5204
+ ["BUILDKITE", "buildkite"],
5205
+ ["JENKINS_URL", "jenkins"],
5206
+ ["JENKINS_HOME", "jenkins"],
5207
+ ["TF_BUILD", "azure_pipelines"],
5208
+ ["TEAMCITY_VERSION", "teamcity"],
5209
+ ["TRAVIS", "travis"],
5210
+ ["BITBUCKET_BUILD_NUMBER", "bitbucket"]
5211
+ ]);
5212
+ if (ci) return { type: "ci", name: ci };
5213
+ if (isomorph_default.getEnv("CI")) return { type: "ci", name: "ci" };
5214
+ const earlyServer = firstPresent([
5215
+ ["VERCEL", "vercel"],
5216
+ ["NETLIFY", "netlify"]
5217
+ ]);
5218
+ if (earlyServer) return { type: "server", name: earlyServer };
5219
+ if (isomorph_default.getEnv("ECS_CONTAINER_METADATA_URI") || isomorph_default.getEnv("ECS_CONTAINER_METADATA_URI_V4")) {
5220
+ return { type: "server", name: "ecs" };
5221
+ }
5222
+ const awsExecutionEnv = isomorph_default.getEnv("AWS_EXECUTION_ENV");
5223
+ if (awsExecutionEnv?.startsWith("AWS_ECS_")) {
5224
+ return { type: "server", name: "ecs" };
5225
+ }
5226
+ if (awsExecutionEnv?.startsWith("AWS_Lambda_")) {
5227
+ return { type: "server", name: "aws_lambda" };
5228
+ }
5229
+ if (isomorph_default.getEnv("AWS_LAMBDA_FUNCTION_NAME")) {
5230
+ return { type: "server", name: "aws_lambda" };
5231
+ }
5232
+ const server = firstPresent([
5233
+ ["K_SERVICE", "cloud_run"],
5234
+ ["FUNCTION_TARGET", "gcp_functions"],
5235
+ ["KUBERNETES_SERVICE_HOST", "kubernetes"],
5236
+ ["DYNO", "heroku"],
5237
+ ["FLY_APP_NAME", "fly"],
5238
+ ["RAILWAY_ENVIRONMENT", "railway"],
5239
+ ["RENDER_SERVICE_NAME", "render"]
5240
+ ]);
5241
+ if (server) return { type: "server", name: server };
5242
+ return deploymentModeEnvironment("NODE_ENV", isomorph_default.getEnv("NODE_ENV"));
5243
+ }
5244
+ function makeSpanOrigin(instrumentationName, environment) {
5245
+ return {
5246
+ name: "braintrust.sdk.javascript",
5247
+ version: SDK_VERSION,
5248
+ instrumentation: { name: instrumentationName },
5249
+ ...environment ? { environment } : {}
5250
+ };
5251
+ }
5252
+ function mergeSpanOriginContext(context, instrumentationName, environment) {
5253
+ const next = { ...context ?? {} };
5254
+ const current = isObject2(next.span_origin) ? { ...next.span_origin } : {};
5255
+ next.span_origin = {
5256
+ ...makeSpanOrigin(instrumentationName, environment),
5257
+ ...current
5258
+ };
5259
+ return next;
5260
+ }
5261
+ function isSpanInstrumentationName(value) {
5262
+ return Object.values(INSTRUMENTATION_NAMES).some((name) => name === value);
5263
+ }
5264
+ function firstPresent(entries) {
5265
+ return entries.find(([key]) => Boolean(isomorph_default.getEnv(key)))?.[1];
5266
+ }
5267
+ function deploymentModeEnvironment(_key, value) {
5268
+ if (!value) return void 0;
5269
+ const normalized = value.toLowerCase();
5270
+ if (normalized === "production" || normalized === "staging") {
5271
+ return { type: "server", name: normalized };
5272
+ }
5273
+ if (normalized === "development" || normalized === "local") {
5274
+ return { type: "local", name: normalized };
5275
+ }
5276
+ return { name: value };
5277
+ }
5278
+ function isObject2(value) {
5279
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5280
+ }
5281
+
5141
5282
  // src/logger.ts
5142
5283
  var BRAINTRUST_ATTACHMENT = BraintrustAttachmentReference.shape.type.value;
5143
5284
  var EXTERNAL_ATTACHMENT = ExternalAttachmentReference.shape.type.value;
@@ -5186,6 +5327,7 @@ var LoginInvalidOrgError = class extends Error {
5186
5327
  super(message);
5187
5328
  this.message = message;
5188
5329
  }
5330
+ message;
5189
5331
  };
5190
5332
  var REDACTION_FIELDS = [
5191
5333
  "input",
@@ -5201,6 +5343,8 @@ var MaskingError = class {
5201
5343
  this.fieldName = fieldName;
5202
5344
  this.errorType = errorType;
5203
5345
  }
5346
+ fieldName;
5347
+ errorType;
5204
5348
  get errorMsg() {
5205
5349
  return `ERROR: Failed to mask field '${this.fieldName}' - ${this.errorType}`;
5206
5350
  }
@@ -5410,7 +5554,10 @@ var BraintrustState = class _BraintrustState {
5410
5554
  diskCache: parametersDiskCache
5411
5555
  });
5412
5556
  this.spanCache = new SpanCache({ disabled: loginParams.disableSpanCache });
5557
+ this.spanOriginEnvironment = detectSpanOriginEnvironment();
5558
+ this._internalSetTraceContextSigningSecret(loginParams.apiKey);
5413
5559
  }
5560
+ loginParams;
5414
5561
  id;
5415
5562
  currentExperiment;
5416
5563
  // Note: the value of IsAsyncFlush doesn't really matter here, since we
@@ -5445,6 +5592,19 @@ var BraintrustState = class _BraintrustState {
5445
5592
  _idGenerator = null;
5446
5593
  _contextManager = null;
5447
5594
  _otelFlushCallback = null;
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
+ }
5448
5608
  resetLoginInfo() {
5449
5609
  this.appUrl = null;
5450
5610
  this.appPublicUrl = null;
@@ -5505,6 +5665,7 @@ var BraintrustState = class _BraintrustState {
5505
5665
  this.gitMetadataSettings = other.gitMetadataSettings;
5506
5666
  this.debugLogLevel = other.debugLogLevel;
5507
5667
  this.debugLogLevelConfigured = other.debugLogLevelConfigured;
5668
+ this.traceContextSigningSecret = other.traceContextSigningSecret;
5508
5669
  setGlobalDebugLogLevel(
5509
5670
  this.debugLogLevelConfigured ? this.debugLogLevel ?? false : void 0
5510
5671
  );
@@ -5592,6 +5753,7 @@ var BraintrustState = class _BraintrustState {
5592
5753
  return this.debugLogLevelConfigured;
5593
5754
  }
5594
5755
  async login(loginParams) {
5756
+ this._internalSetTraceContextSigningSecret(loginParams.apiKey);
5595
5757
  this.setDebugLogLevel(loginParams.debugLogLevel);
5596
5758
  if (this.apiUrl && !loginParams.forceLogin) {
5597
5759
  return;
@@ -6256,6 +6418,28 @@ function updateSpanImpl({
6256
6418
  }));
6257
6419
  state.bgLogger().log([record]);
6258
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
+ }
6259
6443
  function spanComponentsToObjectIdLambda(state, components) {
6260
6444
  if (components.data.object_id) {
6261
6445
  const ret = components.data.object_id;
@@ -7342,6 +7526,7 @@ function init(projectOrOptions, optionalOptions) {
7342
7526
  throw new Error("Cannot open and update an experiment at the same time");
7343
7527
  }
7344
7528
  const state = stateArg ?? _globalState;
7529
+ state._internalSetTraceContextSigningSecret(apiKey);
7345
7530
  state.enforceQueueSizeLimit(false);
7346
7531
  if (open2) {
7347
7532
  if (isEmpty2(experiment)) {
@@ -7798,6 +7983,7 @@ function initLogger(options = {}) {
7798
7983
  orgName,
7799
7984
  forceLogin,
7800
7985
  debugLogLevel,
7986
+ environment,
7801
7987
  fetch: fetch2,
7802
7988
  state: stateArg
7803
7989
  } = options || {};
@@ -7813,7 +7999,9 @@ function initLogger(options = {}) {
7813
7999
  project_id: projectId
7814
8000
  };
7815
8001
  const state = stateArg ?? _globalState;
8002
+ state._internalSetTraceContextSigningSecret(apiKey);
7816
8003
  state.setDebugLogLevel(debugLogLevel);
8004
+ state.spanOriginEnvironment = detectSpanOriginEnvironment(environment);
7817
8005
  state.enforceQueueSizeLimit(true);
7818
8006
  const lazyMetadata = new LazyValue(
7819
8007
  async () => {
@@ -8241,6 +8429,12 @@ function traced(callback, args) {
8241
8429
  function startSpan(args) {
8242
8430
  return startSpanAndIsLogger(args).span;
8243
8431
  }
8432
+ function _internalStartSpanWithInitialMerge(args) {
8433
+ return startSpanAndIsLogger({
8434
+ ...args,
8435
+ [INITIAL_SPAN_WRITE_AS_MERGE]: true
8436
+ }).span;
8437
+ }
8244
8438
  async function flush(options) {
8245
8439
  const state = options?.state ?? _globalState;
8246
8440
  return await state.bgLogger().flush();
@@ -8392,7 +8586,9 @@ function deepCopyEvent(event) {
8392
8586
  const ATTACHMENT_MARKER_KEY = "_bt_internal_saved_attachment_marker";
8393
8587
  const attachmentMarker = ++deepCopyEventMarkerCounter;
8394
8588
  const serialized = JSON.stringify(event, (_k, v) => {
8395
- 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) {
8396
8592
  return `<span>`;
8397
8593
  } else if (v instanceof Experiment2) {
8398
8594
  return `<experiment>`;
@@ -8522,6 +8718,11 @@ var ObjectFetcher = class {
8522
8718
  this._internal_btql = _internal_btql;
8523
8719
  this._internalBrainstoreRealtime = _internalBrainstoreRealtime;
8524
8720
  }
8721
+ objectType;
8722
+ pinnedVersion;
8723
+ mutateRecord;
8724
+ _internal_btql;
8725
+ _internalBrainstoreRealtime;
8525
8726
  _fetchedData = void 0;
8526
8727
  get id() {
8527
8728
  throw new Error("ObjectFetcher subclasses must have an 'id' attribute");
@@ -8960,6 +9161,8 @@ var ReadonlyExperiment = class extends ObjectFetcher {
8960
9161
  this.state = state;
8961
9162
  this.lazyMetadata = lazyMetadata;
8962
9163
  }
9164
+ state;
9165
+ lazyMetadata;
8963
9166
  get id() {
8964
9167
  return (async () => {
8965
9168
  return (await this.lazyMetadata.get()).experiment.id;
@@ -9053,6 +9256,7 @@ var SpanImpl = class _SpanImpl {
9053
9256
  constructor(args) {
9054
9257
  this._state = args.state;
9055
9258
  this._propagatedState = args.propagatedState;
9259
+ const instrumentationName = getSpanInstrumentationName(args) ?? INSTRUMENTATION_NAMES.BRAINTRUST_JS_LOGGER;
9056
9260
  const spanAttributes = args.spanAttributes ?? {};
9057
9261
  const rawEvent = args.event ?? {};
9058
9262
  const type = args.type ?? (args.parentSpanIds ? void 0 : args.defaultRootType);
@@ -9082,7 +9286,11 @@ var SpanImpl = class _SpanImpl {
9082
9286
  metrics: {
9083
9287
  start: args.startTime ?? getCurrentUnixTimestamp()
9084
9288
  },
9085
- context: { ...callerLocation },
9289
+ context: mergeSpanOriginContext(
9290
+ { ...callerLocation },
9291
+ instrumentationName,
9292
+ this._state.spanOriginEnvironment
9293
+ ),
9086
9294
  span_attributes: {
9087
9295
  name,
9088
9296
  type,
@@ -9456,6 +9664,7 @@ var Dataset2 = class extends ObjectFetcher {
9456
9664
  this.pinnedEnvironment = pinState?.pinnedEnvironment;
9457
9665
  this.pinnedSnapshotName = pinState?.pinnedSnapshotName;
9458
9666
  }
9667
+ state;
9459
9668
  lazyMetadata;
9460
9669
  __braintrust_dataset_marker = true;
9461
9670
  newRecords = 0;
@@ -9967,6 +10176,9 @@ var Prompt2 = class _Prompt {
9967
10176
  this.noTrace = noTrace;
9968
10177
  void this.__braintrust_prompt_marker;
9969
10178
  }
10179
+ metadata;
10180
+ defaults;
10181
+ noTrace;
9970
10182
  parsedPromptData;
9971
10183
  hasParsedPromptData = false;
9972
10184
  __braintrust_prompt_marker = true;
@@ -10204,6 +10416,7 @@ var RemoteEvalParameters = class {
10204
10416
  this.metadata = metadata;
10205
10417
  void this.__braintrust_parameters_marker;
10206
10418
  }
10419
+ metadata;
10207
10420
  __braintrust_parameters_marker = true;
10208
10421
  get id() {
10209
10422
  return this.metadata.id;
@@ -10961,15 +11174,25 @@ function hasChoices(value) {
10961
11174
  function normalizeMetadata(metadata) {
10962
11175
  return isObject(metadata) ? metadata : void 0;
10963
11176
  }
10964
- function startSpanForEvent(config, event, channelName) {
11177
+ function startSpanForEvent(config, event, channelName, instrumentationName) {
10965
11178
  const { name, spanAttributes, spanInfoMetadata } = buildStartSpanArgs(
10966
11179
  config,
10967
11180
  event
10968
11181
  );
10969
- const span = startSpan({
10970
- name,
10971
- spanAttributes
10972
- });
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
+ }
10973
11196
  const startTime = getCurrentUnixTimestamp();
10974
11197
  try {
10975
11198
  const { input, metadata } = config.extractInput(
@@ -11000,7 +11223,7 @@ function shouldTraceEvent(config, event, channelName) {
11000
11223
  return true;
11001
11224
  }
11002
11225
  }
11003
- function ensureSpanStateForEvent(states, config, event, channelName) {
11226
+ function ensureSpanStateForEvent(states, config, event, channelName, instrumentationName) {
11004
11227
  const key = event;
11005
11228
  const existing = states.get(key);
11006
11229
  if (existing) {
@@ -11009,11 +11232,16 @@ function ensureSpanStateForEvent(states, config, event, channelName) {
11009
11232
  if (!shouldTraceEvent(config, event, channelName)) {
11010
11233
  return void 0;
11011
11234
  }
11012
- const created = startSpanForEvent(config, event, channelName);
11235
+ const created = startSpanForEvent(
11236
+ config,
11237
+ event,
11238
+ channelName,
11239
+ instrumentationName
11240
+ );
11013
11241
  states.set(key, created);
11014
11242
  return created;
11015
11243
  }
11016
- function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelName) {
11244
+ function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelName, instrumentationName) {
11017
11245
  const state = _internalGetGlobalState();
11018
11246
  const startChannel = tracingChannel2.start;
11019
11247
  const contextManager = state?.contextManager;
@@ -11031,7 +11259,8 @@ function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelNam
11031
11259
  states,
11032
11260
  config,
11033
11261
  event,
11034
- channelName
11262
+ channelName,
11263
+ instrumentationName
11035
11264
  );
11036
11265
  return spanState ? contextManager.wrapSpanForStore(spanState.span) : currentSpanStore.getStore();
11037
11266
  }
@@ -11040,15 +11269,21 @@ function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelNam
11040
11269
  startChannel.unbindStore(currentSpanStore);
11041
11270
  };
11042
11271
  }
11043
- function logErrorAndEnd(states, event) {
11272
+ function logErrorAndEnd(states, event, channelName) {
11044
11273
  const spanData = states.get(event);
11045
11274
  if (!spanData) {
11046
11275
  return;
11047
11276
  }
11048
- spanData.span.log({
11049
- error: event.error.message
11050
- });
11051
- 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
+ }
11052
11287
  states.delete(event);
11053
11288
  }
11054
11289
  function runStreamingCompletionHook(args) {
@@ -11098,7 +11333,8 @@ function traceAsyncChannel(channel2, config) {
11098
11333
  tracingChannel2,
11099
11334
  states,
11100
11335
  config,
11101
- channelName
11336
+ channelName,
11337
+ channel2.instrumentationName
11102
11338
  );
11103
11339
  const handlers = {
11104
11340
  start: (event) => {
@@ -11109,7 +11345,8 @@ function traceAsyncChannel(channel2, config) {
11109
11345
  states,
11110
11346
  config,
11111
11347
  event,
11112
- channelName
11348
+ channelName,
11349
+ channel2.instrumentationName
11113
11350
  );
11114
11351
  },
11115
11352
  asyncEnd: (event) => {
@@ -11146,7 +11383,7 @@ function traceAsyncChannel(channel2, config) {
11146
11383
  }
11147
11384
  },
11148
11385
  error: (event) => {
11149
- logErrorAndEnd(states, event);
11386
+ logErrorAndEnd(states, event, channelName);
11150
11387
  }
11151
11388
  };
11152
11389
  tracingChannel2.subscribe(handlers);
@@ -11163,7 +11400,8 @@ function traceStreamingChannel(channel2, config) {
11163
11400
  tracingChannel2,
11164
11401
  states,
11165
11402
  config,
11166
- channelName
11403
+ channelName,
11404
+ channel2.instrumentationName
11167
11405
  );
11168
11406
  const handlers = {
11169
11407
  start: (event) => {
@@ -11174,7 +11412,8 @@ function traceStreamingChannel(channel2, config) {
11174
11412
  states,
11175
11413
  config,
11176
11414
  event,
11177
- channelName
11415
+ channelName,
11416
+ channel2.instrumentationName
11178
11417
  );
11179
11418
  },
11180
11419
  asyncEnd: (event) => {
@@ -11193,6 +11432,7 @@ function traceStreamingChannel(channel2, config) {
11193
11432
  }
11194
11433
  },
11195
11434
  onComplete: (chunks) => {
11435
+ let completion2;
11196
11436
  try {
11197
11437
  let output;
11198
11438
  let metrics;
@@ -11223,18 +11463,11 @@ function traceStreamingChannel(channel2, config) {
11223
11463
  } else if (metrics.time_to_first_token === void 0 && chunks.length > 0) {
11224
11464
  metrics.time_to_first_token = getCurrentUnixTimestamp() - startTime;
11225
11465
  }
11226
- runStreamingCompletionHook({
11227
- channelName,
11228
- chunks,
11229
- config,
11230
- endEvent: asyncEndEvent,
11466
+ completion2 = {
11231
11467
  ...metadata !== void 0 ? { metadata } : {},
11232
11468
  metrics,
11233
- output,
11234
- result: asyncEndEvent.result,
11235
- span,
11236
- startTime
11237
- });
11469
+ output
11470
+ };
11238
11471
  span.log({
11239
11472
  output,
11240
11473
  ...metadata !== void 0 ? { metadata } : {},
@@ -11246,11 +11479,49 @@ function traceStreamingChannel(channel2, config) {
11246
11479
  error
11247
11480
  );
11248
11481
  } finally {
11249
- span.end();
11482
+ try {
11483
+ span.end();
11484
+ } catch (error) {
11485
+ debugLogger.error(
11486
+ `Error ending span for ${channelName}:`,
11487
+ error
11488
+ );
11489
+ }
11250
11490
  states.delete(event);
11251
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
+ }
11252
11506
  },
11253
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);
11254
11525
  runStreamingErrorHook({
11255
11526
  channelName,
11256
11527
  config,
@@ -11259,11 +11530,6 @@ function traceStreamingChannel(channel2, config) {
11259
11530
  span,
11260
11531
  startTime
11261
11532
  });
11262
- span.log({
11263
- error: error.message
11264
- });
11265
- span.end();
11266
- states.delete(event);
11267
11533
  }
11268
11534
  });
11269
11535
  return;
@@ -11278,6 +11544,7 @@ function traceStreamingChannel(channel2, config) {
11278
11544
  states.delete(event);
11279
11545
  return;
11280
11546
  }
11547
+ let completion;
11281
11548
  try {
11282
11549
  const output = config.extractOutput(
11283
11550
  asyncEndEvent.result,
@@ -11292,17 +11559,11 @@ function traceStreamingChannel(channel2, config) {
11292
11559
  asyncEndEvent.result,
11293
11560
  asyncEndEvent
11294
11561
  );
11295
- runStreamingCompletionHook({
11296
- channelName,
11297
- config,
11298
- endEvent: asyncEndEvent,
11562
+ completion = {
11299
11563
  ...normalizeMetadata(metadata) !== void 0 ? { metadata: normalizeMetadata(metadata) } : {},
11300
11564
  metrics,
11301
- output,
11302
- result: asyncEndEvent.result,
11303
- span,
11304
- startTime
11305
- });
11565
+ output
11566
+ };
11306
11567
  span.log({
11307
11568
  output,
11308
11569
  ...normalizeMetadata(metadata) !== void 0 ? { metadata: normalizeMetadata(metadata) } : {},
@@ -11311,12 +11572,30 @@ function traceStreamingChannel(channel2, config) {
11311
11572
  } catch (error) {
11312
11573
  debugLogger.error(`Error extracting output for ${channelName}:`, error);
11313
11574
  } finally {
11314
- span.end();
11575
+ try {
11576
+ span.end();
11577
+ } catch (error) {
11578
+ debugLogger.error(`Error ending span for ${channelName}:`, error);
11579
+ }
11315
11580
  states.delete(event);
11316
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
+ }
11317
11595
  },
11318
11596
  error: (event) => {
11319
11597
  const spanData = states.get(event);
11598
+ logErrorAndEnd(states, event, channelName);
11320
11599
  if (spanData) {
11321
11600
  runStreamingErrorHook({
11322
11601
  channelName,
@@ -11327,7 +11606,6 @@ function traceStreamingChannel(channel2, config) {
11327
11606
  startTime: spanData.startTime
11328
11607
  });
11329
11608
  }
11330
- logErrorAndEnd(states, event);
11331
11609
  }
11332
11610
  };
11333
11611
  tracingChannel2.subscribe(handlers);
@@ -11344,7 +11622,8 @@ function traceSyncStreamChannel(channel2, config) {
11344
11622
  tracingChannel2,
11345
11623
  states,
11346
11624
  config,
11347
- channelName
11625
+ channelName,
11626
+ channel2.instrumentationName
11348
11627
  );
11349
11628
  const handlers = {
11350
11629
  start: (event) => {
@@ -11355,7 +11634,8 @@ function traceSyncStreamChannel(channel2, config) {
11355
11634
  states,
11356
11635
  config,
11357
11636
  event,
11358
- channelName
11637
+ channelName,
11638
+ channel2.instrumentationName
11359
11639
  );
11360
11640
  },
11361
11641
  end: (event) => {
@@ -11449,7 +11729,7 @@ function traceSyncStreamChannel(channel2, config) {
11449
11729
  handleResolvedResult(endEvent.result);
11450
11730
  },
11451
11731
  error: (event) => {
11452
- logErrorAndEnd(states, event);
11732
+ logErrorAndEnd(states, event, channelName);
11453
11733
  }
11454
11734
  };
11455
11735
  tracingChannel2.subscribe(handlers);
@@ -11628,7 +11908,8 @@ function processInputAttachments(input) {
11628
11908
  function channel(spec) {
11629
11909
  return spec;
11630
11910
  }
11631
- function defineChannels(pkg, channels) {
11911
+ function defineChannels(pkg, channels, options) {
11912
+ const { instrumentationName } = options;
11632
11913
  return Object.fromEntries(
11633
11914
  Object.entries(channels).map(([key, spec]) => {
11634
11915
  const fullChannelName = `orchestrion:${pkg}:${spec.channelName}`;
@@ -11641,6 +11922,7 @@ function defineChannels(pkg, channels) {
11641
11922
  key,
11642
11923
  {
11643
11924
  ...asyncSpec,
11925
+ instrumentationName,
11644
11926
  tracingChannel: tracingChannel3,
11645
11927
  tracePromise: (fn, context) => tracingChannel3().tracePromise(
11646
11928
  fn,
@@ -11658,6 +11940,7 @@ function defineChannels(pkg, channels) {
11658
11940
  key,
11659
11941
  {
11660
11942
  ...syncSpec,
11943
+ instrumentationName,
11661
11944
  tracingChannel: tracingChannel2,
11662
11945
  traceSync: (fn, context) => tracingChannel2().traceSync(
11663
11946
  fn,
@@ -11671,44 +11954,48 @@ function defineChannels(pkg, channels) {
11671
11954
  }
11672
11955
 
11673
11956
  // src/instrumentation/plugins/openai-channels.ts
11674
- var openAIChannels = defineChannels("openai", {
11675
- chatCompletionsCreate: channel({
11676
- channelName: "chat.completions.create",
11677
- kind: "async"
11678
- }),
11679
- embeddingsCreate: channel({
11680
- channelName: "embeddings.create",
11681
- kind: "async"
11682
- }),
11683
- betaChatCompletionsParse: channel({
11684
- channelName: "beta.chat.completions.parse",
11685
- kind: "async"
11686
- }),
11687
- betaChatCompletionsStream: channel({
11688
- channelName: "beta.chat.completions.stream",
11689
- kind: "sync-stream"
11690
- }),
11691
- moderationsCreate: channel({
11692
- channelName: "moderations.create",
11693
- kind: "async"
11694
- }),
11695
- responsesCreate: channel({
11696
- channelName: "responses.create",
11697
- kind: "async"
11698
- }),
11699
- responsesStream: channel({
11700
- channelName: "responses.stream",
11701
- kind: "sync-stream"
11702
- }),
11703
- responsesParse: channel({
11704
- channelName: "responses.parse",
11705
- kind: "async"
11706
- }),
11707
- responsesCompact: channel({
11708
- channelName: "responses.compact",
11709
- kind: "async"
11710
- })
11711
- });
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
+ );
11712
11999
 
11713
12000
  // src/openai-utils.ts
11714
12001
  var BRAINTRUST_CACHED_STREAM_METRIC = "__braintrust_cached_metric";
@@ -12223,16 +12510,20 @@ function aggregateResponseStreamEvents(chunks, _streamResult, endEvent) {
12223
12510
  }
12224
12511
 
12225
12512
  // src/instrumentation/plugins/openai-codex-channels.ts
12226
- var openAICodexChannels = defineChannels("@openai/codex-sdk", {
12227
- run: channel({
12228
- channelName: "Thread.run",
12229
- kind: "async"
12230
- }),
12231
- runStreamed: channel({
12232
- channelName: "Thread.runStreamed",
12233
- kind: "async"
12234
- })
12235
- });
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
+ );
12236
12527
 
12237
12528
  // src/instrumentation/plugins/openai-codex-plugin.ts
12238
12529
  var PATCHED_STREAMED_TURN = /* @__PURE__ */ Symbol.for(
@@ -12320,10 +12611,15 @@ function startCodexRun(event, operation) {
12320
12611
  provider: "openai",
12321
12612
  ...event.moduleVersion ? { "openai_codex.version": event.moduleVersion } : {}
12322
12613
  };
12323
- const span = startSpan({
12324
- name: "OpenAI Codex",
12325
- spanAttributes: { type: "task" /* TASK */ }
12326
- });
12614
+ const span = startSpan(
12615
+ withSpanInstrumentationName(
12616
+ {
12617
+ name: "OpenAI Codex",
12618
+ spanAttributes: { type: "task" /* TASK */ }
12619
+ },
12620
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
12621
+ )
12622
+ );
12327
12623
  const startTime = getCurrentUnixTimestamp();
12328
12624
  safeLog(span, {
12329
12625
  input: sanitizedInput,
@@ -12472,7 +12768,12 @@ async function createCompletedItemSpan(state, item) {
12472
12768
  if (!spanArgs) {
12473
12769
  return;
12474
12770
  }
12475
- const span = startSpan(spanArgs.start);
12771
+ const span = startSpan(
12772
+ withSpanInstrumentationName(
12773
+ spanArgs.start,
12774
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
12775
+ )
12776
+ );
12476
12777
  safeLog(span, spanArgs.end);
12477
12778
  span.end();
12478
12779
  }
@@ -12514,15 +12815,20 @@ async function ensureActiveLlmSpan(state) {
12514
12815
  ...state.metadata["openai_codex.thread_id"] ? { "openai_codex.thread_id": state.metadata["openai_codex.thread_id"] } : {},
12515
12816
  "openai_codex.llm_sequence": sequence
12516
12817
  };
12517
- const span = startSpan({
12518
- event: {
12519
- ...sequence === 1 ? { input: state.input } : {},
12520
- metadata
12521
- },
12522
- name: "OpenAI Codex LLM",
12523
- parent: await state.span.export(),
12524
- spanAttributes: { type: "llm" /* LLM */ }
12525
- });
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
+ );
12526
12832
  state.activeLlmSpan = {
12527
12833
  anonymousMessages: [],
12528
12834
  anonymousReasoning: [],
@@ -12568,7 +12874,15 @@ async function startCodexItemSpan(state, item) {
12568
12874
  if (!spanArgs) {
12569
12875
  return;
12570
12876
  }
12571
- 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
+ );
12572
12886
  }
12573
12887
  function updateCodexItem(state, item) {
12574
12888
  if (item.type === "agent_message" && typeof item.text === "string") {
@@ -12878,20 +13192,24 @@ function extractAnthropicCacheTokens(cacheReadTokens = 0, cacheCreationTokens =
12878
13192
  }
12879
13193
 
12880
13194
  // src/instrumentation/plugins/anthropic-channels.ts
12881
- var anthropicChannels = defineChannels("@anthropic-ai/sdk", {
12882
- messagesCreate: channel({
12883
- channelName: "messages.create",
12884
- kind: "async"
12885
- }),
12886
- betaMessagesCreate: channel({
12887
- channelName: "beta.messages.create",
12888
- kind: "async"
12889
- }),
12890
- betaMessagesToolRunner: channel({
12891
- channelName: "beta.messages.toolRunner",
12892
- kind: "sync-stream"
12893
- })
12894
- });
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
+ );
12895
13213
 
12896
13214
  // src/instrumentation/plugins/anthropic-plugin.ts
12897
13215
  var ANTHROPIC_TOOL_RUNNER_TOOL_WRAPPED = /* @__PURE__ */ Symbol.for(
@@ -12964,12 +13282,17 @@ var AnthropicPlugin = class extends BasePlugin {
12964
13282
  return;
12965
13283
  }
12966
13284
  const params = event.arguments[0] ?? {};
12967
- const span = startSpan({
12968
- name: "anthropic.beta.messages.toolRunner",
12969
- spanAttributes: {
12970
- type: "task" /* TASK */
12971
- }
12972
- });
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
+ );
12973
13296
  span.log({
12974
13297
  input: processAttachmentsInInput(
12975
13298
  coalesceInput(params.messages ?? [], params.system)
@@ -13110,19 +13433,22 @@ function wrapAnthropicToolRunnerTool(tool, index, state) {
13110
13433
  return finalizeError(error);
13111
13434
  }
13112
13435
  },
13113
- {
13114
- event: {
13115
- input: getAnthropicToolRunnerInput(args),
13116
- metadata: {
13117
- "gen_ai.tool.name": toolName,
13118
- 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 */
13119
13448
  }
13120
13449
  },
13121
- name: `tool: ${toolName}`,
13122
- spanAttributes: {
13123
- type: "tool" /* TOOL */
13124
- }
13125
- }
13450
+ INSTRUMENTATION_NAMES.ANTHROPIC
13451
+ )
13126
13452
  );
13127
13453
  },
13128
13454
  writable: runDescriptor?.writable ?? true
@@ -13717,6 +14043,267 @@ function currentWorkflowAgentWrapperSpan() {
13717
14043
  return void 0;
13718
14044
  }
13719
14045
 
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
14074
+ };
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
+
13720
14307
  // src/wrappers/ai-sdk/telemetry.ts
13721
14308
  function braintrustAISDKTelemetry() {
13722
14309
  const operations = /* @__PURE__ */ new Map();
@@ -13735,14 +14322,17 @@ function braintrustAISDKTelemetry() {
13735
14322
  console.error(`Error in Braintrust AI SDK telemetry ${name}:`, error);
13736
14323
  }
13737
14324
  };
13738
- const startChildSpan = (operationKey, name, type, event) => {
14325
+ const startChildSpan = (operationKey, name, type, event, parentOverride) => {
13739
14326
  const parent = operations.get(operationKey)?.span;
13740
- const spanArgs = {
13741
- name,
13742
- spanAttributes: { type },
13743
- ...event ? { event } : {}
13744
- };
13745
- const span = parent ? parent.startSpan(spanArgs) : startSpan(spanArgs);
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);
13746
14336
  const state = operations.get(operationKey);
13747
14337
  if (state && type === "llm" /* LLM */) {
13748
14338
  state.hadModelChild = true;
@@ -14022,14 +14612,30 @@ function braintrustAISDKTelemetry() {
14022
14612
  const workflowAgent = operationName === "WorkflowAgent.stream";
14023
14613
  const wrapperSpan = workflowAgent ? currentWorkflowAgentWrapperSpan() : void 0;
14024
14614
  const ownsSpan = !wrapperSpan;
14025
- const span = ownsSpan ? startSpan({
14026
- name: operationName,
14027
- spanAttributes: { type: "function" /* FUNCTION */ }
14028
- }) : 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;
14029
14634
  const operationKey = createOperationKey(event, operationName);
14030
14635
  registerOperation({
14031
14636
  callId: event.callId,
14032
14637
  hadModelChild: false,
14638
+ harnessTurnParent,
14033
14639
  loggedInput: false,
14034
14640
  operationName,
14035
14641
  operationKey,
@@ -14270,7 +14876,8 @@ function braintrustAISDKTelemetry() {
14270
14876
  toolCallId,
14271
14877
  ...typeof event.toolCall.toolName === "string" ? { toolName: event.toolCall.toolName } : {}
14272
14878
  }
14273
- }
14879
+ },
14880
+ state?.harnessTurnParent
14274
14881
  );
14275
14882
  toolSpans.set(toolCallId, { operationKey, span });
14276
14883
  });
@@ -14506,74 +15113,102 @@ function finishOutput(result, operationName) {
14506
15113
  }
14507
15114
 
14508
15115
  // src/instrumentation/plugins/ai-sdk-channels.ts
14509
- var aiSDKChannels = defineChannels("ai", {
14510
- generateText: channel({
14511
- channelName: "generateText",
14512
- kind: "async"
14513
- }),
14514
- streamText: channel({
14515
- channelName: "streamText",
14516
- kind: "async"
14517
- }),
14518
- streamTextSync: channel({
14519
- channelName: "streamText.sync",
14520
- kind: "sync-stream"
14521
- }),
14522
- generateObject: channel({
14523
- channelName: "generateObject",
14524
- kind: "async"
14525
- }),
14526
- streamObject: channel({
14527
- channelName: "streamObject",
14528
- kind: "async"
14529
- }),
14530
- streamObjectSync: channel({
14531
- channelName: "streamObject.sync",
14532
- kind: "sync-stream"
14533
- }),
14534
- embed: channel(
14535
- {
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({
14536
15144
  channelName: "embed",
14537
15145
  kind: "async"
14538
- }
14539
- ),
14540
- embedMany: channel({
14541
- channelName: "embedMany",
14542
- kind: "async"
14543
- }),
14544
- rerank: channel({
14545
- channelName: "rerank",
14546
- kind: "async"
14547
- }),
14548
- agentGenerate: channel({
14549
- channelName: "Agent.generate",
14550
- kind: "async"
14551
- }),
14552
- agentStream: channel({
14553
- channelName: "Agent.stream",
14554
- kind: "async"
14555
- }),
14556
- agentStreamSync: channel({
14557
- channelName: "Agent.stream.sync",
14558
- kind: "sync-stream"
14559
- }),
14560
- toolLoopAgentGenerate: channel({
14561
- channelName: "ToolLoopAgent.generate",
14562
- kind: "async"
14563
- }),
14564
- toolLoopAgentStream: channel({
14565
- channelName: "ToolLoopAgent.stream",
14566
- kind: "async"
14567
- }),
14568
- workflowAgentStream: channel({
14569
- channelName: "WorkflowAgent.stream",
14570
- kind: "async"
14571
- }),
14572
- v7CreateTelemetryDispatcher: channel({
14573
- channelName: "createTelemetryDispatcher",
14574
- kind: "sync-stream"
14575
- })
14576
- });
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
+ );
14577
15212
 
14578
15213
  // src/instrumentation/plugins/ai-sdk-plugin.ts
14579
15214
  var DEFAULT_DENY_OUTPUT_PATHS = [
@@ -14650,6 +15285,17 @@ var AISDKPlugin = class extends BasePlugin {
14650
15285
  subscribeToAISDK() {
14651
15286
  const denyOutputPaths = this.config.denyOutputPaths || DEFAULT_DENY_OUTPUT_PATHS;
14652
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
+ );
14653
15299
  this.unsubscribers.push(
14654
15300
  traceStreamingChannel(aiSDKChannels.generateText, {
14655
15301
  name: "generateText",
@@ -14842,6 +15488,90 @@ var AISDKPlugin = class extends BasePlugin {
14842
15488
  })
14843
15489
  })
14844
15490
  );
15491
+ this.unsubscribers.push(
15492
+ traceStreamingChannel(harnessAgentChannels.generate, {
15493
+ name: "HarnessAgent.generate",
15494
+ startSpan: _internalStartSpanWithInitialMerge,
15495
+ type: "task" /* TASK */,
15496
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
15497
+ extractOutput: (result, endEvent) => processAISDKOutput(
15498
+ result,
15499
+ resolveDenyOutputPaths(endEvent, denyOutputPaths)
15500
+ ),
15501
+ extractMetrics: (result) => extractTokenMetrics(result),
15502
+ aggregateChunks: aggregateAISDKChunks
15503
+ })
15504
+ );
15505
+ this.unsubscribers.push(
15506
+ traceStreamingChannel(harnessAgentChannels.stream, {
15507
+ name: "HarnessAgent.stream",
15508
+ startSpan: _internalStartSpanWithInitialMerge,
15509
+ type: "task" /* TASK */,
15510
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
15511
+ extractOutput: (result, endEvent) => processAISDKOutput(
15512
+ result,
15513
+ resolveDenyOutputPaths(endEvent, denyOutputPaths)
15514
+ ),
15515
+ extractMetrics: (result, startTime) => ({
15516
+ ...extractTokenMetrics(result),
15517
+ ...startTime === void 0 ? {} : {
15518
+ time_to_first_token: getCurrentUnixTimestamp() - startTime
15519
+ }
15520
+ }),
15521
+ aggregateChunks: aggregateAISDKChunks,
15522
+ patchResult: ({ endEvent, result, span, startTime }) => patchAISDKStreamingResult({
15523
+ defaultDenyOutputPaths: denyOutputPaths,
15524
+ endEvent,
15525
+ result,
15526
+ resolvePromiseUsage: true,
15527
+ span,
15528
+ startTime
15529
+ })
15530
+ })
15531
+ );
15532
+ this.unsubscribers.push(
15533
+ traceStreamingChannel(harnessAgentChannels.continueGenerate, {
15534
+ name: "HarnessAgent.continueGenerate",
15535
+ shouldTrace: (args) => !harnessContinuationParent(harnessSessionFromArguments(args)),
15536
+ startSpan: _internalStartSpanWithInitialMerge,
15537
+ type: "task" /* TASK */,
15538
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
15539
+ extractOutput: (result, endEvent) => processAISDKOutput(
15540
+ result,
15541
+ resolveDenyOutputPaths(endEvent, denyOutputPaths)
15542
+ ),
15543
+ extractMetrics: (result) => extractTokenMetrics(result),
15544
+ aggregateChunks: aggregateAISDKChunks
15545
+ })
15546
+ );
15547
+ this.unsubscribers.push(
15548
+ traceStreamingChannel(harnessAgentChannels.continueStream, {
15549
+ name: "HarnessAgent.continueStream",
15550
+ shouldTrace: (args) => !harnessContinuationParent(harnessSessionFromArguments(args)),
15551
+ startSpan: _internalStartSpanWithInitialMerge,
15552
+ type: "task" /* TASK */,
15553
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
15554
+ extractOutput: (result, endEvent) => processAISDKOutput(
15555
+ result,
15556
+ resolveDenyOutputPaths(endEvent, denyOutputPaths)
15557
+ ),
15558
+ extractMetrics: (result, startTime) => ({
15559
+ ...extractTokenMetrics(result),
15560
+ ...startTime === void 0 ? {} : {
15561
+ time_to_first_token: getCurrentUnixTimestamp() - startTime
15562
+ }
15563
+ }),
15564
+ aggregateChunks: aggregateAISDKChunks,
15565
+ patchResult: ({ endEvent, result, span, startTime }) => patchAISDKStreamingResult({
15566
+ defaultDenyOutputPaths: denyOutputPaths,
15567
+ endEvent,
15568
+ result,
15569
+ resolvePromiseUsage: true,
15570
+ span,
15571
+ startTime
15572
+ })
15573
+ })
15574
+ );
14845
15575
  this.unsubscribers.push(
14846
15576
  traceStreamingChannel(aiSDKChannels.toolLoopAgentGenerate, {
14847
15577
  name: "ToolLoopAgent.generate",
@@ -14912,6 +15642,8 @@ var AISDKPlugin = class extends BasePlugin {
14912
15642
  defaultDenyOutputPaths: denyOutputPaths,
14913
15643
  endEvent,
14914
15644
  onComplete: () => unregisterWorkflowAgentWrapperSpan(span),
15645
+ onCancel: () => unregisterWorkflowAgentWrapperSpan(span),
15646
+ onError: () => unregisterWorkflowAgentWrapperSpan(span),
14915
15647
  result,
14916
15648
  span,
14917
15649
  startTime
@@ -14920,6 +15652,153 @@ var AISDKPlugin = class extends BasePlugin {
14920
15652
  );
14921
15653
  }
14922
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
+ }
14923
15802
  function subscribeToAISDKV7TelemetryDispatcher() {
14924
15803
  const channel2 = aiSDKChannels.v7CreateTelemetryDispatcher.tracingChannel();
14925
15804
  const telemetry = braintrustAISDKTelemetry();
@@ -15372,6 +16251,55 @@ function prepareAISDKCallInput(params, event, span, defaultDenyOutputPaths, chil
15372
16251
  metadata
15373
16252
  };
15374
16253
  }
16254
+ function prepareAISDKHarnessAgentInput(params, self, span) {
16255
+ if (span) {
16256
+ registerHarnessTurnSpan({
16257
+ session: params.session,
16258
+ span
16259
+ });
16260
+ }
16261
+ if (isObject(self)) {
16262
+ try {
16263
+ if (isObject(self.settings)) {
16264
+ const settings = self.settings;
16265
+ if (settings.telemetry === void 0) {
16266
+ Reflect.set(self, "settings", { ...settings, telemetry: {} });
16267
+ }
16268
+ }
16269
+ } catch {
16270
+ }
16271
+ }
16272
+ const selectedInput = {};
16273
+ if (params.prompt !== void 0) {
16274
+ selectedInput.prompt = params.prompt;
16275
+ }
16276
+ if (params.messages !== void 0) {
16277
+ selectedInput.messages = params.messages;
16278
+ }
16279
+ if (params.toolApprovalContinuations !== void 0) {
16280
+ selectedInput.toolApprovalContinuations = params.toolApprovalContinuations;
16281
+ }
16282
+ const metadata = extractMetadataFromCallParams({}, self);
16283
+ if (isObject(params.session) && typeof params.session.sessionId === "string") {
16284
+ metadata.sessionId = params.session.sessionId;
16285
+ }
16286
+ if (isObject(self)) {
16287
+ if (typeof self.harnessId === "string") {
16288
+ metadata.harnessId = self.harnessId;
16289
+ }
16290
+ if (typeof self.permissionMode === "string") {
16291
+ metadata.permissionMode = self.permissionMode;
16292
+ }
16293
+ }
16294
+ return {
16295
+ input: processAISDKCallInput(selectedInput).input,
16296
+ metadata
16297
+ };
16298
+ }
16299
+ function harnessSessionFromArguments(args) {
16300
+ const params = args[0];
16301
+ return isObject(params) ? params.session : void 0;
16302
+ }
15375
16303
  function prepareAISDKWorkflowAgentStreamInput(params, event, span, defaultDenyOutputPaths) {
15376
16304
  registerWorkflowAgentWrapperSpan(span);
15377
16305
  const { input } = processAISDKWorkflowAgentCallInput(params);
@@ -15819,19 +16747,22 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
15819
16747
  activeEntry.openSpans.delete(span);
15820
16748
  }
15821
16749
  },
15822
- {
15823
- name: "doGenerate",
15824
- spanAttributes: {
15825
- 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
+ )
15826
16763
  },
15827
- event: buildAISDKModelStartEvent(
15828
- callOptions,
15829
- activeEntry.baseMetadata,
15830
- {
15831
- workflowAgent: activeEntry.childTracingOptions.workflowAgent
15832
- }
15833
- )
15834
- }
16764
+ INSTRUMENTATION_NAMES.AI_SDK
16765
+ )
15835
16766
  );
15836
16767
  };
15837
16768
  if (originalDoStream) {
@@ -15841,19 +16772,24 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
15841
16772
  return Reflect.apply(originalDoStream, resolvedModel, [callOptions]);
15842
16773
  }
15843
16774
  closeOpenAISDKModelPatchSpans(activeEntry);
15844
- const span = activeEntry.parentSpan.startSpan({
15845
- name: "doStream",
15846
- spanAttributes: {
15847
- type: "llm" /* LLM */
15848
- },
15849
- event: buildAISDKModelStartEvent(
15850
- callOptions,
15851
- activeEntry.baseMetadata,
16775
+ const span = activeEntry.parentSpan.startSpan(
16776
+ withSpanInstrumentationName(
15852
16777
  {
15853
- workflowAgent: activeEntry.childTracingOptions.workflowAgent
15854
- }
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
15855
16791
  )
15856
- });
16792
+ );
15857
16793
  activeEntry.openSpans.add(span);
15858
16794
  const streamStartTime = getCurrentUnixTimestamp();
15859
16795
  const result = await withCurrent(
@@ -16025,12 +16961,17 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
16025
16961
  }
16026
16962
  if (isAsyncGenerator(result)) {
16027
16963
  return (async function* () {
16028
- const span = activeEntry.parentSpan.startSpan({
16029
- name: activeEntry.name,
16030
- spanAttributes: {
16031
- type: "tool" /* TOOL */
16032
- }
16033
- });
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
+ );
16034
16975
  span.log({ input: serializeToolExecutionInput(args) });
16035
16976
  try {
16036
16977
  let lastValue;
@@ -16054,12 +16995,15 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
16054
16995
  span.log({ output: awaitedResult });
16055
16996
  return awaitedResult;
16056
16997
  },
16057
- {
16058
- name: activeEntry.name,
16059
- spanAttributes: {
16060
- type: "tool" /* TOOL */
16061
- }
16062
- }
16998
+ withSpanInstrumentationName(
16999
+ {
17000
+ name: activeEntry.name,
17001
+ spanAttributes: {
17002
+ type: "tool" /* TOOL */
17003
+ }
17004
+ },
17005
+ INSTRUMENTATION_NAMES.AI_SDK
17006
+ )
16063
17007
  );
16064
17008
  };
16065
17009
  cleanup.push(() => {
@@ -16218,7 +17162,10 @@ function patchAISDKStreamingResult(args) {
16218
17162
  defaultDenyOutputPaths,
16219
17163
  endEvent,
16220
17164
  onComplete,
17165
+ onCancel,
17166
+ onError,
16221
17167
  result,
17168
+ resolvePromiseUsage,
16222
17169
  span,
16223
17170
  startTime
16224
17171
  } = args;
@@ -16228,14 +17175,43 @@ function patchAISDKStreamingResult(args) {
16228
17175
  const resultRecord = result;
16229
17176
  attachKnownResultPromiseHandlers(resultRecord);
16230
17177
  let finalized = false;
16231
- const finalize = () => {
17178
+ const finalize = (outcome) => {
16232
17179
  if (finalized) {
16233
17180
  return;
16234
17181
  }
16235
17182
  finalized = true;
16236
- finalizeAISDKChildTracing(endEvent);
16237
- span.end();
16238
- 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
+ }
16239
17215
  };
16240
17216
  let outputLogged = false;
16241
17217
  const logStreamingOutput = async (firstChunkTime) => {
@@ -16245,6 +17221,22 @@ function patchAISDKStreamingResult(args) {
16245
17221
  outputLogged = true;
16246
17222
  try {
16247
17223
  const metrics = extractTopLevelAISDKMetrics(result, endEvent);
17224
+ if (resolvePromiseUsage) {
17225
+ try {
17226
+ const resultRecord2 = result;
17227
+ const pendingUsage = resultRecord2.totalUsage ?? resultRecord2.usage;
17228
+ if (isPromiseLike(pendingUsage)) {
17229
+ const usage = await Promise.resolve(pendingUsage);
17230
+ if (isObject(usage)) {
17231
+ Object.assign(
17232
+ metrics,
17233
+ extractTokenMetrics({ usage })
17234
+ );
17235
+ }
17236
+ }
17237
+ } catch {
17238
+ }
17239
+ }
16248
17240
  if (metrics.time_to_first_token === void 0 && firstChunkTime !== void 0) {
16249
17241
  metrics.time_to_first_token = firstChunkTime - startTime;
16250
17242
  }
@@ -16253,15 +17245,29 @@ function patchAISDKStreamingResult(args) {
16253
17245
  resolveDenyOutputPaths(endEvent, defaultDenyOutputPaths)
16254
17246
  );
16255
17247
  const metadata = buildResolvedMetadataPayload(result).metadata;
16256
- span.log({
16257
- output,
16258
- ...metadata ? { metadata } : {},
16259
- metrics
16260
- });
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 });
16261
17258
  } catch (error) {
16262
- span.log({ error: toLoggedError(error) });
16263
- } finally {
16264
- 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
+ });
16265
17271
  }
16266
17272
  };
16267
17273
  const createAsyncIterableHooks = () => {
@@ -16278,11 +17284,16 @@ function patchAISDKStreamingResult(args) {
16278
17284
  onError: (error) => {
16279
17285
  if (!outputLogged) {
16280
17286
  outputLogged = true;
16281
- span.log({
16282
- error: error.message
16283
- });
17287
+ try {
17288
+ span.log({ error });
17289
+ } catch (loggingError) {
17290
+ debugLogger.error(
17291
+ "Error logging AI SDK stream failure:",
17292
+ loggingError
17293
+ );
17294
+ }
16284
17295
  }
16285
- finalize();
17296
+ finalize({ error });
16286
17297
  },
16287
17298
  onCancel: finalize
16288
17299
  };
@@ -16368,8 +17379,18 @@ function patchAISDKStreamingResult(args) {
16368
17379
  }
16369
17380
  controller.enqueue(value);
16370
17381
  } catch (error) {
16371
- span.log({ error: toLoggedError(error) });
16372
- 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
+ });
16373
17394
  controller.error(error);
16374
17395
  }
16375
17396
  },
@@ -17158,7 +18179,8 @@ var claudeAgentSDKChannels = defineChannels(
17158
18179
  channelName: "query",
17159
18180
  kind: "sync-stream"
17160
18181
  })
17161
- }
18182
+ },
18183
+ { instrumentationName: INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK }
17162
18184
  );
17163
18185
 
17164
18186
  // src/instrumentation/plugins/claude-agent-sdk-instrumentation-constants.ts
@@ -17306,22 +18328,27 @@ function wrapLocalClaudeToolHandler(handler, getMetadata) {
17306
18328
  const spanName = metadata.serverName ? `tool: ${metadata.serverName}/${metadata.toolName}` : `tool: ${metadata.toolName}`;
17307
18329
  const runWithResolvedParent = async () => {
17308
18330
  const parent = toolUseId && localToolParentResolver ? await localToolParentResolver(toolUseId).catch(() => void 0) : void 0;
17309
- const span = startSpan({
17310
- event: {
17311
- input: handlerArgs[0],
17312
- metadata: {
17313
- "claude_agent_sdk.raw_tool_name": rawToolName,
17314
- "gen_ai.tool.name": metadata.toolName,
17315
- ...toolUseId && { "gen_ai.tool.call.id": toolUseId },
17316
- ...metadata.serverName && {
17317
- "mcp.server": metadata.serverName
17318
- }
17319
- }
17320
- },
17321
- name: spanName,
17322
- ...parent && { parent },
17323
- spanAttributes: { type: "tool" /* TOOL */ }
17324
- });
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
+ );
17325
18352
  const runHandler = () => Reflect.apply(handler, this, handlerArgs);
17326
18353
  const finalizeSuccess = (result) => {
17327
18354
  span.log({ output: result });
@@ -17646,14 +18673,19 @@ async function createLLMSpanForMessages(messages, promptMessages, conversationHi
17646
18673
  ).filter(
17647
18674
  (c) => c !== void 0
17648
18675
  );
17649
- const span = existingSpan ?? startSpan({
17650
- name: "anthropic.messages.create",
17651
- parent: parentSpan,
17652
- spanAttributes: {
17653
- type: "llm" /* LLM */
17654
- },
17655
- startTime
17656
- });
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
+ );
17657
18689
  span.log({
17658
18690
  input,
17659
18691
  metadata: model ? { model } : void 0,
@@ -17756,25 +18788,30 @@ function createToolTracingHooks(resolveParentSpan, activeToolSpans, mcpServers,
17756
18788
  return {};
17757
18789
  }
17758
18790
  const parsed = parseToolName(input.tool_name);
17759
- const toolSpan = startSpan({
17760
- event: {
17761
- input: input.tool_input,
17762
- metadata: {
17763
- "claude_agent_sdk.cwd": input.cwd,
17764
- "claude_agent_sdk.raw_tool_name": parsed.rawToolName,
17765
- "claude_agent_sdk.session_id": input.session_id,
17766
- "gen_ai.tool.call.id": toolUseID,
17767
- "gen_ai.tool.name": parsed.toolName,
17768
- ...parsed.mcpServer && { "mcp.server": parsed.mcpServer },
17769
- ...getMcpServerMetadata(parsed.mcpServer, mcpServers)
17770
- }
17771
- },
17772
- name: parsed.displayName,
17773
- parent: await resolveParentSpan(toolUseID, {
17774
- agentId: input.agent_id
17775
- }),
17776
- spanAttributes: { type: "tool" /* TOOL */ }
17777
- });
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
+ );
17778
18815
  activeToolSpans.set(toolUseID, toolSpan);
17779
18816
  return {};
17780
18817
  };
@@ -18140,14 +19177,19 @@ async function ensureSubAgentSpan(subAgentDetailsByToolUseId, rootSpan, activeTo
18140
19177
  const spanName = formatSubAgentSpanName(details);
18141
19178
  const parentToolSpan = activeToolSpans.get(parentToolUseId);
18142
19179
  const parentSpan = parentToolSpan ? await parentToolSpan.export() : await rootSpan.export();
18143
- const subAgentSpan = startSpan({
18144
- event: {
18145
- metadata: subAgentDetailsToMetadata(details)
18146
- },
18147
- name: spanName,
18148
- parent: parentSpan,
18149
- spanAttributes: { type: "task" /* TASK */ }
18150
- });
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
+ );
18151
19193
  subAgentSpans.set(parentToolUseId, subAgentSpan);
18152
19194
  return subAgentSpan;
18153
19195
  }
@@ -18168,14 +19210,19 @@ async function ensureActiveLlmSpanForParentToolUse(rootSpan, activeLlmSpansByPar
18168
19210
  );
18169
19211
  llmParentSpan = await subAgentSpan.export();
18170
19212
  }
18171
- const llmSpan = startSpan({
18172
- name: "anthropic.messages.create",
18173
- parent: llmParentSpan,
18174
- spanAttributes: {
18175
- type: "llm" /* LLM */
18176
- },
18177
- startTime
18178
- });
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
+ );
18179
19226
  activeLlmSpansByParentToolUse.set(parentKey, llmSpan);
18180
19227
  return llmSpan;
18181
19228
  }
@@ -18444,12 +19491,17 @@ var ClaudeAgentSDKPlugin = class extends BasePlugin {
18444
19491
  }
18445
19492
  })();
18446
19493
  }
18447
- const span = startSpan({
18448
- name: "Claude Agent",
18449
- spanAttributes: {
18450
- type: "task" /* TASK */
18451
- }
18452
- });
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
+ );
18453
19505
  const startTime = getCurrentUnixTimestamp();
18454
19506
  try {
18455
19507
  span.log({
@@ -18614,24 +19666,28 @@ var ClaudeAgentSDKPlugin = class extends BasePlugin {
18614
19666
  };
18615
19667
 
18616
19668
  // src/instrumentation/plugins/cursor-sdk-channels.ts
18617
- var cursorSDKChannels = defineChannels("@cursor/sdk", {
18618
- create: channel({
18619
- channelName: "Agent.create",
18620
- kind: "async"
18621
- }),
18622
- resume: channel({
18623
- channelName: "Agent.resume",
18624
- kind: "async"
18625
- }),
18626
- prompt: channel({
18627
- channelName: "Agent.prompt",
18628
- kind: "async"
18629
- }),
18630
- send: channel({
18631
- channelName: "agent.send",
18632
- kind: "async"
18633
- })
18634
- });
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
+ );
18635
19691
 
18636
19692
  // src/instrumentation/plugins/cursor-sdk-plugin.ts
18637
19693
  var PATCHED_AGENT = /* @__PURE__ */ Symbol.for("braintrust.cursor-sdk.auto-patched-agent");
@@ -18683,10 +19739,15 @@ var CursorSDKPlugin = class extends BasePlugin {
18683
19739
  provider: "cursor",
18684
19740
  ...event.moduleVersion ? { "cursor_sdk.version": event.moduleVersion } : {}
18685
19741
  };
18686
- const span = startSpan({
18687
- name: "Cursor Agent",
18688
- spanAttributes: { type: "task" /* TASK */ }
18689
- });
19742
+ const span = startSpan(
19743
+ withSpanInstrumentationName(
19744
+ {
19745
+ name: "Cursor Agent",
19746
+ spanAttributes: { type: "task" /* TASK */ }
19747
+ },
19748
+ INSTRUMENTATION_NAMES.CURSOR_SDK
19749
+ )
19750
+ );
18690
19751
  const startTime = getCurrentUnixTimestamp();
18691
19752
  safeLog2(span, {
18692
19753
  input: sanitizeUserMessage(message),
@@ -18748,10 +19809,15 @@ var CursorSDKPlugin = class extends BasePlugin {
18748
19809
  provider: "cursor",
18749
19810
  ...event.moduleVersion ? { "cursor_sdk.version": event.moduleVersion } : {}
18750
19811
  };
18751
- const span = startSpan({
18752
- name: "Cursor Agent",
18753
- spanAttributes: { type: "task" /* TASK */ }
18754
- });
19812
+ const span = startSpan(
19813
+ withSpanInstrumentationName(
19814
+ {
19815
+ name: "Cursor Agent",
19816
+ spanAttributes: { type: "task" /* TASK */ }
19817
+ },
19818
+ INSTRUMENTATION_NAMES.CURSOR_SDK
19819
+ )
19820
+ );
18755
19821
  const startTime = getCurrentUnixTimestamp();
18756
19822
  safeLog2(span, {
18757
19823
  input: sanitizeUserMessage(message),
@@ -19198,29 +20264,39 @@ async function startToolSpan(state, args) {
19198
20264
  if (args.truncated?.result !== void 0) {
19199
20265
  metadata["cursor_sdk.tool.result_truncated"] = args.truncated.result;
19200
20266
  }
19201
- const span = startSpan({
19202
- event: {
19203
- input: args.args,
19204
- metadata
19205
- },
19206
- name: `tool: ${name}`,
19207
- parent: await state.span.export(),
19208
- spanAttributes: { type: "tool" /* TOOL */ }
19209
- });
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
+ );
19210
20281
  let subAgentSpan;
19211
20282
  if (isSubAgentToolName(name)) {
19212
- subAgentSpan = startSpan({
19213
- event: {
19214
- input: args.args,
19215
- metadata: {
19216
- "cursor_sdk.subagent.tool_call_id": args.callId,
19217
- "gen_ai.tool.name": name
19218
- }
19219
- },
19220
- name: formatSubAgentSpanName2(args.toolCall, args.args),
19221
- parent: await span.export(),
19222
- spanAttributes: { type: "task" /* TASK */ }
19223
- });
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
+ );
19224
20300
  }
19225
20301
  return { span, subAgentSpan };
19226
20302
  }
@@ -19479,24 +20555,28 @@ function cleanMetrics2(metrics) {
19479
20555
  }
19480
20556
 
19481
20557
  // src/instrumentation/plugins/openai-agents-channels.ts
19482
- var openAIAgentsCoreChannels = defineChannels("@openai/agents-core", {
19483
- onTraceStart: channel({
19484
- channelName: "tracing.processor.onTraceStart",
19485
- kind: "async"
19486
- }),
19487
- onTraceEnd: channel({
19488
- channelName: "tracing.processor.onTraceEnd",
19489
- kind: "async"
19490
- }),
19491
- onSpanStart: channel({
19492
- channelName: "tracing.processor.onSpanStart",
19493
- kind: "async"
19494
- }),
19495
- onSpanEnd: channel({
19496
- channelName: "tracing.processor.onSpanEnd",
19497
- kind: "async"
19498
- })
19499
- });
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
+ );
19500
20580
 
19501
20581
  // src/instrumentation/plugins/openai-agents-trace-processor.ts
19502
20582
  function isSpanData(spanData, type) {
@@ -19612,16 +20692,19 @@ var OpenAIAgentsTraceProcessor = class _OpenAIAgentsTraceProcessor {
19612
20692
  this.evictOldestTrace();
19613
20693
  }
19614
20694
  const current = currentSpan();
19615
- const span = current && current !== NOOP_SPAN ? current.startSpan({
19616
- name: trace.name,
19617
- type: "task" /* TASK */
19618
- }) : this.logger ? this.logger.startSpan({
19619
- name: trace.name,
19620
- type: "task" /* TASK */
19621
- }) : startSpan({
19622
- name: trace.name,
19623
- type: "task" /* TASK */
19624
- });
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
+ );
19625
20708
  span.log({
19626
20709
  input: "Agent workflow started",
19627
20710
  metadata: {
@@ -19672,10 +20755,15 @@ var OpenAIAgentsTraceProcessor = class _OpenAIAgentsTraceProcessor {
19672
20755
  if (!parentSpan) {
19673
20756
  return Promise.resolve();
19674
20757
  }
19675
- const childSpan = parentSpan.startSpan({
19676
- name: spanNameFromAgents(span),
19677
- type: spanTypeFromAgents(span)
19678
- });
20758
+ const childSpan = parentSpan.startSpan(
20759
+ withSpanInstrumentationName(
20760
+ {
20761
+ name: spanNameFromAgents(span),
20762
+ type: spanTypeFromAgents(span)
20763
+ },
20764
+ INSTRUMENTATION_NAMES.OPENAI_AGENTS
20765
+ )
20766
+ );
19679
20767
  traceData.childSpans.set(span.spanId, childSpan);
19680
20768
  return Promise.resolve();
19681
20769
  }
@@ -19940,24 +21028,28 @@ var OpenAIAgentsPlugin = class extends BasePlugin {
19940
21028
  };
19941
21029
 
19942
21030
  // src/instrumentation/plugins/google-genai-channels.ts
19943
- var googleGenAIChannels = defineChannels("@google/genai", {
19944
- generateContent: channel({
19945
- channelName: "models.generateContent",
19946
- kind: "async"
19947
- }),
19948
- generateContentStream: channel({
19949
- channelName: "models.generateContentStream",
19950
- kind: "async"
19951
- }),
19952
- embedContent: channel({
19953
- channelName: "models.embedContent",
19954
- kind: "async"
19955
- }),
19956
- interactionsCreate: channel({
19957
- channelName: "interactions.create",
19958
- kind: "async"
19959
- })
19960
- });
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
+ );
19961
21053
 
19962
21054
  // src/instrumentation/plugins/google-genai-plugin.ts
19963
21055
  var GOOGLE_GENAI_INTERNAL_CONTEXT = {
@@ -19995,13 +21087,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
19995
21087
  const params = event.arguments[0];
19996
21088
  const input = serializeGenerateContentInput(params);
19997
21089
  const metadata = extractGenerateContentMetadata(params);
19998
- const span = startSpan({
19999
- name: "generate_content",
20000
- spanAttributes: {
20001
- type: "llm" /* LLM */
20002
- },
20003
- event: createWrapperParityEvent({ input, metadata })
20004
- });
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
+ );
20005
21102
  return {
20006
21103
  span,
20007
21104
  startTime: getCurrentUnixTimestamp()
@@ -20014,13 +21111,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
20014
21111
  const params = event.arguments[0];
20015
21112
  const input = serializeGenerateContentInput(params);
20016
21113
  const metadata = extractGenerateContentMetadata(params);
20017
- const span = startSpan({
20018
- name: "generate_content",
20019
- spanAttributes: {
20020
- type: "llm" /* LLM */
20021
- },
20022
- event: createWrapperParityEvent({ input, metadata })
20023
- });
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
+ );
20024
21126
  return {
20025
21127
  span,
20026
21128
  startTime: getCurrentUnixTimestamp()
@@ -20096,13 +21198,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
20096
21198
  const params = event.arguments[0];
20097
21199
  const input = serializeEmbedContentInput(params);
20098
21200
  const metadata = extractEmbedContentMetadata(params);
20099
- const span = startSpan({
20100
- name: "embed_content",
20101
- spanAttributes: {
20102
- type: "llm" /* LLM */
20103
- },
20104
- event: createWrapperParityEvent({ input, metadata })
20105
- });
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
+ );
20106
21213
  return {
20107
21214
  span,
20108
21215
  startTime: getCurrentUnixTimestamp()
@@ -20115,13 +21222,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
20115
21222
  const params = event.arguments[0];
20116
21223
  const input = serializeEmbedContentInput(params);
20117
21224
  const metadata = extractEmbedContentMetadata(params);
20118
- const span = startSpan({
20119
- name: "embed_content",
20120
- spanAttributes: {
20121
- type: "llm" /* LLM */
20122
- },
20123
- event: createWrapperParityEvent({ input, metadata })
20124
- });
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
+ );
20125
21237
  return {
20126
21238
  span,
20127
21239
  startTime: getCurrentUnixTimestamp()
@@ -20232,16 +21344,21 @@ function patchGoogleGenAIStreamingResult(args) {
20232
21344
  const requestStartTime = startTime ?? getCurrentUnixTimestamp();
20233
21345
  const ensureSpan = () => {
20234
21346
  if (!span) {
20235
- span = startSpan({
20236
- name: "generate_content_stream",
20237
- spanAttributes: {
20238
- type: "llm" /* LLM */
20239
- },
20240
- event: {
20241
- input,
20242
- metadata
20243
- }
20244
- });
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
+ );
20245
21362
  }
20246
21363
  return span;
20247
21364
  };
@@ -21009,28 +22126,32 @@ function tryToDict(obj) {
21009
22126
  }
21010
22127
 
21011
22128
  // src/instrumentation/plugins/huggingface-channels.ts
21012
- var huggingFaceChannels = defineChannels("@huggingface/inference", {
21013
- chatCompletion: channel({
21014
- channelName: "chatCompletion",
21015
- kind: "async"
21016
- }),
21017
- chatCompletionStream: channel({
21018
- channelName: "chatCompletionStream",
21019
- kind: "sync-stream"
21020
- }),
21021
- textGeneration: channel({
21022
- channelName: "textGeneration",
21023
- kind: "async"
21024
- }),
21025
- textGenerationStream: channel({
21026
- channelName: "textGenerationStream",
21027
- kind: "sync-stream"
21028
- }),
21029
- featureExtraction: channel({
21030
- channelName: "featureExtraction",
21031
- kind: "async"
21032
- })
21033
- });
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
+ );
21034
22155
 
21035
22156
  // src/instrumentation/plugins/huggingface-plugin.ts
21036
22157
  var REQUEST_METADATA_ALLOWLIST = /* @__PURE__ */ new Set([
@@ -21457,20 +22578,24 @@ function extractTextGenerationStreamMetadata(chunks) {
21457
22578
  }
21458
22579
 
21459
22580
  // src/instrumentation/plugins/openrouter-agent-channels.ts
21460
- var openRouterAgentChannels = defineChannels("@openrouter/agent", {
21461
- callModel: channel({
21462
- channelName: "callModel",
21463
- kind: "sync-stream"
21464
- }),
21465
- callModelTurn: channel({
21466
- channelName: "callModel.turn",
21467
- kind: "async"
21468
- }),
21469
- toolExecute: channel({
21470
- channelName: "tool.execute",
21471
- kind: "async"
21472
- })
21473
- });
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
+ );
21474
22599
 
21475
22600
  // src/instrumentation/plugins/openrouter-agent-plugin.ts
21476
22601
  var OpenRouterAgentPlugin = class extends BasePlugin {
@@ -22240,38 +23365,40 @@ function normalizeError(error) {
22240
23365
  }
22241
23366
 
22242
23367
  // src/instrumentation/plugins/openrouter-channels.ts
22243
- var openRouterChannels = defineChannels("@openrouter/sdk", {
22244
- chatSend: channel({
22245
- channelName: "chat.send",
22246
- kind: "async"
22247
- }),
22248
- embeddingsGenerate: channel({
22249
- channelName: "embeddings.generate",
22250
- kind: "async"
22251
- }),
22252
- rerankRerank: channel(
22253
- {
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({
22254
23380
  channelName: "rerank.rerank",
22255
23381
  kind: "async"
22256
- }
22257
- ),
22258
- betaResponsesSend: channel({
22259
- channelName: "beta.responses.send",
22260
- kind: "async"
22261
- }),
22262
- callModel: channel({
22263
- channelName: "callModel",
22264
- kind: "sync-stream"
22265
- }),
22266
- callModelTurn: channel({
22267
- channelName: "callModel.turn",
22268
- kind: "async"
22269
- }),
22270
- toolExecute: channel({
22271
- channelName: "tool.execute",
22272
- kind: "async"
22273
- })
22274
- });
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
+ );
22275
23402
 
22276
23403
  // src/instrumentation/plugins/openrouter-plugin.ts
22277
23404
  var OpenRouterPlugin = class extends BasePlugin {
@@ -23311,52 +24438,56 @@ function normalizeError2(error) {
23311
24438
  }
23312
24439
 
23313
24440
  // src/instrumentation/plugins/mistral-channels.ts
23314
- var mistralChannels = defineChannels("@mistralai/mistralai", {
23315
- chatComplete: channel({
23316
- channelName: "chat.complete",
23317
- kind: "async"
23318
- }),
23319
- chatStream: channel({
23320
- channelName: "chat.stream",
23321
- kind: "async"
23322
- }),
23323
- embeddingsCreate: channel({
23324
- channelName: "embeddings.create",
23325
- kind: "async"
23326
- }),
23327
- classifiersModerate: channel({
23328
- channelName: "classifiers.moderate",
23329
- kind: "async"
23330
- }),
23331
- classifiersModerateChat: channel({
23332
- channelName: "classifiers.moderateChat",
23333
- kind: "async"
23334
- }),
23335
- classifiersClassify: channel({
23336
- channelName: "classifiers.classify",
23337
- kind: "async"
23338
- }),
23339
- classifiersClassifyChat: channel({
23340
- channelName: "classifiers.classifyChat",
23341
- kind: "async"
23342
- }),
23343
- fimComplete: channel({
23344
- channelName: "fim.complete",
23345
- kind: "async"
23346
- }),
23347
- fimStream: channel({
23348
- channelName: "fim.stream",
23349
- kind: "async"
23350
- }),
23351
- agentsComplete: channel({
23352
- channelName: "agents.complete",
23353
- kind: "async"
23354
- }),
23355
- agentsStream: channel({
23356
- channelName: "agents.stream",
23357
- kind: "async"
23358
- })
23359
- });
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
+ );
23360
24491
 
23361
24492
  // src/instrumentation/plugins/mistral-plugin.ts
23362
24493
  var MistralPlugin = class extends BasePlugin {
@@ -23976,20 +25107,24 @@ function aggregateMistralStreamChunks(chunks) {
23976
25107
  }
23977
25108
 
23978
25109
  // src/instrumentation/plugins/google-adk-channels.ts
23979
- var googleADKChannels = defineChannels("@google/adk", {
23980
- runnerRunAsync: channel({
23981
- channelName: "runner.runAsync",
23982
- kind: "sync-stream"
23983
- }),
23984
- agentRunAsync: channel({
23985
- channelName: "agent.runAsync",
23986
- kind: "sync-stream"
23987
- }),
23988
- toolRunAsync: channel({
23989
- channelName: "tool.runAsync",
23990
- kind: "async"
23991
- })
23992
- });
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
+ );
23993
25128
 
23994
25129
  // src/instrumentation/plugins/google-adk-plugin.ts
23995
25130
  var GoogleADKPlugin = class extends BasePlugin {
@@ -24014,12 +25149,17 @@ var GoogleADKPlugin = class extends BasePlugin {
24014
25149
  const createState = (event) => {
24015
25150
  const params = event.arguments[0] ?? {};
24016
25151
  const contextKey = extractRunnerContextKey(params);
24017
- const span = startSpan({
24018
- name: "Google ADK Runner",
24019
- spanAttributes: {
24020
- type: "task" /* TASK */
24021
- }
24022
- });
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
+ );
24023
25163
  const startTime = getCurrentUnixTimestamp();
24024
25164
  try {
24025
25165
  const metadata = extractRunnerMetadata(params);
@@ -24105,18 +25245,23 @@ var GoogleADKPlugin = class extends BasePlugin {
24105
25245
  this.activeRunnerSpans
24106
25246
  );
24107
25247
  const contextKey = extractInvocationContextKey(parentContext);
24108
- const span = startSpan({
24109
- name: agentName ? `Agent: ${agentName}` : "Google ADK Agent",
24110
- spanAttributes: {
24111
- type: "task" /* TASK */
24112
- },
24113
- ...runnerParentSpan ? {
24114
- parentSpanIds: {
24115
- spanId: runnerParentSpan.spanId,
24116
- rootSpanId: runnerParentSpan.rootSpanId
24117
- }
24118
- } : {}
24119
- });
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
+ );
24120
25265
  const startTime = getCurrentUnixTimestamp();
24121
25266
  try {
24122
25267
  const metadata = {
@@ -24209,22 +25354,27 @@ var GoogleADKPlugin = class extends BasePlugin {
24209
25354
  this.activeAgentSpans,
24210
25355
  this.activeRunnerSpans
24211
25356
  );
24212
- const createSpan = () => startSpan({
24213
- name: toolName ? `tool: ${toolName}` : "Google ADK Tool",
24214
- spanAttributes: {
24215
- type: "tool" /* TOOL */
24216
- },
24217
- event: {
24218
- input: req.args,
24219
- metadata: {
24220
- provider: "google-adk",
24221
- ...toolName && { "google_adk.tool_name": toolName },
24222
- ...extractToolCallId(req) && {
24223
- "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
+ }
24224
25373
  }
24225
- }
24226
- }
24227
- });
25374
+ },
25375
+ INSTRUMENTATION_NAMES.GOOGLE_ADK
25376
+ )
25377
+ );
24228
25378
  const span = parentSpan ? withCurrent(parentSpan, () => createSpan()) : createSpan();
24229
25379
  const startTime = getCurrentUnixTimestamp();
24230
25380
  states.set(event, { span, startTime });
@@ -24623,24 +25773,28 @@ function cleanMetrics4(metrics) {
24623
25773
  }
24624
25774
 
24625
25775
  // src/instrumentation/plugins/cohere-channels.ts
24626
- var cohereChannels = defineChannels("cohere-ai", {
24627
- chat: channel({
24628
- channelName: "chat",
24629
- kind: "async"
24630
- }),
24631
- chatStream: channel({
24632
- channelName: "chatStream",
24633
- kind: "async"
24634
- }),
24635
- embed: channel({
24636
- channelName: "embed",
24637
- kind: "async"
24638
- }),
24639
- rerank: channel({
24640
- channelName: "rerank",
24641
- kind: "async"
24642
- })
24643
- });
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
+ );
24644
25798
 
24645
25799
  // src/instrumentation/plugins/cohere-plugin.ts
24646
25800
  var CoherePlugin = class extends BasePlugin {
@@ -25309,18 +26463,20 @@ function aggregateCohereChatStreamChunks(chunks) {
25309
26463
  }
25310
26464
 
25311
26465
  // src/instrumentation/plugins/groq-channels.ts
25312
- var groqChannels = defineChannels("groq-sdk", {
25313
- chatCompletionsCreate: channel({
25314
- channelName: "chat.completions.create",
25315
- kind: "async"
25316
- }),
25317
- embeddingsCreate: channel(
25318
- {
26466
+ var groqChannels = defineChannels(
26467
+ "groq-sdk",
26468
+ {
26469
+ chatCompletionsCreate: channel({
26470
+ channelName: "chat.completions.create",
26471
+ kind: "async"
26472
+ }),
26473
+ embeddingsCreate: channel({
25319
26474
  channelName: "embeddings.create",
25320
26475
  kind: "async"
25321
- }
25322
- )
25323
- });
26476
+ })
26477
+ },
26478
+ { instrumentationName: INSTRUMENTATION_NAMES.GROQ }
26479
+ );
25324
26480
 
25325
26481
  // src/instrumentation/plugins/groq-plugin.ts
25326
26482
  var GroqPlugin = class extends BasePlugin {
@@ -25423,15 +26579,27 @@ var clientSendChannel = channel({
25423
26579
  channelName: "client.send",
25424
26580
  kind: "async"
25425
26581
  });
25426
- var bedrockRuntimeChannels = defineChannels("aws-bedrock-runtime", {
25427
- clientSend: clientSendChannel
25428
- });
25429
- var smithyCoreChannels = defineChannels("@smithy/core", {
25430
- clientSend: clientSendChannel
25431
- });
25432
- var smithyClientChannels = defineChannels("@smithy/smithy-client", {
25433
- clientSend: clientSendChannel
25434
- });
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
+ );
25435
26603
 
25436
26604
  // src/instrumentation/plugins/bedrock-runtime-common.ts
25437
26605
  var BEDROCK_RUNTIME_COMMAND_OPERATIONS = {
@@ -26065,38 +27233,46 @@ function extractTextFromJsonLike(value) {
26065
27233
  }
26066
27234
 
26067
27235
  // src/instrumentation/plugins/genkit-channels.ts
26068
- var genkitChannels = defineChannels("@genkit-ai/ai", {
26069
- generate: channel({
26070
- channelName: "generate",
26071
- kind: "async"
26072
- }),
26073
- generateStream: channel({
26074
- channelName: "generateStream",
26075
- kind: "sync-stream"
26076
- }),
26077
- embed: channel({
26078
- channelName: "embed",
26079
- kind: "async"
26080
- }),
26081
- embedMany: channel({
26082
- channelName: "embedMany",
26083
- kind: "async"
26084
- }),
26085
- actionRun: channel({
26086
- channelName: "action.run",
26087
- kind: "async"
26088
- }),
26089
- actionStream: channel({
26090
- channelName: "action.stream",
26091
- kind: "sync-stream"
26092
- })
26093
- });
26094
- var genkitCoreChannels = defineChannels("@genkit-ai/core", {
26095
- actionSpan: channel({
26096
- channelName: "action.span",
26097
- kind: "async"
26098
- })
26099
- });
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
+ );
26100
27276
 
26101
27277
  // src/instrumentation/plugins/genkit-plugin.ts
26102
27278
  var GenkitPlugin = class extends BasePlugin {
@@ -26281,12 +27457,17 @@ function startActionSpanState(args) {
26281
27457
  if (!shouldTraceAction(args.metadata, args.runStepName)) {
26282
27458
  return void 0;
26283
27459
  }
26284
- const span = startSpan({
26285
- name: actionSpanName(args.metadata, args.runStepName),
26286
- spanAttributes: {
26287
- type: actionSpanType(args.metadata)
26288
- }
26289
- });
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
+ );
26290
27471
  const startTime = getCurrentUnixTimestamp();
26291
27472
  span.log({
26292
27473
  input: args.input,
@@ -26647,20 +27828,24 @@ function stringValue(value) {
26647
27828
  }
26648
27829
 
26649
27830
  // src/instrumentation/plugins/github-copilot-channels.ts
26650
- var gitHubCopilotChannels = defineChannels("@github/copilot-sdk", {
26651
- createSession: channel({
26652
- channelName: "client.createSession",
26653
- kind: "async"
26654
- }),
26655
- resumeSession: channel({
26656
- channelName: "client.resumeSession",
26657
- kind: "async"
26658
- }),
26659
- sendAndWait: channel({
26660
- channelName: "session.sendAndWait",
26661
- kind: "async"
26662
- })
26663
- });
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
+ );
26664
27849
 
26665
27850
  // src/instrumentation/plugins/github-copilot-plugin.ts
26666
27851
  var ROOT_AGENT_KEY = "__root__";
@@ -26751,11 +27936,16 @@ async function handleTurnStart(state, agentId) {
26751
27936
  return;
26752
27937
  }
26753
27938
  const parentId = await getParentIdForAgent(state, agentId);
26754
- const span = startSpan({
26755
- name: "Copilot Turn",
26756
- parent: parentId,
26757
- spanAttributes: { type: "task" /* TASK */ }
26758
- });
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
+ );
26759
27949
  const pendingUserMessage = state.pendingUserMessages.get(key);
26760
27950
  if (pendingUserMessage) {
26761
27951
  span.log({ input: pendingUserMessage });
@@ -26786,11 +27976,16 @@ async function handleUsage(state, agentId, usage) {
26786
27976
  const parentId = turn ? await turn.id : await state.session.id;
26787
27977
  const content = state.currentMessageContent.get(key);
26788
27978
  const { metrics, metadata } = extractMetricsFromUsage(usage);
26789
- const llmSpan = startSpan({
26790
- name: "github.copilot.llm",
26791
- parent: parentId,
26792
- spanAttributes: { type: "llm" /* LLM */ }
26793
- });
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
+ );
26794
27989
  llmSpan.log({
26795
27990
  output: content ?? void 0,
26796
27991
  metadata,
@@ -26816,11 +28011,16 @@ async function handleToolStart(state, agentId, toolCallId, toolName, args, mcpSe
26816
28011
  }
26817
28012
  const parentId = await getToolParentId(state, agentId);
26818
28013
  const displayName = mcpServerName ? `tool: ${mcpServerName}/${toolName}` : `tool: ${toolName}`;
26819
- const span = startSpan({
26820
- name: displayName,
26821
- parent: parentId,
26822
- spanAttributes: { type: "tool" /* TOOL */ }
26823
- });
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
+ );
26824
28024
  const metadata = {
26825
28025
  "gen_ai.tool.name": toolName,
26826
28026
  "gen_ai.tool.call.id": toolCallId
@@ -26856,11 +28056,16 @@ async function handleSubagentStarted(state, agentId, toolCallId, agentDisplayNam
26856
28056
  }
26857
28057
  const tool = state.activeTools.get(toolCallId);
26858
28058
  const parentId = tool ? await tool.id : await state.session.id;
26859
- const span = startSpan({
26860
- name: `Agent: ${agentDisplayName}`,
26861
- parent: parentId,
26862
- spanAttributes: { type: "task" /* TASK */ }
26863
- });
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
+ );
26864
28069
  span.log({
26865
28070
  metadata: {
26866
28071
  "github_copilot.agent_name": agentDisplayName,
@@ -27086,10 +28291,15 @@ function makeSessionHandlers(sessionStates, configArgIndex, includeProviderMetad
27086
28291
  if (!config || typeof config !== "object") {
27087
28292
  return;
27088
28293
  }
27089
- const sessionSpan = startSpan({
27090
- name: "Copilot Session",
27091
- spanAttributes: { type: "task" /* TASK */ }
27092
- });
28294
+ const sessionSpan = startSpan(
28295
+ withSpanInstrumentationName(
28296
+ {
28297
+ name: "Copilot Session",
28298
+ spanAttributes: { type: "task" /* TASK */ }
28299
+ },
28300
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
28301
+ )
28302
+ );
27093
28303
  const metadata = {};
27094
28304
  if (config.model) {
27095
28305
  metadata["github_copilot.model"] = config.model;
@@ -27177,12 +28387,16 @@ var GitHubCopilotPlugin = class extends BasePlugin {
27177
28387
  };
27178
28388
 
27179
28389
  // src/instrumentation/plugins/flue-channels.ts
27180
- var flueChannels = defineChannels("@flue/runtime", {
27181
- createContext: channel({
27182
- channelName: "createFlueContext",
27183
- kind: "sync-stream"
27184
- })
27185
- });
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
+ );
27186
28400
 
27187
28401
  // src/instrumentation/plugins/flue-plugin.ts
27188
28402
  var FLUE_AUTO_STATE = /* @__PURE__ */ Symbol.for("braintrust.flue.auto-state");
@@ -27525,15 +28739,20 @@ var FlueObserveBridge = class {
27525
28739
  safeLog3(existing.span, { input, metadata });
27526
28740
  return;
27527
28741
  }
27528
- const span = startSpan({
27529
- name: `workflow:${workflowName}`,
27530
- spanAttributes: { type: "task" /* TASK */ },
27531
- startTime: eventTime(event.startedAt ?? event.timestamp),
27532
- event: {
27533
- input,
27534
- metadata
27535
- }
27536
- });
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
+ );
27537
28756
  this.runsById.set(event.runId, { metadata, span });
27538
28757
  }
27539
28758
  handleRunResume(event, ctx) {
@@ -27553,12 +28772,17 @@ var FlueObserveBridge = class {
27553
28772
  safeLog3(existing.span, { metadata });
27554
28773
  return;
27555
28774
  }
27556
- const span = startSpan({
27557
- name: `workflow:${workflowName}`,
27558
- spanAttributes: { type: "task" /* TASK */ },
27559
- startTime: eventTime(event.startedAt ?? event.timestamp),
27560
- event: { metadata }
27561
- });
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
+ );
27562
28786
  this.runsById.set(event.runId, { metadata, span });
27563
28787
  }
27564
28788
  handleRunEnd(event) {
@@ -28197,7 +29421,14 @@ function stateMatchesRun(state, runId) {
28197
29421
  return state.metadata["flue.run_id"] === runId;
28198
29422
  }
28199
29423
  function startFlueSpan(parent, args) {
28200
- 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
+ );
28201
29432
  }
28202
29433
  function runWithCurrentSpanStore(span, next) {
28203
29434
  const state = _internalGetGlobalState();
@@ -28287,9 +29518,13 @@ var BraintrustLangChainCallbackHandler = class {
28287
29518
  ...this.options.debug ? { runId, parentRunId } : {}
28288
29519
  }
28289
29520
  };
28290
- let span = parentSpan.startSpan(args);
29521
+ const spanArgs = withSpanInstrumentationName(
29522
+ args,
29523
+ INSTRUMENTATION_NAMES.LANGCHAIN
29524
+ );
29525
+ let span = parentSpan.startSpan(spanArgs);
28291
29526
  if (!Object.is(this.options.logger, NOOP_SPAN) && Object.is(span, NOOP_SPAN)) {
28292
- span = initLogger().startSpan(args);
29527
+ span = initLogger().startSpan(spanArgs);
28293
29528
  }
28294
29529
  this.spans.set(runId, span);
28295
29530
  }
@@ -28502,6 +29737,16 @@ function cleanObject(obj) {
28502
29737
  })
28503
29738
  );
28504
29739
  }
29740
+ function normalizeTokenMetrics(obj) {
29741
+ const metrics = cleanObject(obj);
29742
+ if (metrics.total_tokens !== void 0) {
29743
+ metrics.tokens = metrics.total_tokens;
29744
+ } else if (metrics.prompt_tokens !== void 0 && metrics.completion_tokens !== void 0) {
29745
+ metrics.tokens = metrics.prompt_tokens + metrics.completion_tokens;
29746
+ }
29747
+ delete metrics.total_tokens;
29748
+ return metrics;
29749
+ }
28505
29750
  function walkGenerations(response) {
28506
29751
  const result = [];
28507
29752
  const generations = response.generations || [];
@@ -28548,7 +29793,7 @@ function getMetricsFromResponse(response) {
28548
29793
  continue;
28549
29794
  }
28550
29795
  const inputTokenDetails = usageMetadata.input_token_details;
28551
- return cleanObject({
29796
+ return normalizeTokenMetrics({
28552
29797
  total_tokens: usageMetadata.total_tokens,
28553
29798
  prompt_tokens: usageMetadata.input_tokens,
28554
29799
  completion_tokens: usageMetadata.output_tokens,
@@ -28558,7 +29803,7 @@ function getMetricsFromResponse(response) {
28558
29803
  }
28559
29804
  const llmOutput = response.llmOutput || {};
28560
29805
  const tokenUsage = isRecord(llmOutput.tokenUsage) ? llmOutput.tokenUsage : isRecord(llmOutput.estimatedTokens) ? llmOutput.estimatedTokens : {};
28561
- return cleanObject({
29806
+ return normalizeTokenMetrics({
28562
29807
  total_tokens: tokenUsage.totalTokens,
28563
29808
  prompt_tokens: tokenUsage.promptTokens,
28564
29809
  completion_tokens: tokenUsage.completionTokens
@@ -28576,16 +29821,20 @@ function isRecord(value) {
28576
29821
  }
28577
29822
 
28578
29823
  // src/instrumentation/plugins/langchain-channels.ts
28579
- var langChainChannels = defineChannels("@langchain/core", {
28580
- configure: channel({
28581
- channelName: "CallbackManager.configure",
28582
- kind: "sync-stream"
28583
- }),
28584
- configureSync: channel({
28585
- channelName: "CallbackManager._configureSync",
28586
- kind: "sync-stream"
28587
- })
28588
- });
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
+ );
28589
29838
 
28590
29839
  // src/instrumentation/plugins/langchain-plugin.ts
28591
29840
  var LangChainPlugin = class extends BasePlugin {
@@ -28673,20 +29922,24 @@ function isBraintrustHandler(handler) {
28673
29922
  }
28674
29923
 
28675
29924
  // src/instrumentation/plugins/langsmith-channels.ts
28676
- var langSmithChannels = defineChannels("langsmith", {
28677
- createRun: channel({
28678
- channelName: "Client.createRun",
28679
- kind: "async"
28680
- }),
28681
- updateRun: channel({
28682
- channelName: "Client.updateRun",
28683
- kind: "async"
28684
- }),
28685
- batchIngestRuns: channel({
28686
- channelName: "Client.batchIngestRuns",
28687
- kind: "async"
28688
- })
28689
- });
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
+ );
28690
29943
 
28691
29944
  // src/instrumentation/plugins/langsmith-plugin.ts
28692
29945
  var MAX_COMPLETED_RUNS = 1e4;
@@ -28850,19 +30103,24 @@ var LangSmithPlugin = class extends BasePlugin {
28850
30103
  const traceId = stringValue2(ownValue(run, "trace_id")) ?? id;
28851
30104
  const parentId = stringValue2(ownValue(run, "parent_run_id")) ?? stringValue2(ownValue(ownValue(run, "parent_run"), "id"));
28852
30105
  const startTime = timestampSeconds(ownValue(run, "start_time"));
28853
- return startSpan({
28854
- name: stringValue2(ownValue(run, "name")) ?? "LangSmith run",
28855
- spanId: id,
28856
- parentSpanIds: {
28857
- parentSpanIds: parentId ? [parentId] : [],
28858
- rootSpanId: traceId
28859
- },
28860
- spanAttributes: {
28861
- type: mapRunType(ownValue(run, "run_type"))
28862
- },
28863
- ...startTime === void 0 ? {} : { startTime },
28864
- event: { id }
28865
- });
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
+ );
28866
30124
  }
28867
30125
  logRun(span, run, previous, includeOutput) {
28868
30126
  const inputs = preferOwnValue(run, previous, "inputs");
@@ -29120,7 +30378,8 @@ var piCodingAgentChannels = defineChannels(
29120
30378
  channelName: "AgentSession.prompt",
29121
30379
  kind: "async"
29122
30380
  })
29123
- }
30381
+ },
30382
+ { instrumentationName: INSTRUMENTATION_NAMES.PI_CODING_AGENT }
29124
30383
  );
29125
30384
 
29126
30385
  // src/instrumentation/plugins/pi-coding-agent-plugin.ts
@@ -29204,14 +30463,19 @@ function startPiPromptRun(event, onFinalize) {
29204
30463
  ...session.model?.id || agent.state?.model?.id ? { model: session.model?.id ?? agent.state?.model?.id } : {},
29205
30464
  ...event.moduleVersion ? { "pi_coding_agent.version": event.moduleVersion } : {}
29206
30465
  };
29207
- const span = startSpan({
29208
- event: {
29209
- input: extractPromptInput(event.arguments[0], event.arguments[1]),
29210
- metadata
29211
- },
29212
- name: "AgentSession.prompt",
29213
- spanAttributes: { type: "task" /* TASK */ }
29214
- });
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
+ );
29215
30479
  const streamPatchState = installPiStreamPatch(agent);
29216
30480
  const options = event.arguments[1];
29217
30481
  const promptText = event.arguments[0];
@@ -29381,15 +30645,20 @@ async function startPiLlmSpan(state, model, context, options) {
29381
30645
  ...extractToolMetadata(context.tools),
29382
30646
  "pi_coding_agent.operation": "agent.streamFn"
29383
30647
  };
29384
- const span = startSpan({
29385
- event: {
29386
- input: processInputAttachments(normalizePiContextInput(context)),
29387
- metadata
29388
- },
29389
- name: getLlmSpanName(model),
29390
- parent: await state.span.export(),
29391
- spanAttributes: { type: "llm" /* LLM */ }
29392
- });
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
+ );
29393
30662
  const llmState = {
29394
30663
  finalized: false,
29395
30664
  metadata,
@@ -29557,15 +30826,20 @@ async function startPiToolSpan(state, event) {
29557
30826
  "pi_coding_agent.tool.name": event.toolName
29558
30827
  };
29559
30828
  try {
29560
- const span = startSpan({
29561
- event: {
29562
- input: event.args,
29563
- metadata
29564
- },
29565
- name: event.toolName || "tool",
29566
- parent: await state.span.export(),
29567
- spanAttributes: { type: "tool" /* TOOL */ }
29568
- });
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
+ );
29569
30843
  state.activeToolSpans.set(event.toolCallId, {
29570
30844
  restoreAutoInstrumentation,
29571
30845
  span
@@ -29997,20 +31271,24 @@ function logInstrumentationError4(context, error) {
29997
31271
  }
29998
31272
 
29999
31273
  // src/instrumentation/plugins/strands-agent-sdk-channels.ts
30000
- var strandsAgentSDKChannels = defineChannels("@strands-agents/sdk", {
30001
- agentStream: channel({
30002
- channelName: "Agent.stream",
30003
- kind: "sync-stream"
30004
- }),
30005
- graphStream: channel({
30006
- channelName: "Graph.stream",
30007
- kind: "sync-stream"
30008
- }),
30009
- swarmStream: channel({
30010
- channelName: "Swarm.stream",
30011
- kind: "sync-stream"
30012
- })
30013
- });
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
+ );
30014
31292
 
30015
31293
  // src/instrumentation/plugins/strands-agent-sdk-plugin.ts
30016
31294
  var MAX_STRANDS_STRING_ATTACHMENT_CACHE_ENTRIES = 32;
@@ -30165,22 +31443,32 @@ function startAgentStream(event, activeChildParents) {
30165
31443
  );
30166
31444
  const span = parentSpan ? withCurrent(
30167
31445
  parentSpan,
30168
- () => startSpan({
30169
- event: {
30170
- input,
30171
- 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 */ }
30172
31468
  },
30173
- name: formatAgentSpanName(agent),
30174
- spanAttributes: { type: "task" /* TASK */ }
30175
- })
30176
- ) : startSpan({
30177
- event: {
30178
- input,
30179
- metadata
30180
- },
30181
- name: formatAgentSpanName(agent),
30182
- spanAttributes: { type: "task" /* TASK */ }
30183
- });
31469
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
31470
+ )
31471
+ );
30184
31472
  return {
30185
31473
  activeTools: /* @__PURE__ */ new Map(),
30186
31474
  attachmentCache,
@@ -30202,22 +31490,32 @@ function startMultiAgentStream(event, operation, activeChildParents) {
30202
31490
  const input = processStrandsInputAttachments(event.arguments[0]);
30203
31491
  const span = parentSpan ? withCurrent(
30204
31492
  parentSpan,
30205
- () => startSpan({
30206
- event: {
30207
- input,
30208
- 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 */ }
30209
31515
  },
30210
- name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
30211
- spanAttributes: { type: "task" /* TASK */ }
30212
- })
30213
- ) : startSpan({
30214
- event: {
30215
- input,
30216
- metadata
30217
- },
30218
- name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
30219
- spanAttributes: { type: "task" /* TASK */ }
30220
- });
31516
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
31517
+ )
31518
+ );
30221
31519
  return {
30222
31520
  activeNodes: /* @__PURE__ */ new Map(),
30223
31521
  finalized: false,
@@ -30319,17 +31617,22 @@ function startModelSpan(state, event) {
30319
31617
  };
30320
31618
  const span = withCurrent(
30321
31619
  state.span,
30322
- () => startSpan({
30323
- event: {
30324
- input: Array.isArray(event.agent?.messages) ? processStrandsInputAttachments(
30325
- event.agent.messages,
30326
- state.attachmentCache
30327
- ) : void 0,
30328
- metadata
30329
- },
30330
- name: formatModelSpanName(model),
30331
- spanAttributes: { type: "llm" /* LLM */ }
30332
- })
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
+ )
30333
31636
  );
30334
31637
  state.activeModel = {
30335
31638
  metadata,
@@ -30381,20 +31684,25 @@ function startToolSpan2(state, event) {
30381
31684
  const name = extractToolName3(toolUse, event.tool);
30382
31685
  const span = withCurrent(
30383
31686
  state.span,
30384
- () => startSpan({
30385
- event: {
30386
- input: toolUse?.input,
30387
- metadata: {
30388
- "gen_ai.tool.call.id": toolUse?.toolUseId,
30389
- "gen_ai.tool.name": name,
30390
- "strands.operation": "tool.call",
30391
- "strands.tool.name": name,
30392
- provider: "strands"
30393
- }
30394
- },
30395
- name: `tool: ${name}`,
30396
- spanAttributes: { type: "tool" /* TOOL */ }
30397
- })
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
+ )
30398
31706
  );
30399
31707
  state.activeTools.set(key, {
30400
31708
  span,
@@ -30465,11 +31773,16 @@ function startNodeSpan(state, event, activeChildParents) {
30465
31773
  };
30466
31774
  const span = withCurrent(
30467
31775
  state.span,
30468
- () => startSpan({
30469
- event: { metadata },
30470
- name: `node: ${nodeId}`,
30471
- spanAttributes: { type: "task" /* TASK */ }
30472
- })
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
+ )
30473
31786
  );
30474
31787
  const nodeState = {
30475
31788
  ...child ? { child } : {},
@@ -31583,17 +32896,20 @@ var BraintrustObservabilityExporter = class {
31583
32896
  }
31584
32897
  onStart(exported) {
31585
32898
  if (this.spans.has(exported.id)) return;
31586
- const args = {
31587
- name: exported.name,
31588
- spanAttributes: { type: spanTypeFor(exported.type) },
31589
- startTime: epochSeconds(exported.startTime),
31590
- // Use the Mastra span id as the Braintrust row id so that
31591
- // `logFeedback({ id: <mastra span id> })` (and Mastra's score events)
31592
- // attach to the right row. Without this, `SpanImpl` auto-generates a
31593
- // row id (`this._id = eventId ?? idGenerator.getSpanId()`) that no
31594
- // external caller could know.
31595
- event: { id: exported.id }
31596
- };
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
+ );
31597
32913
  const parentRecord = exported.parentSpanId ? this.spans.get(exported.parentSpanId) : void 0;
31598
32914
  if (!this.capturedParent) {
31599
32915
  const probe = currentSpan();
@@ -31668,7 +32984,13 @@ function configureNode() {
31668
32984
  isomorph_default.getPastNAncestors = getPastNAncestors;
31669
32985
  isomorph_default.getEnv = (name) => {
31670
32986
  const value = process.env[name];
31671
- return name === "BRAINTRUST_API_KEY" && !value?.trim() ? void 0 : value;
32987
+ if (name === "BRAINTRUST_API_KEY") {
32988
+ return value?.trim() ? value : void 0;
32989
+ }
32990
+ if ((name === "BRAINTRUST_ENVIRONMENT_TYPE" || name === "BRAINTRUST_ENVIRONMENT_NAME") && !value?.trim()) {
32991
+ return getNearestBraintrustEnvValue(name);
32992
+ }
32993
+ return value;
31672
32994
  };
31673
32995
  isomorph_default.getBraintrustApiKey = async () => {
31674
32996
  const value = process.env.BRAINTRUST_API_KEY;
@@ -31744,6 +33066,12 @@ function configureNode() {
31744
33066
  isomorph_default.gzip = promisify(zlib.gzip);
31745
33067
  isomorph_default.gunzip = promisify(zlib.gunzip);
31746
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
+ };
31747
33075
  _internalSetInitialState();
31748
33076
  const disabled = readDisabledInstrumentationEnvConfig(
31749
33077
  isomorph_default.getEnv("BRAINTRUST_DISABLE_INSTRUMENTATION")
@@ -31753,6 +33081,24 @@ function configureNode() {
31753
33081
  }
31754
33082
  registry.enable();
31755
33083
  }
33084
+ function getNearestBraintrustEnvValue(name) {
33085
+ for (let dir2 = process.cwd(), depth = 0; depth <= BRAINTRUST_ENV_SEARCH_PARENT_LIMIT; dir2 = path.dirname(dir2), depth++) {
33086
+ const envPath = path.join(dir2, ".env.braintrust");
33087
+ try {
33088
+ const parsed = dotenv.parse(fsSync.readFileSync(envPath, "utf8"));
33089
+ const value = parsed[name];
33090
+ return value?.trim() ? value : void 0;
33091
+ } catch (e) {
33092
+ if (typeof e !== "object" || e === null || !("code" in e) || e.code !== "ENOENT") {
33093
+ return void 0;
33094
+ }
33095
+ }
33096
+ if (path.dirname(dir2) === dir2) {
33097
+ break;
33098
+ }
33099
+ }
33100
+ return void 0;
33101
+ }
31756
33102
 
31757
33103
  // dev/server.ts
31758
33104
  import express from "express";
@@ -32897,6 +34243,10 @@ var SpanFetcher = class _SpanFetcher extends ObjectFetcher {
32897
34243
  this._state = _state;
32898
34244
  this.spanTypeFilter = spanTypeFilter;
32899
34245
  }
34246
+ _objectId;
34247
+ rootSpanId;
34248
+ _state;
34249
+ spanTypeFilter;
32900
34250
  static buildFilter(rootSpanId, spanTypeFilter, includeScorers = false) {
32901
34251
  const children = [
32902
34252
  // Base filter: root_span_id = 'value'
@@ -33344,6 +34694,8 @@ var EvalResultWithSummary = class {
33344
34694
  this.summary = summary;
33345
34695
  this.results = results;
33346
34696
  }
34697
+ summary;
34698
+ results;
33347
34699
  /**
33348
34700
  * @deprecated Use `summary` instead.
33349
34701
  */
@@ -34042,26 +35394,30 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
34042
35394
  }
34043
35395
  }
34044
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
+ };
34045
35409
  const cancel = async () => {
34046
35410
  await new Promise((_, reject2) => {
34047
35411
  if (cancelled) {
34048
35412
  reject2(new InternalAbortError("Evaluator already cancelled"));
34049
35413
  return;
34050
35414
  }
34051
- let timeoutId;
34052
- let abortHandler;
34053
35415
  const rejectOnce = (error) => {
34054
35416
  if (cancelled) {
34055
35417
  return;
34056
35418
  }
34057
35419
  cancelled = true;
34058
- if (timeoutId) {
34059
- clearTimeout(timeoutId);
34060
- timeoutId = void 0;
34061
- }
34062
- if (abortHandler && evaluator.signal) {
34063
- evaluator.signal.removeEventListener("abort", abortHandler);
34064
- }
35420
+ cleanupCancellation();
34065
35421
  reject2(error);
34066
35422
  };
34067
35423
  if (evaluator.timeout) {
@@ -34101,6 +35457,7 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
34101
35457
  }
34102
35458
  throw e;
34103
35459
  } finally {
35460
+ cleanupCancellation();
34104
35461
  if (!collectResults) {
34105
35462
  collectedResults.length = 0;
34106
35463
  }
@@ -34636,6 +35993,7 @@ var ToolBuilder = class {
34636
35993
  constructor(project) {
34637
35994
  this.project = project;
34638
35995
  }
35996
+ project;
34639
35997
  taskCounter = 0;
34640
35998
  // This type definition is just a catch all so that the implementation can be
34641
35999
  // less specific than the two more specific declarations above.
@@ -34666,6 +36024,7 @@ var ScorerBuilder = class {
34666
36024
  constructor(project) {
34667
36025
  this.project = project;
34668
36026
  }
36027
+ project;
34669
36028
  taskCounter = 0;
34670
36029
  create(opts) {
34671
36030
  this.taskCounter++;
@@ -34725,6 +36084,7 @@ var ClassifierBuilder = class {
34725
36084
  constructor(project) {
34726
36085
  this.project = project;
34727
36086
  }
36087
+ project;
34728
36088
  taskCounter = 0;
34729
36089
  create(opts) {
34730
36090
  this.taskCounter++;
@@ -34760,6 +36120,7 @@ var CodeFunction = class {
34760
36120
  throw new Error("parameters are required if return type is defined");
34761
36121
  }
34762
36122
  }
36123
+ project;
34763
36124
  handler;
34764
36125
  name;
34765
36126
  slug;
@@ -34847,6 +36208,7 @@ var PromptBuilder = class {
34847
36208
  constructor(project) {
34848
36209
  this.project = project;
34849
36210
  }
36211
+ project;
34850
36212
  create(opts) {
34851
36213
  const toolFunctions = [];
34852
36214
  const rawTools = [];
@@ -34923,6 +36285,7 @@ var ParametersBuilder = class {
34923
36285
  constructor(project) {
34924
36286
  this.project = project;
34925
36287
  }
36288
+ project;
34926
36289
  create(opts) {
34927
36290
  const slug = opts.slug ?? slugify(opts.name, { lower: true, strict: true });
34928
36291
  const codeParameters = new CodeParameters(this.project, {