braintrust 3.24.0 → 3.26.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 (80) hide show
  1. package/NOTICE +6 -0
  2. package/dev/dist/index.d.mts +135 -2
  3. package/dev/dist/index.d.ts +135 -2
  4. package/dev/dist/index.js +4426 -2040
  5. package/dev/dist/index.mjs +3594 -1208
  6. package/dist/apply-auto-instrumentation.js +445 -403
  7. package/dist/apply-auto-instrumentation.mjs +249 -207
  8. package/dist/auto-instrumentations/bundler/esbuild.cjs +1449 -799
  9. package/dist/auto-instrumentations/bundler/esbuild.d.mts +4 -4
  10. package/dist/auto-instrumentations/bundler/esbuild.d.ts +4 -4
  11. package/dist/auto-instrumentations/bundler/esbuild.mjs +5 -8
  12. package/dist/auto-instrumentations/bundler/next.cjs +1448 -818
  13. package/dist/auto-instrumentations/bundler/next.mjs +6 -29
  14. package/dist/auto-instrumentations/bundler/rollup.cjs +1449 -799
  15. package/dist/auto-instrumentations/bundler/rollup.d.mts +4 -4
  16. package/dist/auto-instrumentations/bundler/rollup.d.ts +4 -4
  17. package/dist/auto-instrumentations/bundler/rollup.mjs +5 -8
  18. package/dist/auto-instrumentations/bundler/vite.cjs +1449 -799
  19. package/dist/auto-instrumentations/bundler/vite.d.mts +4 -4
  20. package/dist/auto-instrumentations/bundler/vite.d.ts +4 -4
  21. package/dist/auto-instrumentations/bundler/vite.mjs +5 -8
  22. package/dist/auto-instrumentations/bundler/webpack-loader.cjs +1602 -728
  23. package/dist/auto-instrumentations/bundler/webpack-loader.d.ts +20 -12
  24. package/dist/auto-instrumentations/bundler/webpack.cjs +1449 -799
  25. package/dist/auto-instrumentations/bundler/webpack.d.mts +4 -4
  26. package/dist/auto-instrumentations/bundler/webpack.d.ts +4 -4
  27. package/dist/auto-instrumentations/bundler/webpack.mjs +5 -4
  28. package/dist/auto-instrumentations/{chunk-GSZHTAQW.mjs → chunk-6E22MYSW.mjs} +194 -93
  29. package/dist/auto-instrumentations/{chunk-VT6DDNKM.mjs → chunk-AKKPLXTP.mjs} +631 -194
  30. package/dist/auto-instrumentations/chunk-NRE4QUQR.mjs +509 -0
  31. package/dist/auto-instrumentations/{chunk-BURMPO7L.mjs → chunk-V5LEODRX.mjs} +2 -6
  32. package/dist/auto-instrumentations/{chunk-M6DLIJ2Z.mjs → chunk-XYN63IG5.mjs} +124 -194
  33. package/dist/auto-instrumentations/{chunk-F43DNLPD.mjs → chunk-XZHHE4Y3.mjs} +646 -510
  34. package/dist/auto-instrumentations/hook.mjs +894 -657
  35. package/dist/auto-instrumentations/index.cjs +1125 -490
  36. package/dist/auto-instrumentations/index.d.mts +6 -2
  37. package/dist/auto-instrumentations/index.d.ts +6 -2
  38. package/dist/auto-instrumentations/index.mjs +6 -1
  39. package/dist/auto-instrumentations/loader/cjs-patch.cjs +492 -195
  40. package/dist/auto-instrumentations/loader/cjs-patch.d.mts +2 -2
  41. package/dist/auto-instrumentations/loader/cjs-patch.d.ts +2 -2
  42. package/dist/auto-instrumentations/loader/cjs-patch.mjs +3 -2
  43. package/dist/auto-instrumentations/loader/esm-hook.mjs +1 -1
  44. package/dist/auto-instrumentations/plugin-B-aZh7EP.d.ts +30 -0
  45. package/dist/auto-instrumentations/plugin-Bnj4E_6B.d.mts +30 -0
  46. package/dist/auto-instrumentations/{types-RNPaKi9o.d.mts → types-C1fVeiCp.d.mts} +1 -1
  47. package/dist/auto-instrumentations/{types-RNPaKi9o.d.ts → types-C1fVeiCp.d.ts} +1 -1
  48. package/dist/browser.d.mts +824 -197
  49. package/dist/browser.d.ts +824 -197
  50. package/dist/browser.js +3897 -1228
  51. package/dist/browser.mjs +3897 -1228
  52. package/dist/chunk-PN7EWK66.mjs +1784 -0
  53. package/dist/{chunk-SU6EHKJV.js → chunk-VRZZQPAA.js} +3289 -1577
  54. package/dist/chunk-VYNNEKSA.js +1784 -0
  55. package/dist/{chunk-XE5FS7QY.mjs → chunk-XIZOM2HO.mjs} +2470 -758
  56. package/dist/cli.js +3596 -1211
  57. package/dist/edge-light.d.mts +1 -1
  58. package/dist/edge-light.d.ts +1 -1
  59. package/dist/edge-light.js +3897 -1231
  60. package/dist/edge-light.mjs +3897 -1231
  61. package/dist/index.d.mts +824 -197
  62. package/dist/index.d.ts +824 -197
  63. package/dist/index.js +750 -445
  64. package/dist/index.mjs +334 -29
  65. package/dist/instrumentation/index.d.mts +135 -6
  66. package/dist/instrumentation/index.d.ts +135 -6
  67. package/dist/instrumentation/index.js +3696 -1257
  68. package/dist/instrumentation/index.mjs +3696 -1257
  69. package/dist/vitest-evals-reporter.js +16 -16
  70. package/dist/vitest-evals-reporter.mjs +2 -2
  71. package/dist/workerd.d.mts +1 -1
  72. package/dist/workerd.d.ts +1 -1
  73. package/dist/workerd.js +3897 -1231
  74. package/dist/workerd.mjs +3897 -1231
  75. package/licenses/node-diagnostics-channel/LICENSE +19 -0
  76. package/package.json +34 -35
  77. package/dist/auto-instrumentations/plugin-D0KHwSJv.d.mts +0 -44
  78. package/dist/auto-instrumentations/plugin-G6fgxk1b.d.ts +0 -44
  79. package/dist/chunk-7AUY2XWX.js +0 -1090
  80. package/dist/chunk-7F6GCRHH.mjs +0 -1090
@@ -1,38 +1,50 @@
1
1
  import {
2
+ GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION,
3
+ INSTRUMENTATION_NAMES,
2
4
  aiSDKChannels,
3
5
  anthropicChannels,
4
6
  bedrockRuntimeChannels,
5
7
  claudeAgentSDKChannels,
8
+ cloudflareAIChatChannels,
9
+ cloudflareAgentsChannels,
6
10
  cohereChannels,
7
11
  cursorSDKChannels,
12
+ detectSpanOriginEnvironment,
8
13
  flueChannels,
9
14
  genkitChannels,
10
15
  genkitCoreChannels,
11
16
  getDefaultInstrumentationIntegrations,
17
+ getHuggingFaceTransformersPipelineInfo,
18
+ getSpanInstrumentationName,
12
19
  gitHubCopilotChannels,
13
20
  googleADKChannels,
14
21
  googleGenAIChannels,
15
22
  groqChannels,
16
23
  harnessAgentChannels,
17
24
  huggingFaceChannels,
25
+ huggingFaceTransformersChannels,
18
26
  installMastraExporterFactory,
19
27
  isInstrumentationIntegrationDisabled,
28
+ isSupportedHuggingFaceTransformersTask,
20
29
  isomorph_default,
21
30
  langChainChannels,
22
31
  langSmithChannels,
32
+ mergeSpanOriginContext,
23
33
  mistralChannels,
24
34
  openAIAgentsCoreChannels,
25
35
  openAIChannels,
26
36
  openAICodexChannels,
27
37
  openRouterAgentChannels,
28
38
  openRouterChannels,
29
- patchTracingChannel,
30
39
  piCodingAgentChannels,
31
40
  readDisabledInstrumentationEnvConfig,
41
+ registerHuggingFaceTransformersPipeline,
42
+ setGlobalHookErrorReporter,
32
43
  smithyClientChannels,
33
44
  smithyCoreChannels,
34
- strandsAgentSDKChannels
35
- } from "./chunk-7F6GCRHH.mjs";
45
+ strandsAgentSDKChannels,
46
+ withSpanInstrumentationName
47
+ } from "./chunk-PN7EWK66.mjs";
36
48
 
37
49
  // src/id-gen.ts
38
50
  import { v4 as uuidv4 } from "uuid";
@@ -145,6 +157,9 @@ var debugLogger = {
145
157
  return createDebugLogger(state);
146
158
  }
147
159
  };
160
+ setGlobalHookErrorReporter((error) => {
161
+ debugLogger.error("Global instrumentation hook error:", error);
162
+ });
148
163
 
149
164
  // src/id-gen.ts
150
165
  var IDGenerator = class {
@@ -1872,7 +1887,8 @@ var ApiKey = z6.object({
1872
1887
  user_email: z6.union([z6.string(), z6.null()]).optional(),
1873
1888
  user_given_name: z6.union([z6.string(), z6.null()]).optional(),
1874
1889
  user_family_name: z6.union([z6.string(), z6.null()]).optional(),
1875
- org_id: z6.union([z6.string(), z6.null()]).optional()
1890
+ org_id: z6.union([z6.string(), z6.null()]).optional(),
1891
+ expires_at: z6.union([z6.string(), z6.null()]).optional()
1876
1892
  });
1877
1893
  var TriggeredFunctionState = z6.object({
1878
1894
  triggered_xact_id: z6.string(),
@@ -1992,6 +2008,7 @@ var TopicMapData = z6.object({
1992
2008
  topic_names: z6.record(z6.string()).optional(),
1993
2009
  generation_settings: TopicMapGenerationSettings.optional(),
1994
2010
  disable_reconciliation: z6.boolean().optional(),
2011
+ reconcile_mode: z6.enum(["evolve", "names_only"]).optional(),
1995
2012
  distance_threshold: z6.number().optional(),
1996
2013
  btql_filter: z6.string().optional(),
1997
2014
  automation_btql_filter: z6.string().optional()
@@ -2572,7 +2589,12 @@ var ModelParams = z6.union([
2572
2589
  }).partial().passthrough()
2573
2590
  ]);
2574
2591
  var PromptOptionsNullish = z6.union([
2575
- z6.object({ model: z6.string(), params: ModelParams, position: z6.string() }).partial(),
2592
+ z6.object({
2593
+ model: z6.string(),
2594
+ params: ModelParams,
2595
+ position: z6.string(),
2596
+ endpoint_name: z6.union([z6.string(), z6.null()])
2597
+ }).partial(),
2576
2598
  z6.null()
2577
2599
  ]);
2578
2600
  var PromptParserNullish = z6.union([
@@ -2586,11 +2608,25 @@ var PromptParserNullish = z6.union([
2586
2608
  }),
2587
2609
  z6.null()
2588
2610
  ]);
2611
+ var PreprocessorSavedFunctionId = z6.union([
2612
+ z6.object({
2613
+ type: z6.literal("function"),
2614
+ id: z6.string(),
2615
+ version: z6.string().optional()
2616
+ }),
2617
+ z6.object({
2618
+ type: z6.literal("global"),
2619
+ name: z6.string(),
2620
+ function_type: z6.literal("preprocessor").optional().default("preprocessor")
2621
+ }),
2622
+ z6.null()
2623
+ ]);
2589
2624
  var PromptDataNullish = z6.union([
2590
2625
  z6.object({
2591
2626
  prompt: PromptBlockDataNullish,
2592
2627
  options: PromptOptionsNullish,
2593
2628
  parser: PromptParserNullish,
2629
+ preprocessor: PreprocessorSavedFunctionId,
2594
2630
  tool_functions: z6.union([z6.array(SavedFunctionId), z6.null()]),
2595
2631
  template_format: z6.union([
2596
2632
  z6.enum(["mustache", "nunjucks", "none"]),
@@ -2792,6 +2828,7 @@ var PromptData = z6.object({
2792
2828
  prompt: PromptBlockDataNullish,
2793
2829
  options: PromptOptionsNullish,
2794
2830
  parser: PromptParserNullish,
2831
+ preprocessor: PreprocessorSavedFunctionId,
2795
2832
  tool_functions: z6.union([z6.array(SavedFunctionId), z6.null()]),
2796
2833
  template_format: z6.union([
2797
2834
  z6.enum(["mustache", "nunjucks", "none"]),
@@ -2954,7 +2991,8 @@ var InvokeFunction = FunctionId.and(
2954
2991
  mode: StreamingMode,
2955
2992
  strict: z6.union([z6.boolean(), z6.null()]),
2956
2993
  mcp_auth: z6.record(z6.object({ oauth_token: z6.string() }).partial()),
2957
- overrides: z6.union([z6.object({}).partial().passthrough(), z6.null()])
2994
+ overrides: z6.union([z6.object({}).partial().passthrough(), z6.null()]),
2995
+ endpoint_name: z6.union([z6.string(), z6.null()])
2958
2996
  }).partial()
2959
2997
  );
2960
2998
  var MCPServer = z6.object({
@@ -3018,6 +3056,24 @@ var Organization = z6.object({
3018
3056
  created: z6.union([z6.string(), z6.null()]).optional(),
3019
3057
  image_rendering_mode: ImageRenderingMode.optional()
3020
3058
  });
3059
+ var RetentionObjectType = z6.enum([
3060
+ "project_logs",
3061
+ "experiment",
3062
+ "dataset"
3063
+ ]);
3064
+ var OrgAutomation = z6.object({
3065
+ id: z6.string().uuid(),
3066
+ org_id: z6.string().uuid(),
3067
+ user_id: z6.union([z6.string(), z6.null()]).optional(),
3068
+ created: z6.union([z6.string(), z6.null()]).optional(),
3069
+ name: z6.string(),
3070
+ description: z6.union([z6.string(), z6.null()]).optional(),
3071
+ config: z6.object({
3072
+ event_type: z6.literal("retention"),
3073
+ object_type: RetentionObjectType,
3074
+ retention_days: z6.number().int().gte(0)
3075
+ })
3076
+ });
3021
3077
  var ProjectSettings = z6.union([
3022
3078
  z6.object({
3023
3079
  comparison_key: z6.union([z6.string(), z6.null()]),
@@ -3044,6 +3100,7 @@ var ProjectSettings = z6.union([
3044
3100
  z6.null()
3045
3101
  ]),
3046
3102
  disable_realtime_queries: z6.union([z6.boolean(), z6.null()]),
3103
+ monitor_charts_use_metrics_start: z6.union([z6.boolean(), z6.null()]),
3047
3104
  default_preprocessor: NullableSavedFunctionId
3048
3105
  }).partial(),
3049
3106
  z6.null()
@@ -3058,11 +3115,6 @@ var Project = z6.object({
3058
3115
  user_id: z6.union([z6.string(), z6.null()]).optional(),
3059
3116
  settings: ProjectSettings.optional()
3060
3117
  });
3061
- var RetentionObjectType = z6.enum([
3062
- "project_logs",
3063
- "experiment",
3064
- "dataset"
3065
- ]);
3066
3118
  var TopicAutomationFacetModel = z6.union([
3067
3119
  z6.enum(["brain-facet-latest", "brain-facet-1", "brain-facet-2"]),
3068
3120
  z6.null()
@@ -3173,7 +3225,7 @@ var ProjectAutomation = z6.object({
3173
3225
  z6.object({
3174
3226
  event_type: z6.literal("retention"),
3175
3227
  object_type: RetentionObjectType,
3176
- retention_days: z6.number().gte(0)
3228
+ retention_days: z6.number().int().gte(0)
3177
3229
  }),
3178
3230
  z6.object({
3179
3231
  event_type: z6.literal("environment_update"),
@@ -3345,7 +3397,12 @@ var Prompt = z6.object({
3345
3397
  metadata: z6.union([z6.object({}).partial().passthrough(), z6.null()]).optional(),
3346
3398
  function_type: FunctionTypeEnumNullish.optional()
3347
3399
  });
3348
- var PromptOptions = z6.object({ model: z6.string(), params: ModelParams, position: z6.string() }).partial();
3400
+ var PromptOptions = z6.object({
3401
+ model: z6.string(),
3402
+ params: ModelParams,
3403
+ position: z6.string(),
3404
+ endpoint_name: z6.union([z6.string(), z6.null()])
3405
+ }).partial();
3349
3406
  var PromptSessionEvent = z6.object({
3350
3407
  id: z6.string(),
3351
3408
  _xact_id: z6.string(),
@@ -3428,7 +3485,8 @@ var RunEval = z6.object({
3428
3485
  stop_token: z6.union([z6.string(), z6.null()]).optional(),
3429
3486
  extra_messages: z6.string().optional(),
3430
3487
  tags: z6.array(z6.string()).optional(),
3431
- mcp_auth: z6.record(z6.object({ oauth_token: z6.string() }).partial()).optional()
3488
+ mcp_auth: z6.record(z6.object({ oauth_token: z6.string() }).partial()).optional(),
3489
+ endpoint_name: z6.union([z6.string(), z6.null()]).optional()
3432
3490
  });
3433
3491
  var ServiceToken = z6.object({
3434
3492
  id: z6.string().uuid(),
@@ -3438,7 +3496,8 @@ var ServiceToken = z6.object({
3438
3496
  service_account_id: z6.union([z6.string(), z6.null()]).optional(),
3439
3497
  service_account_email: z6.union([z6.string(), z6.null()]).optional(),
3440
3498
  service_account_name: z6.union([z6.string(), z6.null()]).optional(),
3441
- org_id: z6.union([z6.string(), z6.null()]).optional()
3499
+ org_id: z6.union([z6.string(), z6.null()]).optional(),
3500
+ expires_at: z6.union([z6.string(), z6.null()]).optional()
3442
3501
  });
3443
3502
  var SpanIFrame = z6.object({
3444
3503
  id: z6.string().uuid(),
@@ -3560,6 +3619,13 @@ var ViewOptions = z6.union([
3560
3619
  }),
3561
3620
  z6.null()
3562
3621
  ]),
3622
+ pointSizeMetric: z6.union([
3623
+ z6.object({
3624
+ type: z6.enum(["none", "score", "metric", "metadata"]),
3625
+ value: z6.string()
3626
+ }),
3627
+ z6.null()
3628
+ ]),
3563
3629
  xAxisAggregation: z6.union([z6.string(), z6.null()]),
3564
3630
  chartAnnotations: z6.union([
3565
3631
  z6.array(z6.object({ id: z6.string(), text: z6.string() })),
@@ -4753,97 +4819,6 @@ var SpanCache = class {
4753
4819
  }
4754
4820
  };
4755
4821
 
4756
- // src/span-origin.ts
4757
- var SDK_VERSION = true ? "3.24.0" : "0.0.0";
4758
- function detectSpanOriginEnvironment(explicit) {
4759
- if (explicit) return explicit;
4760
- const envType = isomorph_default.getEnv("BRAINTRUST_ENVIRONMENT_TYPE");
4761
- const envName = isomorph_default.getEnv("BRAINTRUST_ENVIRONMENT_NAME");
4762
- if (envType || envName) {
4763
- return {
4764
- ...envType ? { type: envType } : {},
4765
- ...envName ? { name: envName } : {}
4766
- };
4767
- }
4768
- const ci = firstPresent([
4769
- ["GITHUB_ACTIONS", "github_actions"],
4770
- ["GITLAB_CI", "gitlab_ci"],
4771
- ["CIRCLECI", "circleci"],
4772
- ["BUILDKITE", "buildkite"],
4773
- ["JENKINS_URL", "jenkins"],
4774
- ["JENKINS_HOME", "jenkins"],
4775
- ["TF_BUILD", "azure_pipelines"],
4776
- ["TEAMCITY_VERSION", "teamcity"],
4777
- ["TRAVIS", "travis"],
4778
- ["BITBUCKET_BUILD_NUMBER", "bitbucket"]
4779
- ]);
4780
- if (ci) return { type: "ci", name: ci };
4781
- if (isomorph_default.getEnv("CI")) return { type: "ci", name: "ci" };
4782
- const earlyServer = firstPresent([
4783
- ["VERCEL", "vercel"],
4784
- ["NETLIFY", "netlify"]
4785
- ]);
4786
- if (earlyServer) return { type: "server", name: earlyServer };
4787
- if (isomorph_default.getEnv("ECS_CONTAINER_METADATA_URI") || isomorph_default.getEnv("ECS_CONTAINER_METADATA_URI_V4")) {
4788
- return { type: "server", name: "ecs" };
4789
- }
4790
- const awsExecutionEnv = isomorph_default.getEnv("AWS_EXECUTION_ENV");
4791
- if (awsExecutionEnv?.startsWith("AWS_ECS_")) {
4792
- return { type: "server", name: "ecs" };
4793
- }
4794
- if (awsExecutionEnv?.startsWith("AWS_Lambda_")) {
4795
- return { type: "server", name: "aws_lambda" };
4796
- }
4797
- if (isomorph_default.getEnv("AWS_LAMBDA_FUNCTION_NAME")) {
4798
- return { type: "server", name: "aws_lambda" };
4799
- }
4800
- const server = firstPresent([
4801
- ["K_SERVICE", "cloud_run"],
4802
- ["FUNCTION_TARGET", "gcp_functions"],
4803
- ["KUBERNETES_SERVICE_HOST", "kubernetes"],
4804
- ["DYNO", "heroku"],
4805
- ["FLY_APP_NAME", "fly"],
4806
- ["RAILWAY_ENVIRONMENT", "railway"],
4807
- ["RENDER_SERVICE_NAME", "render"]
4808
- ]);
4809
- if (server) return { type: "server", name: server };
4810
- return deploymentModeEnvironment("NODE_ENV", isomorph_default.getEnv("NODE_ENV"));
4811
- }
4812
- function makeSpanOrigin(instrumentationName, environment) {
4813
- return {
4814
- name: "braintrust.sdk.javascript",
4815
- version: SDK_VERSION,
4816
- instrumentation: { name: instrumentationName },
4817
- ...environment ? { environment } : {}
4818
- };
4819
- }
4820
- function mergeSpanOriginContext(context, instrumentationName, environment) {
4821
- const next = { ...context ?? {} };
4822
- const current = isObject2(next.span_origin) ? { ...next.span_origin } : {};
4823
- next.span_origin = {
4824
- ...makeSpanOrigin(instrumentationName, environment),
4825
- ...current
4826
- };
4827
- return next;
4828
- }
4829
- function firstPresent(entries) {
4830
- return entries.find(([key]) => Boolean(isomorph_default.getEnv(key)))?.[1];
4831
- }
4832
- function deploymentModeEnvironment(_key, value) {
4833
- if (!value) return void 0;
4834
- const normalized = value.toLowerCase();
4835
- if (normalized === "production" || normalized === "staging") {
4836
- return { type: "server", name: normalized };
4837
- }
4838
- if (normalized === "development" || normalized === "local") {
4839
- return { type: "local", name: normalized };
4840
- }
4841
- return { name: value };
4842
- }
4843
- function isObject2(value) {
4844
- return typeof value === "object" && value !== null && !Array.isArray(value);
4845
- }
4846
-
4847
4822
  // src/logger.ts
4848
4823
  var BRAINTRUST_ATTACHMENT = BraintrustAttachmentReference.shape.type.value;
4849
4824
  var EXTERNAL_ATTACHMENT = ExternalAttachmentReference.shape.type.value;
@@ -4933,12 +4908,13 @@ function applyMaskingToField(maskingFunction, data, fieldName) {
4933
4908
  var INITIAL_SPAN_WRITE_AS_MERGE = /* @__PURE__ */ Symbol(
4934
4909
  "braintrust.initial-span-write-as-merge"
4935
4910
  );
4911
+ var INTERNAL_SPAN_CONTEXT = /* @__PURE__ */ Symbol("braintrust.internal-span-context");
4936
4912
  var BRAINTRUST_CURRENT_SPAN_STORE = /* @__PURE__ */ Symbol.for(
4937
4913
  "braintrust.currentSpanStore"
4938
4914
  );
4939
4915
  var ContextManager = class {
4940
4916
  /**
4941
- * Returns the value to store in the ALS bound to a TracingChannel's start event.
4917
+ * Returns the value to store in the ALS bound to a global hook's start event.
4942
4918
  * In default mode this is the Span itself; in OTEL mode it is the OTEL Context
4943
4919
  * containing the span so that OTEL's own ALS stores a proper Context object.
4944
4920
  */
@@ -5120,6 +5096,7 @@ var BraintrustState = class _BraintrustState {
5120
5096
  });
5121
5097
  this.spanCache = new SpanCache({ disabled: loginParams.disableSpanCache });
5122
5098
  this.spanOriginEnvironment = detectSpanOriginEnvironment();
5099
+ this._internalSetTraceContextSigningSecret(loginParams.apiKey);
5123
5100
  }
5124
5101
  loginParams;
5125
5102
  id;
@@ -5157,6 +5134,18 @@ var BraintrustState = class _BraintrustState {
5157
5134
  _contextManager = null;
5158
5135
  _otelFlushCallback = null;
5159
5136
  spanOriginEnvironment;
5137
+ traceContextSigningSecret;
5138
+ /** @internal */
5139
+ _internalSetTraceContextSigningSecret(secret) {
5140
+ const normalizedSecret = secret?.trim();
5141
+ if (normalizedSecret) {
5142
+ this.traceContextSigningSecret = normalizedSecret;
5143
+ }
5144
+ }
5145
+ /** @internal */
5146
+ _internalGetTraceContextSigningSecret() {
5147
+ return (this.traceContextSigningSecret ?? this.loginToken ?? isomorph_default.getEnv("BRAINTRUST_API_KEY"))?.trim();
5148
+ }
5160
5149
  resetLoginInfo() {
5161
5150
  this.appUrl = null;
5162
5151
  this.appPublicUrl = null;
@@ -5217,6 +5206,7 @@ var BraintrustState = class _BraintrustState {
5217
5206
  this.gitMetadataSettings = other.gitMetadataSettings;
5218
5207
  this.debugLogLevel = other.debugLogLevel;
5219
5208
  this.debugLogLevelConfigured = other.debugLogLevelConfigured;
5209
+ this.traceContextSigningSecret = other.traceContextSigningSecret;
5220
5210
  setGlobalDebugLogLevel(
5221
5211
  this.debugLogLevelConfigured ? this.debugLogLevel ?? false : void 0
5222
5212
  );
@@ -5304,6 +5294,7 @@ var BraintrustState = class _BraintrustState {
5304
5294
  return this.debugLogLevelConfigured;
5305
5295
  }
5306
5296
  async login(loginParams) {
5297
+ this._internalSetTraceContextSigningSecret(loginParams.apiKey);
5307
5298
  this.setDebugLogLevel(loginParams.debugLogLevel);
5308
5299
  if (this.apiUrl && !loginParams.forceLogin) {
5309
5300
  return;
@@ -7283,6 +7274,7 @@ function init(projectOrOptions, optionalOptions) {
7283
7274
  throw new Error("Cannot open and update an experiment at the same time");
7284
7275
  }
7285
7276
  const state = stateArg ?? _globalState;
7277
+ state._internalSetTraceContextSigningSecret(apiKey);
7286
7278
  state.enforceQueueSizeLimit(false);
7287
7279
  if (open2) {
7288
7280
  if (isEmpty2(experiment)) {
@@ -7791,6 +7783,7 @@ function initLogger(options = {}) {
7791
7783
  project_id: projectId
7792
7784
  };
7793
7785
  const state = stateArg ?? _globalState;
7786
+ state._internalSetTraceContextSigningSecret(apiKey);
7794
7787
  state.setDebugLogLevel(debugLogLevel);
7795
7788
  state.spanOriginEnvironment = detectSpanOriginEnvironment(environment);
7796
7789
  state.enforceQueueSizeLimit(true);
@@ -8654,6 +8647,12 @@ function _internalStartSpanWithInitialMerge(args) {
8654
8647
  [INITIAL_SPAN_WRITE_AS_MERGE]: true
8655
8648
  }).span;
8656
8649
  }
8650
+ function _internalStartSpanWithContext(args, context) {
8651
+ return startSpanAndIsLogger({
8652
+ ...args,
8653
+ [INTERNAL_SPAN_CONTEXT]: context
8654
+ }).span;
8655
+ }
8657
8656
  async function flush(options) {
8658
8657
  const state = options?.state ?? _globalState;
8659
8658
  return await state.bgLogger().flush();
@@ -8854,7 +8853,9 @@ function deepCopyEvent(event) {
8854
8853
  const ATTACHMENT_MARKER_KEY = "_bt_internal_saved_attachment_marker";
8855
8854
  const attachmentMarker = ++deepCopyEventMarkerCounter;
8856
8855
  const serialized = JSON.stringify(event, (_k, v) => {
8857
- if (v instanceof SpanImpl || v instanceof NoopSpan) {
8856
+ if (v instanceof Error) {
8857
+ return v.message;
8858
+ } else if (v instanceof SpanImpl || v instanceof NoopSpan) {
8858
8859
  return `<span>`;
8859
8860
  } else if (v instanceof Experiment2) {
8860
8861
  return `<experiment>`;
@@ -9522,6 +9523,7 @@ var SpanImpl = class _SpanImpl {
9522
9523
  constructor(args) {
9523
9524
  this._state = args.state;
9524
9525
  this._propagatedState = args.propagatedState;
9526
+ const instrumentationName = getSpanInstrumentationName(args) ?? INSTRUMENTATION_NAMES.BRAINTRUST_JS_LOGGER;
9525
9527
  const spanAttributes = args.spanAttributes ?? {};
9526
9528
  const rawEvent = args.event ?? {};
9527
9529
  const type = args.type ?? (args.parentSpanIds ? void 0 : args.defaultRootType);
@@ -9552,8 +9554,8 @@ var SpanImpl = class _SpanImpl {
9552
9554
  start: args.startTime ?? getCurrentUnixTimestamp()
9553
9555
  },
9554
9556
  context: mergeSpanOriginContext(
9555
- { ...callerLocation },
9556
- "braintrust-js-logger",
9557
+ { ...callerLocation, ...args[INTERNAL_SPAN_CONTEXT] },
9558
+ instrumentationName,
9557
9559
  this._state.spanOriginEnvironment
9558
9560
  ),
9559
9561
  span_attributes: {
@@ -11547,8 +11549,8 @@ function runWithAutoInstrumentationSuppressed(callback) {
11547
11549
  callback
11548
11550
  );
11549
11551
  }
11550
- function bindAutoInstrumentationSuppressionToStart(tracingChannel2) {
11551
- const startChannel = tracingChannel2.start;
11552
+ function bindAutoInstrumentationSuppressionToStart(tracingChannel) {
11553
+ const startChannel = tracingChannel.start;
11552
11554
  if (!startChannel) {
11553
11555
  return void 0;
11554
11556
  }
@@ -11592,15 +11594,25 @@ function hasChoices(value) {
11592
11594
  function normalizeMetadata(metadata) {
11593
11595
  return isObject(metadata) ? metadata : void 0;
11594
11596
  }
11595
- function startSpanForEvent(config, event, channelName) {
11597
+ function startSpanForEvent(config, event, channelName, instrumentationName) {
11596
11598
  const { name, spanAttributes, spanInfoMetadata } = buildStartSpanArgs(
11597
11599
  config,
11598
11600
  event
11599
11601
  );
11600
- const span = startSpan({
11601
- name,
11602
- spanAttributes
11603
- });
11602
+ const spanArgs = withSpanInstrumentationName(
11603
+ {
11604
+ name,
11605
+ spanAttributes
11606
+ },
11607
+ instrumentationName
11608
+ );
11609
+ let span;
11610
+ try {
11611
+ span = config.startSpan?.(spanArgs) ?? startSpan(spanArgs);
11612
+ } catch (error) {
11613
+ debugLogger.error(`Error starting span for ${channelName}:`, error);
11614
+ span = startSpan(spanArgs);
11615
+ }
11604
11616
  const startTime = getCurrentUnixTimestamp();
11605
11617
  try {
11606
11618
  const { input, metadata } = config.extractInput(
@@ -11631,7 +11643,7 @@ function shouldTraceEvent(config, event, channelName) {
11631
11643
  return true;
11632
11644
  }
11633
11645
  }
11634
- function ensureSpanStateForEvent(states, config, event, channelName) {
11646
+ function ensureSpanStateForEvent(states, config, event, channelName, instrumentationName) {
11635
11647
  const key = event;
11636
11648
  const existing = states.get(key);
11637
11649
  if (existing) {
@@ -11640,13 +11652,18 @@ function ensureSpanStateForEvent(states, config, event, channelName) {
11640
11652
  if (!shouldTraceEvent(config, event, channelName)) {
11641
11653
  return void 0;
11642
11654
  }
11643
- const created = startSpanForEvent(config, event, channelName);
11655
+ const created = startSpanForEvent(
11656
+ config,
11657
+ event,
11658
+ channelName,
11659
+ instrumentationName
11660
+ );
11644
11661
  states.set(key, created);
11645
11662
  return created;
11646
11663
  }
11647
- function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelName) {
11664
+ function bindCurrentSpanStoreToStart(tracingChannel, states, config, channelName, instrumentationName) {
11648
11665
  const state = _internalGetGlobalState();
11649
- const startChannel = tracingChannel2.start;
11666
+ const startChannel = tracingChannel.start;
11650
11667
  const contextManager = state?.contextManager;
11651
11668
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
11652
11669
  if (!currentSpanStore || !startChannel) {
@@ -11662,7 +11679,8 @@ function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelNam
11662
11679
  states,
11663
11680
  config,
11664
11681
  event,
11665
- channelName
11682
+ channelName,
11683
+ instrumentationName
11666
11684
  );
11667
11685
  return spanState ? contextManager.wrapSpanForStore(spanState.span) : currentSpanStore.getStore();
11668
11686
  }
@@ -11671,15 +11689,21 @@ function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelNam
11671
11689
  startChannel.unbindStore(currentSpanStore);
11672
11690
  };
11673
11691
  }
11674
- function logErrorAndEnd(states, event) {
11692
+ function logErrorAndEnd(states, event, channelName) {
11675
11693
  const spanData = states.get(event);
11676
11694
  if (!spanData) {
11677
11695
  return;
11678
11696
  }
11679
- spanData.span.log({
11680
- error: event.error.message
11681
- });
11682
- spanData.span.end();
11697
+ try {
11698
+ spanData.span.log({ error: event.error });
11699
+ } catch (error) {
11700
+ debugLogger.error(`Error logging failure for ${channelName}:`, error);
11701
+ }
11702
+ try {
11703
+ spanData.span.end();
11704
+ } catch (error) {
11705
+ debugLogger.error(`Error ending span for ${channelName}:`, error);
11706
+ }
11683
11707
  states.delete(event);
11684
11708
  }
11685
11709
  function runStreamingCompletionHook(args) {
@@ -11722,14 +11746,15 @@ function runStreamingErrorHook(args) {
11722
11746
  }
11723
11747
  }
11724
11748
  function traceAsyncChannel(channel, config) {
11725
- const tracingChannel2 = channel.tracingChannel();
11749
+ const tracingChannel = channel.tracingChannel();
11726
11750
  const states = /* @__PURE__ */ new WeakMap();
11727
11751
  const channelName = channel.channelName;
11728
11752
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart(
11729
- tracingChannel2,
11753
+ tracingChannel,
11730
11754
  states,
11731
11755
  config,
11732
- channelName
11756
+ channelName,
11757
+ channel.instrumentationName
11733
11758
  );
11734
11759
  const handlers = {
11735
11760
  start: (event) => {
@@ -11740,7 +11765,8 @@ function traceAsyncChannel(channel, config) {
11740
11765
  states,
11741
11766
  config,
11742
11767
  event,
11743
- channelName
11768
+ channelName,
11769
+ channel.instrumentationName
11744
11770
  );
11745
11771
  },
11746
11772
  asyncEnd: (event) => {
@@ -11777,24 +11803,25 @@ function traceAsyncChannel(channel, config) {
11777
11803
  }
11778
11804
  },
11779
11805
  error: (event) => {
11780
- logErrorAndEnd(states, event);
11806
+ logErrorAndEnd(states, event, channelName);
11781
11807
  }
11782
11808
  };
11783
- tracingChannel2.subscribe(handlers);
11809
+ tracingChannel.subscribe(handlers);
11784
11810
  return () => {
11785
11811
  unbindCurrentSpanStore?.();
11786
- tracingChannel2.unsubscribe(handlers);
11812
+ tracingChannel.unsubscribe(handlers);
11787
11813
  };
11788
11814
  }
11789
11815
  function traceStreamingChannel(channel, config) {
11790
- const tracingChannel2 = channel.tracingChannel();
11816
+ const tracingChannel = channel.tracingChannel();
11791
11817
  const states = /* @__PURE__ */ new WeakMap();
11792
11818
  const channelName = channel.channelName;
11793
11819
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart(
11794
- tracingChannel2,
11820
+ tracingChannel,
11795
11821
  states,
11796
11822
  config,
11797
- channelName
11823
+ channelName,
11824
+ channel.instrumentationName
11798
11825
  );
11799
11826
  const handlers = {
11800
11827
  start: (event) => {
@@ -11805,7 +11832,8 @@ function traceStreamingChannel(channel, config) {
11805
11832
  states,
11806
11833
  config,
11807
11834
  event,
11808
- channelName
11835
+ channelName,
11836
+ channel.instrumentationName
11809
11837
  );
11810
11838
  },
11811
11839
  asyncEnd: (event) => {
@@ -11824,6 +11852,7 @@ function traceStreamingChannel(channel, config) {
11824
11852
  }
11825
11853
  },
11826
11854
  onComplete: (chunks) => {
11855
+ let completion2;
11827
11856
  try {
11828
11857
  let output;
11829
11858
  let metrics;
@@ -11854,18 +11883,11 @@ function traceStreamingChannel(channel, config) {
11854
11883
  } else if (metrics.time_to_first_token === void 0 && chunks.length > 0) {
11855
11884
  metrics.time_to_first_token = getCurrentUnixTimestamp() - startTime;
11856
11885
  }
11857
- runStreamingCompletionHook({
11858
- channelName,
11859
- chunks,
11860
- config,
11861
- endEvent: asyncEndEvent,
11886
+ completion2 = {
11862
11887
  ...metadata !== void 0 ? { metadata } : {},
11863
11888
  metrics,
11864
- output,
11865
- result: asyncEndEvent.result,
11866
- span,
11867
- startTime
11868
- });
11889
+ output
11890
+ };
11869
11891
  span.log({
11870
11892
  output,
11871
11893
  ...metadata !== void 0 ? { metadata } : {},
@@ -11877,11 +11899,49 @@ function traceStreamingChannel(channel, config) {
11877
11899
  error
11878
11900
  );
11879
11901
  } finally {
11880
- span.end();
11902
+ try {
11903
+ span.end();
11904
+ } catch (error) {
11905
+ debugLogger.error(
11906
+ `Error ending span for ${channelName}:`,
11907
+ error
11908
+ );
11909
+ }
11881
11910
  states.delete(event);
11882
11911
  }
11912
+ if (completion2) {
11913
+ runStreamingCompletionHook({
11914
+ channelName,
11915
+ chunks,
11916
+ config,
11917
+ endEvent: asyncEndEvent,
11918
+ ...completion2.metadata !== void 0 ? { metadata: completion2.metadata } : {},
11919
+ metrics: completion2.metrics,
11920
+ output: completion2.output,
11921
+ result: asyncEndEvent.result,
11922
+ span,
11923
+ startTime
11924
+ });
11925
+ }
11883
11926
  },
11884
11927
  onError: (error) => {
11928
+ try {
11929
+ span.log({ error });
11930
+ } catch (loggingError) {
11931
+ debugLogger.error(
11932
+ `Error logging failure for ${channelName}:`,
11933
+ loggingError
11934
+ );
11935
+ }
11936
+ try {
11937
+ span.end();
11938
+ } catch (endingError) {
11939
+ debugLogger.error(
11940
+ `Error ending span for ${channelName}:`,
11941
+ endingError
11942
+ );
11943
+ }
11944
+ states.delete(event);
11885
11945
  runStreamingErrorHook({
11886
11946
  channelName,
11887
11947
  config,
@@ -11890,11 +11950,6 @@ function traceStreamingChannel(channel, config) {
11890
11950
  span,
11891
11951
  startTime
11892
11952
  });
11893
- span.log({
11894
- error: error.message
11895
- });
11896
- span.end();
11897
- states.delete(event);
11898
11953
  }
11899
11954
  });
11900
11955
  return;
@@ -11909,6 +11964,7 @@ function traceStreamingChannel(channel, config) {
11909
11964
  states.delete(event);
11910
11965
  return;
11911
11966
  }
11967
+ let completion;
11912
11968
  try {
11913
11969
  const output = config.extractOutput(
11914
11970
  asyncEndEvent.result,
@@ -11923,17 +11979,11 @@ function traceStreamingChannel(channel, config) {
11923
11979
  asyncEndEvent.result,
11924
11980
  asyncEndEvent
11925
11981
  );
11926
- runStreamingCompletionHook({
11927
- channelName,
11928
- config,
11929
- endEvent: asyncEndEvent,
11982
+ completion = {
11930
11983
  ...normalizeMetadata(metadata) !== void 0 ? { metadata: normalizeMetadata(metadata) } : {},
11931
11984
  metrics,
11932
- output,
11933
- result: asyncEndEvent.result,
11934
- span,
11935
- startTime
11936
- });
11985
+ output
11986
+ };
11937
11987
  span.log({
11938
11988
  output,
11939
11989
  ...normalizeMetadata(metadata) !== void 0 ? { metadata: normalizeMetadata(metadata) } : {},
@@ -11942,12 +11992,30 @@ function traceStreamingChannel(channel, config) {
11942
11992
  } catch (error) {
11943
11993
  debugLogger.error(`Error extracting output for ${channelName}:`, error);
11944
11994
  } finally {
11945
- span.end();
11995
+ try {
11996
+ span.end();
11997
+ } catch (error) {
11998
+ debugLogger.error(`Error ending span for ${channelName}:`, error);
11999
+ }
11946
12000
  states.delete(event);
11947
12001
  }
12002
+ if (completion) {
12003
+ runStreamingCompletionHook({
12004
+ channelName,
12005
+ config,
12006
+ endEvent: asyncEndEvent,
12007
+ ...completion.metadata !== void 0 ? { metadata: completion.metadata } : {},
12008
+ metrics: completion.metrics,
12009
+ output: completion.output,
12010
+ result: asyncEndEvent.result,
12011
+ span,
12012
+ startTime
12013
+ });
12014
+ }
11948
12015
  },
11949
12016
  error: (event) => {
11950
12017
  const spanData = states.get(event);
12018
+ logErrorAndEnd(states, event, channelName);
11951
12019
  if (spanData) {
11952
12020
  runStreamingErrorHook({
11953
12021
  channelName,
@@ -11958,24 +12026,24 @@ function traceStreamingChannel(channel, config) {
11958
12026
  startTime: spanData.startTime
11959
12027
  });
11960
12028
  }
11961
- logErrorAndEnd(states, event);
11962
12029
  }
11963
12030
  };
11964
- tracingChannel2.subscribe(handlers);
12031
+ tracingChannel.subscribe(handlers);
11965
12032
  return () => {
11966
12033
  unbindCurrentSpanStore?.();
11967
- tracingChannel2.unsubscribe(handlers);
12034
+ tracingChannel.unsubscribe(handlers);
11968
12035
  };
11969
12036
  }
11970
12037
  function traceSyncStreamChannel(channel, config) {
11971
- const tracingChannel2 = channel.tracingChannel();
12038
+ const tracingChannel = channel.tracingChannel();
11972
12039
  const states = /* @__PURE__ */ new WeakMap();
11973
12040
  const channelName = channel.channelName;
11974
12041
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart(
11975
- tracingChannel2,
12042
+ tracingChannel,
11976
12043
  states,
11977
12044
  config,
11978
- channelName
12045
+ channelName,
12046
+ channel.instrumentationName
11979
12047
  );
11980
12048
  const handlers = {
11981
12049
  start: (event) => {
@@ -11986,7 +12054,8 @@ function traceSyncStreamChannel(channel, config) {
11986
12054
  states,
11987
12055
  config,
11988
12056
  event,
11989
- channelName
12057
+ channelName,
12058
+ channel.instrumentationName
11990
12059
  );
11991
12060
  },
11992
12061
  end: (event) => {
@@ -12080,13 +12149,13 @@ function traceSyncStreamChannel(channel, config) {
12080
12149
  handleResolvedResult(endEvent.result);
12081
12150
  },
12082
12151
  error: (event) => {
12083
- logErrorAndEnd(states, event);
12152
+ logErrorAndEnd(states, event, channelName);
12084
12153
  }
12085
12154
  };
12086
- tracingChannel2.subscribe(handlers);
12155
+ tracingChannel.subscribe(handlers);
12087
12156
  return () => {
12088
12157
  unbindCurrentSpanStore?.();
12089
- tracingChannel2.unsubscribe(handlers);
12158
+ tracingChannel.unsubscribe(handlers);
12090
12159
  };
12091
12160
  }
12092
12161
  function unsubscribeAll(unsubscribers) {
@@ -12357,75 +12426,336 @@ function serializeAISDKToolsForLogging(tools) {
12357
12426
  return serialized;
12358
12427
  }
12359
12428
 
12360
- // src/wrappers/ai-sdk/workflow-agent-context.ts
12361
- var workflowAgentWrapperSpans = /* @__PURE__ */ new Map();
12362
- function registerWorkflowAgentWrapperSpan(span) {
12363
- if (span.spanId) {
12364
- workflowAgentWrapperSpans.set(span.spanId, span);
12429
+ // src/wrappers/ai-sdk/harness-agent-context.ts
12430
+ var BRAINTRUST_TURN_CONTEXT_KEY = "__braintrust_trace_context";
12431
+ var sessionTurnParents = /* @__PURE__ */ new WeakMap();
12432
+ var wrapperTurnParents = /* @__PURE__ */ new WeakMap();
12433
+ var patchedLifecycleMethods = /* @__PURE__ */ new WeakMap();
12434
+ var harnessTurnParentStore;
12435
+ function serializedTurnContext(value) {
12436
+ if (!isObject(value)) {
12437
+ return void 0;
12438
+ }
12439
+ const context = value[BRAINTRUST_TURN_CONTEXT_KEY];
12440
+ if (!isObject(context) || typeof context.parent !== "string" || typeof context.sessionId !== "string" || typeof context.signature !== "string") {
12441
+ return void 0;
12442
+ }
12443
+ const expectedSignature = signTurnContext({
12444
+ parent: context.parent,
12445
+ sessionId: context.sessionId
12446
+ });
12447
+ if (!expectedSignature || !isomorph_default.timingSafeEqual?.(context.signature, expectedSignature)) {
12448
+ return void 0;
12449
+ }
12450
+ const parent = SpanComponentsV4.fromStr(context.parent);
12451
+ if (!parent.data.row_id || !parent.data.root_span_id || !parent.data.span_id) {
12452
+ return void 0;
12365
12453
  }
12454
+ return {
12455
+ parent: context.parent,
12456
+ sessionId: context.sessionId
12457
+ };
12366
12458
  }
12367
- function unregisterWorkflowAgentWrapperSpan(span) {
12368
- if (span.spanId) {
12369
- workflowAgentWrapperSpans.delete(span.spanId);
12459
+ function signTurnContext(context) {
12460
+ const secret = _internalGetGlobalState()._internalGetTraceContextSigningSecret();
12461
+ return secret ? isomorph_default.hmacSha256?.(
12462
+ secret,
12463
+ JSON.stringify([BRAINTRUST_TURN_CONTEXT_KEY, context])
12464
+ ) : void 0;
12465
+ }
12466
+ function continuationParentFromCreateSessionParams(params) {
12467
+ if (!isObject(params)) {
12468
+ return void 0;
12469
+ }
12470
+ const continuation = params.continueFrom ?? (isObject(params.resumeFrom) ? params.resumeFrom.continueFrom : void 0);
12471
+ const context = serializedTurnContext(continuation);
12472
+ if (!context) {
12473
+ return void 0;
12474
+ }
12475
+ if (params.sessionId !== context.sessionId) {
12476
+ return void 0;
12370
12477
  }
12478
+ return context.parent;
12371
12479
  }
12372
- function currentWorkflowAgentWrapperSpan() {
12373
- const parentSpanIds = _internalGetGlobalState().contextManager.getParentSpanIds()?.spanParents ?? [];
12374
- for (const parentSpanId of parentSpanIds) {
12375
- const span = workflowAgentWrapperSpans.get(parentSpanId);
12376
- if (span) {
12377
- return span;
12480
+ function exportSpanSynchronously(span) {
12481
+ const parentInfo = span.getParentInfo();
12482
+ if (!parentInfo) {
12483
+ return void 0;
12484
+ }
12485
+ const objectId = parentInfo.objectId.getSync().value;
12486
+ if (!objectId && !parentInfo.computeObjectMetadataArgs) {
12487
+ return void 0;
12488
+ }
12489
+ return new SpanComponentsV4({
12490
+ object_type: parentInfo.objectType,
12491
+ ...objectId ? { object_id: objectId } : {
12492
+ compute_object_metadata_args: parentInfo.computeObjectMetadataArgs ?? {}
12493
+ },
12494
+ row_id: span.id,
12495
+ root_span_id: span.rootSpanId,
12496
+ span_id: span.spanId
12497
+ }).toStr();
12498
+ }
12499
+ function exportedParent(parent) {
12500
+ return typeof parent === "string" ? parent : exportSpanSynchronously(parent);
12501
+ }
12502
+ function addSerializedContext(args) {
12503
+ if (!isObject(args.continuation) || args.sessionId === void 0) {
12504
+ return;
12505
+ }
12506
+ const parent = exportedParent(args.parent);
12507
+ if (!parent) {
12508
+ return;
12509
+ }
12510
+ const context = {
12511
+ parent,
12512
+ sessionId: args.sessionId
12513
+ };
12514
+ const signature = signTurnContext(context);
12515
+ if (!signature) {
12516
+ return;
12517
+ }
12518
+ Object.defineProperty(args.continuation, BRAINTRUST_TURN_CONTEXT_KEY, {
12519
+ configurable: true,
12520
+ enumerable: true,
12521
+ value: {
12522
+ ...context,
12523
+ signature
12524
+ },
12525
+ writable: true
12526
+ });
12527
+ }
12528
+ function lifecycleMethodDescriptor(session, method) {
12529
+ let owner = session;
12530
+ while (owner) {
12531
+ const descriptor = Object.getOwnPropertyDescriptor(owner, method);
12532
+ if (descriptor) {
12533
+ return { descriptor, owner };
12378
12534
  }
12535
+ owner = Object.getPrototypeOf(owner);
12379
12536
  }
12380
12537
  return void 0;
12381
12538
  }
12382
-
12383
- // src/vendor-sdk-types/ai-sdk-v7-telemetry.ts
12384
- var BRAINTRUST_AI_SDK_V7_OPERATION_KEY = /* @__PURE__ */ Symbol.for(
12385
- "braintrust.ai-sdk.v7.telemetry-operation-key"
12386
- );
12387
-
12388
- // src/instrumentation/plugins/ai-sdk-plugin.ts
12389
- var DEFAULT_DENY_OUTPUT_PATHS = [
12390
- // v3
12391
- "roundtrips[].request.body",
12392
- "roundtrips[].request.headers",
12393
- "roundtrips[].response.headers",
12394
- "rawResponse.headers",
12395
- "responseMessages",
12396
- // v5
12397
- "request.body",
12398
- "request.headers",
12399
- "responses[].headers",
12400
- "response.body",
12401
- "response.headers",
12402
- "steps[].request.body",
12403
- "steps[].request.headers",
12404
- "steps[].responses[].headers",
12405
- "steps[].response.body",
12406
- "steps[].response.headers"
12407
- ];
12408
- var AUTO_PATCHED_MODEL = /* @__PURE__ */ Symbol.for("braintrust.ai-sdk.auto-patched-model");
12409
- var AUTO_PATCHED_TOOL = /* @__PURE__ */ Symbol.for("braintrust.ai-sdk.auto-patched-tool");
12410
- var AUTO_PATCHED_V7_TELEMETRY_DISPATCHER = /* @__PURE__ */ Symbol.for(
12411
- "braintrust.ai-sdk.v7.auto-patched-telemetry-dispatcher"
12412
- );
12413
- var RUNTIME_DENY_OUTPUT_PATHS = /* @__PURE__ */ Symbol.for(
12414
- "braintrust.ai-sdk.deny-output-paths"
12415
- );
12416
- var aiSDKV7TelemetryOperationCounter = 0;
12417
- var TRANSPORT_PAYLOAD_ROOT_PATHS = [
12418
- "rawResponse",
12419
- "request",
12420
- "response",
12421
- "responses[]",
12422
- "roundtrips[].request",
12423
- "roundtrips[].response",
12424
- "steps[].request",
12425
- "steps[].response",
12426
- "steps[].responses[]"
12427
- ];
12428
- var AI_SDK_V7_TELEMETRY_CALLBACKS = [
12539
+ function patchLifecycleMethod(session, method) {
12540
+ let resolvedDescriptor;
12541
+ try {
12542
+ resolvedDescriptor = lifecycleMethodDescriptor(session, method);
12543
+ } catch {
12544
+ return;
12545
+ }
12546
+ if (!resolvedDescriptor || !("value" in resolvedDescriptor.descriptor) || typeof resolvedDescriptor.descriptor.value !== "function") {
12547
+ return;
12548
+ }
12549
+ const { descriptor, owner } = resolvedDescriptor;
12550
+ const patched = patchedLifecycleMethods.get(owner);
12551
+ if (patched?.has(method)) {
12552
+ return;
12553
+ }
12554
+ const original = descriptor.value;
12555
+ const replacement = function(...args) {
12556
+ const result = Reflect.apply(original, this, args);
12557
+ const addContext = (state) => {
12558
+ try {
12559
+ const parent = sessionTurnParents.get(this);
12560
+ if (!parent) {
12561
+ return;
12562
+ }
12563
+ const continuation = method === "suspendTurn" ? state : isObject(state) ? state.continueFrom : void 0;
12564
+ addSerializedContext({
12565
+ continuation,
12566
+ parent,
12567
+ sessionId: typeof this.sessionId === "string" ? this.sessionId : void 0
12568
+ });
12569
+ } catch {
12570
+ }
12571
+ };
12572
+ try {
12573
+ if (isObject(result) && typeof result.then === "function") {
12574
+ void Promise.resolve(result).then(addContext, () => {
12575
+ });
12576
+ } else {
12577
+ addContext(result);
12578
+ }
12579
+ } catch {
12580
+ }
12581
+ return result;
12582
+ };
12583
+ try {
12584
+ Object.defineProperty(owner, method, {
12585
+ ...descriptor,
12586
+ value: replacement
12587
+ });
12588
+ const ownerMethods = patched ?? /* @__PURE__ */ new Set();
12589
+ ownerMethods.add(method);
12590
+ if (!patched) {
12591
+ patchedLifecycleMethods.set(owner, ownerMethods);
12592
+ }
12593
+ } catch {
12594
+ }
12595
+ }
12596
+ function patchLifecycleMethods(session) {
12597
+ patchLifecycleMethod(session, "suspendTurn");
12598
+ patchLifecycleMethod(session, "detach");
12599
+ patchLifecycleMethod(session, "stop");
12600
+ }
12601
+ function registerHarnessTurnSpan(args) {
12602
+ if (!isObject(args.session)) {
12603
+ return;
12604
+ }
12605
+ const session = args.session;
12606
+ sessionTurnParents.set(session, args.span);
12607
+ wrapperTurnParents.set(args.span, args.span);
12608
+ patchLifecycleMethods(session);
12609
+ }
12610
+ function harnessContinuationParent(session) {
12611
+ return isObject(session) ? sessionTurnParents.get(session) : void 0;
12612
+ }
12613
+ function captureHarnessCreateSessionParent(params) {
12614
+ try {
12615
+ return continuationParentFromCreateSessionParams(params);
12616
+ } catch {
12617
+ return void 0;
12618
+ }
12619
+ }
12620
+ function registerHarnessSessionParent(session, parent) {
12621
+ if (!parent || !isObject(session)) {
12622
+ return;
12623
+ }
12624
+ const harnessSession = session;
12625
+ sessionTurnParents.set(harnessSession, parent);
12626
+ patchLifecycleMethods(harnessSession);
12627
+ }
12628
+ function currentHarnessTurnParent() {
12629
+ return harnessTurnParentStore?.getStore() ?? wrapperTurnParents.get(currentSpan());
12630
+ }
12631
+ function bindHarnessTurnParentToStart(tracingChannel, parentFromEvent) {
12632
+ const startChannel = tracingChannel.start;
12633
+ if (!startChannel) {
12634
+ return () => {
12635
+ };
12636
+ }
12637
+ harnessTurnParentStore ??= isomorph_default.newAsyncLocalStorage();
12638
+ const store = harnessTurnParentStore;
12639
+ startChannel.bindStore(
12640
+ store,
12641
+ (event) => parentFromEvent(event) ?? store.getStore()
12642
+ );
12643
+ return () => {
12644
+ startChannel.unbindStore(store);
12645
+ };
12646
+ }
12647
+ function startHarnessTurnChildSpan(parent, args) {
12648
+ const spanArgs = withSpanInstrumentationName(
12649
+ args,
12650
+ INSTRUMENTATION_NAMES.AI_SDK
12651
+ );
12652
+ return typeof parent === "string" ? startSpan({ ...spanArgs, parent }) : parent.startSpan(spanArgs);
12653
+ }
12654
+ function updateHarnessTurn(parent, update = {}) {
12655
+ if (!parent) {
12656
+ return;
12657
+ }
12658
+ const log2 = (event) => {
12659
+ if (typeof parent === "string") {
12660
+ updateSpan({ exported: parent, ...event });
12661
+ } else {
12662
+ parent.log(event);
12663
+ }
12664
+ };
12665
+ try {
12666
+ if (Object.prototype.hasOwnProperty.call(update, "output")) {
12667
+ log2({ output: null });
12668
+ }
12669
+ log2(update);
12670
+ } catch {
12671
+ }
12672
+ }
12673
+ function endHarnessTurn(parent) {
12674
+ const endTime = getCurrentUnixTimestamp();
12675
+ if (!parent) {
12676
+ return endTime;
12677
+ }
12678
+ try {
12679
+ const event = { metrics: { end: endTime } };
12680
+ if (typeof parent === "string") {
12681
+ updateSpan({ exported: parent, ...event });
12682
+ } else {
12683
+ parent.log(event);
12684
+ }
12685
+ } catch {
12686
+ }
12687
+ return endTime;
12688
+ }
12689
+
12690
+ // src/wrappers/ai-sdk/workflow-agent-context.ts
12691
+ var workflowAgentWrapperSpans = /* @__PURE__ */ new Map();
12692
+ function registerWorkflowAgentWrapperSpan(span) {
12693
+ if (span.spanId) {
12694
+ workflowAgentWrapperSpans.set(span.spanId, span);
12695
+ }
12696
+ }
12697
+ function unregisterWorkflowAgentWrapperSpan(span) {
12698
+ if (span.spanId) {
12699
+ workflowAgentWrapperSpans.delete(span.spanId);
12700
+ }
12701
+ }
12702
+ function currentWorkflowAgentWrapperSpan() {
12703
+ const parentSpanIds = _internalGetGlobalState().contextManager.getParentSpanIds()?.spanParents ?? [];
12704
+ for (const parentSpanId of parentSpanIds) {
12705
+ const span = workflowAgentWrapperSpans.get(parentSpanId);
12706
+ if (span) {
12707
+ return span;
12708
+ }
12709
+ }
12710
+ return void 0;
12711
+ }
12712
+
12713
+ // src/vendor-sdk-types/ai-sdk-v7-telemetry.ts
12714
+ var BRAINTRUST_AI_SDK_V7_OPERATION_KEY = /* @__PURE__ */ Symbol.for(
12715
+ "braintrust.ai-sdk.v7.telemetry-operation-key"
12716
+ );
12717
+
12718
+ // src/instrumentation/plugins/ai-sdk-plugin.ts
12719
+ var DEFAULT_DENY_OUTPUT_PATHS = [
12720
+ // v3
12721
+ "roundtrips[].request.body",
12722
+ "roundtrips[].request.headers",
12723
+ "roundtrips[].response.headers",
12724
+ "rawResponse.headers",
12725
+ "responseMessages",
12726
+ // v5
12727
+ "request.body",
12728
+ "request.headers",
12729
+ "responses[].headers",
12730
+ "response.body",
12731
+ "response.headers",
12732
+ "steps[].request.body",
12733
+ "steps[].request.headers",
12734
+ "steps[].responses[].headers",
12735
+ "steps[].response.body",
12736
+ "steps[].response.headers"
12737
+ ];
12738
+ var AUTO_PATCHED_MODEL = /* @__PURE__ */ Symbol.for("braintrust.ai-sdk.auto-patched-model");
12739
+ var AUTO_PATCHED_TOOL = /* @__PURE__ */ Symbol.for("braintrust.ai-sdk.auto-patched-tool");
12740
+ var AUTO_PATCHED_V7_TELEMETRY_DISPATCHER = /* @__PURE__ */ Symbol.for(
12741
+ "braintrust.ai-sdk.v7.auto-patched-telemetry-dispatcher"
12742
+ );
12743
+ var RUNTIME_DENY_OUTPUT_PATHS = /* @__PURE__ */ Symbol.for(
12744
+ "braintrust.ai-sdk.deny-output-paths"
12745
+ );
12746
+ var aiSDKV7TelemetryOperationCounter = 0;
12747
+ var TRANSPORT_PAYLOAD_ROOT_PATHS = [
12748
+ "rawResponse",
12749
+ "request",
12750
+ "response",
12751
+ "responses[]",
12752
+ "roundtrips[].request",
12753
+ "roundtrips[].response",
12754
+ "steps[].request",
12755
+ "steps[].response",
12756
+ "steps[].responses[]"
12757
+ ];
12758
+ var AI_SDK_V7_TELEMETRY_CALLBACKS = [
12429
12759
  "onStart",
12430
12760
  "onStepStart",
12431
12761
  "onLanguageModelCallStart",
@@ -12460,6 +12790,17 @@ var AISDKPlugin = class extends BasePlugin {
12460
12790
  subscribeToAISDK() {
12461
12791
  const denyOutputPaths = this.config.denyOutputPaths || DEFAULT_DENY_OUTPUT_PATHS;
12462
12792
  this.unsubscribers.push(subscribeToAISDKV7TelemetryDispatcher());
12793
+ this.unsubscribers.push(subscribeToHarnessAgentCreateSession());
12794
+ this.unsubscribers.push(
12795
+ subscribeToHarnessContinuation(
12796
+ harnessAgentChannels.continueGenerate,
12797
+ denyOutputPaths
12798
+ ),
12799
+ subscribeToHarnessContinuation(
12800
+ harnessAgentChannels.continueStream,
12801
+ denyOutputPaths
12802
+ )
12803
+ );
12463
12804
  this.unsubscribers.push(
12464
12805
  traceStreamingChannel(aiSDKChannels.generateText, {
12465
12806
  name: "generateText",
@@ -12655,8 +12996,9 @@ var AISDKPlugin = class extends BasePlugin {
12655
12996
  this.unsubscribers.push(
12656
12997
  traceStreamingChannel(harnessAgentChannels.generate, {
12657
12998
  name: "HarnessAgent.generate",
12999
+ startSpan: _internalStartSpanWithInitialMerge,
12658
13000
  type: "task" /* TASK */,
12659
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
13001
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
12660
13002
  extractOutput: (result, endEvent) => processAISDKOutput(
12661
13003
  result,
12662
13004
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -12668,8 +13010,9 @@ var AISDKPlugin = class extends BasePlugin {
12668
13010
  this.unsubscribers.push(
12669
13011
  traceStreamingChannel(harnessAgentChannels.stream, {
12670
13012
  name: "HarnessAgent.stream",
13013
+ startSpan: _internalStartSpanWithInitialMerge,
12671
13014
  type: "task" /* TASK */,
12672
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
13015
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
12673
13016
  extractOutput: (result, endEvent) => processAISDKOutput(
12674
13017
  result,
12675
13018
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -12694,8 +13037,10 @@ var AISDKPlugin = class extends BasePlugin {
12694
13037
  this.unsubscribers.push(
12695
13038
  traceStreamingChannel(harnessAgentChannels.continueGenerate, {
12696
13039
  name: "HarnessAgent.continueGenerate",
13040
+ shouldTrace: (args) => !harnessContinuationParent(harnessSessionFromArguments(args)),
13041
+ startSpan: _internalStartSpanWithInitialMerge,
12697
13042
  type: "task" /* TASK */,
12698
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
13043
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
12699
13044
  extractOutput: (result, endEvent) => processAISDKOutput(
12700
13045
  result,
12701
13046
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -12707,8 +13052,10 @@ var AISDKPlugin = class extends BasePlugin {
12707
13052
  this.unsubscribers.push(
12708
13053
  traceStreamingChannel(harnessAgentChannels.continueStream, {
12709
13054
  name: "HarnessAgent.continueStream",
13055
+ shouldTrace: (args) => !harnessContinuationParent(harnessSessionFromArguments(args)),
13056
+ startSpan: _internalStartSpanWithInitialMerge,
12710
13057
  type: "task" /* TASK */,
12711
- extractInput: ([params], event) => prepareAISDKHarnessAgentInput(params, event.self),
13058
+ extractInput: ([params], event, span) => prepareAISDKHarnessAgentInput(params, event.self, span),
12712
13059
  extractOutput: (result, endEvent) => processAISDKOutput(
12713
13060
  result,
12714
13061
  resolveDenyOutputPaths(endEvent, denyOutputPaths)
@@ -12800,6 +13147,8 @@ var AISDKPlugin = class extends BasePlugin {
12800
13147
  defaultDenyOutputPaths: denyOutputPaths,
12801
13148
  endEvent,
12802
13149
  onComplete: () => unregisterWorkflowAgentWrapperSpan(span),
13150
+ onCancel: () => unregisterWorkflowAgentWrapperSpan(span),
13151
+ onError: () => unregisterWorkflowAgentWrapperSpan(span),
12803
13152
  result,
12804
13153
  span,
12805
13154
  startTime
@@ -12808,6 +13157,153 @@ var AISDKPlugin = class extends BasePlugin {
12808
13157
  );
12809
13158
  }
12810
13159
  };
13160
+ function subscribeToHarnessAgentCreateSession() {
13161
+ const channel = harnessAgentChannels.createSession.tracingChannel();
13162
+ const parents = /* @__PURE__ */ new WeakMap();
13163
+ const handlers = {
13164
+ start: (event) => {
13165
+ const parent = captureHarnessCreateSessionParent(event.arguments?.[0]);
13166
+ if (parent) {
13167
+ parents.set(event, parent);
13168
+ }
13169
+ },
13170
+ asyncEnd: (event) => {
13171
+ registerHarnessSessionParent(event.result, parents.get(event));
13172
+ parents.delete(event);
13173
+ },
13174
+ error: (event) => {
13175
+ parents.delete(event);
13176
+ }
13177
+ };
13178
+ channel.subscribe(handlers);
13179
+ return () => channel.unsubscribe(handlers);
13180
+ }
13181
+ function harnessContinuationParentFromEvent(event) {
13182
+ try {
13183
+ return harnessContinuationParent(event.arguments?.[0]?.session);
13184
+ } catch {
13185
+ return void 0;
13186
+ }
13187
+ }
13188
+ function subscribeToHarnessContinuation(continuationChannel, defaultDenyOutputPaths) {
13189
+ const channel = continuationChannel.tracingChannel();
13190
+ const parents = /* @__PURE__ */ new WeakMap();
13191
+ const startTimes = /* @__PURE__ */ new WeakMap();
13192
+ const unbindParentStore = bindHarnessTurnParentToStart(
13193
+ channel,
13194
+ harnessContinuationParentFromEvent
13195
+ );
13196
+ const handlers = {
13197
+ start: (event) => {
13198
+ const parent = harnessContinuationParentFromEvent(event);
13199
+ if (!parent) {
13200
+ return;
13201
+ }
13202
+ parents.set(event, parent);
13203
+ startTimes.set(event, getCurrentUnixTimestamp());
13204
+ try {
13205
+ const params = event.arguments?.[0];
13206
+ if (params) {
13207
+ prepareAISDKHarnessAgentInput(params, event.self);
13208
+ }
13209
+ } catch (error) {
13210
+ debugLogger.error(
13211
+ "Error preparing Harness continuation telemetry:",
13212
+ error
13213
+ );
13214
+ }
13215
+ },
13216
+ asyncEnd: (event) => {
13217
+ const parent = parents.get(event);
13218
+ const startTime = startTimes.get(event) ?? getCurrentUnixTimestamp();
13219
+ parents.delete(event);
13220
+ startTimes.delete(event);
13221
+ if (!parent) {
13222
+ return;
13223
+ }
13224
+ const endEvent = event;
13225
+ const span = {
13226
+ end: () => endHarnessTurn(parent),
13227
+ log: (update) => updateHarnessTurn(
13228
+ parent,
13229
+ Object.prototype.hasOwnProperty.call(update, "error") && !Object.prototype.hasOwnProperty.call(update, "output") ? { ...update, output: null } : update
13230
+ )
13231
+ };
13232
+ try {
13233
+ if (isAsyncIterable(endEvent.result)) {
13234
+ patchStreamIfNeeded(endEvent.result, {
13235
+ onComplete: (chunks) => {
13236
+ try {
13237
+ const { metadata, metrics, output } = aggregateAISDKChunks(
13238
+ chunks,
13239
+ endEvent.result,
13240
+ endEvent
13241
+ );
13242
+ span.log({
13243
+ ...metadata ? { metadata } : {},
13244
+ metrics,
13245
+ output
13246
+ });
13247
+ } catch (error) {
13248
+ debugLogger.error(
13249
+ "Error aggregating Harness continuation stream:",
13250
+ error
13251
+ );
13252
+ } finally {
13253
+ span.end();
13254
+ }
13255
+ },
13256
+ onError: (error) => {
13257
+ span.log({ error: toLoggedError(error), output: null });
13258
+ span.end();
13259
+ }
13260
+ });
13261
+ return;
13262
+ }
13263
+ if (patchAISDKStreamingResult({
13264
+ defaultDenyOutputPaths,
13265
+ endEvent,
13266
+ result: endEvent.result,
13267
+ resolvePromiseUsage: true,
13268
+ span,
13269
+ startTime
13270
+ })) {
13271
+ return;
13272
+ }
13273
+ finalizeAISDKChildTracing(endEvent);
13274
+ span.log({
13275
+ metrics: extractTokenMetrics(endEvent.result),
13276
+ output: processAISDKOutput(
13277
+ endEvent.result,
13278
+ resolveDenyOutputPaths(endEvent, defaultDenyOutputPaths)
13279
+ )
13280
+ });
13281
+ span.end();
13282
+ } catch (error) {
13283
+ debugLogger.error("Error tracing Harness continuation:", error);
13284
+ span.end();
13285
+ }
13286
+ },
13287
+ error: (event) => {
13288
+ const parent = parents.get(event);
13289
+ parents.delete(event);
13290
+ startTimes.delete(event);
13291
+ if (!parent) {
13292
+ return;
13293
+ }
13294
+ updateHarnessTurn(parent, {
13295
+ error: toLoggedError(event.error),
13296
+ output: null
13297
+ });
13298
+ endHarnessTurn(parent);
13299
+ }
13300
+ };
13301
+ channel.subscribe(handlers);
13302
+ return () => {
13303
+ unbindParentStore();
13304
+ channel.unsubscribe(handlers);
13305
+ };
13306
+ }
12811
13307
  function subscribeToAISDKV7TelemetryDispatcher() {
12812
13308
  const channel = aiSDKChannels.v7CreateTelemetryDispatcher.tracingChannel();
12813
13309
  const telemetry = braintrustAISDKTelemetry();
@@ -13260,7 +13756,13 @@ function prepareAISDKCallInput(params, event, span, defaultDenyOutputPaths, chil
13260
13756
  metadata
13261
13757
  };
13262
13758
  }
13263
- function prepareAISDKHarnessAgentInput(params, self) {
13759
+ function prepareAISDKHarnessAgentInput(params, self, span) {
13760
+ if (span) {
13761
+ registerHarnessTurnSpan({
13762
+ session: params.session,
13763
+ span
13764
+ });
13765
+ }
13264
13766
  if (isObject(self)) {
13265
13767
  try {
13266
13768
  if (isObject(self.settings)) {
@@ -13299,6 +13801,10 @@ function prepareAISDKHarnessAgentInput(params, self) {
13299
13801
  metadata
13300
13802
  };
13301
13803
  }
13804
+ function harnessSessionFromArguments(args) {
13805
+ const params = args[0];
13806
+ return isObject(params) ? params.session : void 0;
13807
+ }
13302
13808
  function prepareAISDKWorkflowAgentStreamInput(params, event, span, defaultDenyOutputPaths) {
13303
13809
  registerWorkflowAgentWrapperSpan(span);
13304
13810
  const { input } = processAISDKWorkflowAgentCallInput(params);
@@ -13746,19 +14252,22 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
13746
14252
  activeEntry.openSpans.delete(span);
13747
14253
  }
13748
14254
  },
13749
- {
13750
- name: "doGenerate",
13751
- spanAttributes: {
13752
- type: "llm" /* LLM */
14255
+ withSpanInstrumentationName(
14256
+ {
14257
+ name: "doGenerate",
14258
+ spanAttributes: {
14259
+ type: "llm" /* LLM */
14260
+ },
14261
+ event: buildAISDKModelStartEvent(
14262
+ callOptions,
14263
+ activeEntry.baseMetadata,
14264
+ {
14265
+ workflowAgent: activeEntry.childTracingOptions.workflowAgent
14266
+ }
14267
+ )
13753
14268
  },
13754
- event: buildAISDKModelStartEvent(
13755
- callOptions,
13756
- activeEntry.baseMetadata,
13757
- {
13758
- workflowAgent: activeEntry.childTracingOptions.workflowAgent
13759
- }
13760
- )
13761
- }
14269
+ INSTRUMENTATION_NAMES.AI_SDK
14270
+ )
13762
14271
  );
13763
14272
  };
13764
14273
  if (originalDoStream) {
@@ -13768,19 +14277,24 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
13768
14277
  return Reflect.apply(originalDoStream, resolvedModel, [callOptions]);
13769
14278
  }
13770
14279
  closeOpenAISDKModelPatchSpans(activeEntry);
13771
- const span = activeEntry.parentSpan.startSpan({
13772
- name: "doStream",
13773
- spanAttributes: {
13774
- type: "llm" /* LLM */
13775
- },
13776
- event: buildAISDKModelStartEvent(
13777
- callOptions,
13778
- activeEntry.baseMetadata,
14280
+ const span = activeEntry.parentSpan.startSpan(
14281
+ withSpanInstrumentationName(
13779
14282
  {
13780
- workflowAgent: activeEntry.childTracingOptions.workflowAgent
13781
- }
14283
+ name: "doStream",
14284
+ spanAttributes: {
14285
+ type: "llm" /* LLM */
14286
+ },
14287
+ event: buildAISDKModelStartEvent(
14288
+ callOptions,
14289
+ activeEntry.baseMetadata,
14290
+ {
14291
+ workflowAgent: activeEntry.childTracingOptions.workflowAgent
14292
+ }
14293
+ )
14294
+ },
14295
+ INSTRUMENTATION_NAMES.AI_SDK
13782
14296
  )
13783
- });
14297
+ );
13784
14298
  activeEntry.openSpans.add(span);
13785
14299
  const streamStartTime = getCurrentUnixTimestamp();
13786
14300
  const result = await withCurrent(
@@ -13952,12 +14466,17 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
13952
14466
  }
13953
14467
  if (isAsyncGenerator(result)) {
13954
14468
  return (async function* () {
13955
- const span = activeEntry.parentSpan.startSpan({
13956
- name: activeEntry.name,
13957
- spanAttributes: {
13958
- type: "tool" /* TOOL */
13959
- }
13960
- });
14469
+ const span = activeEntry.parentSpan.startSpan(
14470
+ withSpanInstrumentationName(
14471
+ {
14472
+ name: activeEntry.name,
14473
+ spanAttributes: {
14474
+ type: "tool" /* TOOL */
14475
+ }
14476
+ },
14477
+ INSTRUMENTATION_NAMES.AI_SDK
14478
+ )
14479
+ );
13961
14480
  span.log({ input: serializeToolExecutionInput(args) });
13962
14481
  try {
13963
14482
  let lastValue;
@@ -13981,12 +14500,15 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
13981
14500
  span.log({ output: awaitedResult });
13982
14501
  return awaitedResult;
13983
14502
  },
13984
- {
13985
- name: activeEntry.name,
13986
- spanAttributes: {
13987
- type: "tool" /* TOOL */
13988
- }
13989
- }
14503
+ withSpanInstrumentationName(
14504
+ {
14505
+ name: activeEntry.name,
14506
+ spanAttributes: {
14507
+ type: "tool" /* TOOL */
14508
+ }
14509
+ },
14510
+ INSTRUMENTATION_NAMES.AI_SDK
14511
+ )
13990
14512
  );
13991
14513
  };
13992
14514
  cleanup.push(() => {
@@ -14145,6 +14667,8 @@ function patchAISDKStreamingResult(args) {
14145
14667
  defaultDenyOutputPaths,
14146
14668
  endEvent,
14147
14669
  onComplete,
14670
+ onCancel,
14671
+ onError,
14148
14672
  result,
14149
14673
  resolvePromiseUsage,
14150
14674
  span,
@@ -14156,14 +14680,43 @@ function patchAISDKStreamingResult(args) {
14156
14680
  const resultRecord = result;
14157
14681
  attachKnownResultPromiseHandlers(resultRecord);
14158
14682
  let finalized = false;
14159
- const finalize = () => {
14683
+ const finalize = (outcome) => {
14160
14684
  if (finalized) {
14161
14685
  return;
14162
14686
  }
14163
14687
  finalized = true;
14164
- finalizeAISDKChildTracing(endEvent);
14165
- span.end();
14166
- onComplete?.();
14688
+ try {
14689
+ finalizeAISDKChildTracing(endEvent);
14690
+ } catch (error) {
14691
+ debugLogger.error("Error finalizing AI SDK child tracing:", error);
14692
+ }
14693
+ try {
14694
+ span.end();
14695
+ } catch (error) {
14696
+ debugLogger.error("Error ending AI SDK streaming span:", error);
14697
+ }
14698
+ if (outcome && "error" in outcome) {
14699
+ try {
14700
+ onError?.(outcome.error);
14701
+ } catch (error) {
14702
+ debugLogger.error("Error in AI SDK streaming error hook:", error);
14703
+ }
14704
+ } else if (outcome) {
14705
+ try {
14706
+ onComplete?.(outcome);
14707
+ } catch (error) {
14708
+ debugLogger.error("Error in AI SDK streaming completion hook:", error);
14709
+ }
14710
+ } else {
14711
+ try {
14712
+ onCancel?.();
14713
+ } catch (error) {
14714
+ debugLogger.error(
14715
+ "Error in AI SDK streaming cancellation hook:",
14716
+ error
14717
+ );
14718
+ }
14719
+ }
14167
14720
  };
14168
14721
  let outputLogged = false;
14169
14722
  const logStreamingOutput = async (firstChunkTime) => {
@@ -14197,15 +14750,29 @@ function patchAISDKStreamingResult(args) {
14197
14750
  resolveDenyOutputPaths(endEvent, defaultDenyOutputPaths)
14198
14751
  );
14199
14752
  const metadata = buildResolvedMetadataPayload(result).metadata;
14200
- span.log({
14201
- output,
14202
- ...metadata ? { metadata } : {},
14203
- metrics
14204
- });
14753
+ try {
14754
+ span.log({
14755
+ output,
14756
+ ...metadata ? { metadata } : {},
14757
+ metrics
14758
+ });
14759
+ } catch (error) {
14760
+ debugLogger.error("Error logging AI SDK streaming output:", error);
14761
+ }
14762
+ finalize({ metrics, output });
14205
14763
  } catch (error) {
14206
- span.log({ error: toLoggedError(error) });
14207
- } finally {
14208
- finalize();
14764
+ const loggedError = toLoggedError(error);
14765
+ try {
14766
+ span.log({ error: loggedError });
14767
+ } catch (loggingError) {
14768
+ debugLogger.error(
14769
+ "Error logging AI SDK streaming failure:",
14770
+ loggingError
14771
+ );
14772
+ }
14773
+ finalize({
14774
+ error: error instanceof Error ? error : new Error(String(loggedError))
14775
+ });
14209
14776
  }
14210
14777
  };
14211
14778
  const createAsyncIterableHooks = () => {
@@ -14222,11 +14789,16 @@ function patchAISDKStreamingResult(args) {
14222
14789
  onError: (error) => {
14223
14790
  if (!outputLogged) {
14224
14791
  outputLogged = true;
14225
- span.log({
14226
- error: error.message
14227
- });
14792
+ try {
14793
+ span.log({ error });
14794
+ } catch (loggingError) {
14795
+ debugLogger.error(
14796
+ "Error logging AI SDK stream failure:",
14797
+ loggingError
14798
+ );
14799
+ }
14228
14800
  }
14229
- finalize();
14801
+ finalize({ error });
14230
14802
  },
14231
14803
  onCancel: finalize
14232
14804
  };
@@ -14312,8 +14884,18 @@ function patchAISDKStreamingResult(args) {
14312
14884
  }
14313
14885
  controller.enqueue(value);
14314
14886
  } catch (error) {
14315
- span.log({ error: toLoggedError(error) });
14316
- finalize();
14887
+ const loggedError = toLoggedError(error);
14888
+ try {
14889
+ span.log({ error: loggedError });
14890
+ } catch (loggingError) {
14891
+ debugLogger.error(
14892
+ "Error logging AI SDK base stream failure:",
14893
+ loggingError
14894
+ );
14895
+ }
14896
+ finalize({
14897
+ error: error instanceof Error ? error : new Error(String(loggedError))
14898
+ });
14317
14899
  controller.error(error);
14318
14900
  }
14319
14901
  },
@@ -15112,14 +15694,17 @@ function braintrustAISDKTelemetry() {
15112
15694
  console.error(`Error in Braintrust AI SDK telemetry ${name}:`, error);
15113
15695
  }
15114
15696
  };
15115
- const startChildSpan = (operationKey, name, type, event) => {
15697
+ const startChildSpan = (operationKey, name, type, event, parentOverride) => {
15116
15698
  const parent = operations.get(operationKey)?.span;
15117
- const spanArgs = {
15118
- name,
15119
- spanAttributes: { type },
15120
- ...event ? { event } : {}
15121
- };
15122
- const span = parent ? parent.startSpan(spanArgs) : startSpan(spanArgs);
15699
+ const spanArgs = withSpanInstrumentationName(
15700
+ {
15701
+ name,
15702
+ spanAttributes: { type },
15703
+ ...event ? { event } : {}
15704
+ },
15705
+ INSTRUMENTATION_NAMES.AI_SDK
15706
+ );
15707
+ const span = parentOverride ? startHarnessTurnChildSpan(parentOverride, spanArgs) : parent ? parent.startSpan(spanArgs) : startSpan(spanArgs);
15123
15708
  const state = operations.get(operationKey);
15124
15709
  if (state && type === "llm" /* LLM */) {
15125
15710
  state.hadModelChild = true;
@@ -15399,14 +15984,30 @@ function braintrustAISDKTelemetry() {
15399
15984
  const workflowAgent = operationName === "WorkflowAgent.stream";
15400
15985
  const wrapperSpan = workflowAgent ? currentWorkflowAgentWrapperSpan() : void 0;
15401
15986
  const ownsSpan = !wrapperSpan;
15402
- const span = ownsSpan ? startSpan({
15403
- name: operationName,
15404
- spanAttributes: { type: "function" /* FUNCTION */ }
15405
- }) : wrapperSpan;
15987
+ const harnessTurnParent = currentHarnessTurnParent();
15988
+ const span = ownsSpan ? harnessTurnParent ? startHarnessTurnChildSpan(
15989
+ harnessTurnParent,
15990
+ withSpanInstrumentationName(
15991
+ {
15992
+ name: operationName,
15993
+ spanAttributes: { type: "function" /* FUNCTION */ }
15994
+ },
15995
+ INSTRUMENTATION_NAMES.AI_SDK
15996
+ )
15997
+ ) : startSpan(
15998
+ withSpanInstrumentationName(
15999
+ {
16000
+ name: operationName,
16001
+ spanAttributes: { type: "function" /* FUNCTION */ }
16002
+ },
16003
+ INSTRUMENTATION_NAMES.AI_SDK
16004
+ )
16005
+ ) : wrapperSpan;
15406
16006
  const operationKey = createOperationKey(event, operationName);
15407
16007
  registerOperation({
15408
16008
  callId: event.callId,
15409
16009
  hadModelChild: false,
16010
+ harnessTurnParent,
15410
16011
  loggedInput: false,
15411
16012
  operationName,
15412
16013
  operationKey,
@@ -15647,7 +16248,8 @@ function braintrustAISDKTelemetry() {
15647
16248
  toolCallId,
15648
16249
  ...typeof event.toolCall.toolName === "string" ? { toolName: event.toolCall.toolName } : {}
15649
16250
  }
15650
- }
16251
+ },
16252
+ state?.harnessTurnParent
15651
16253
  );
15652
16254
  toolSpans.set(toolCallId, { operationKey, span });
15653
16255
  });
@@ -16223,15 +16825,20 @@ var FlueObserveBridge = class {
16223
16825
  safeLog(existing.span, { input, metadata });
16224
16826
  return;
16225
16827
  }
16226
- const span = startSpan({
16227
- name: `workflow:${workflowName}`,
16228
- spanAttributes: { type: "task" /* TASK */ },
16229
- startTime: eventTime(event.startedAt ?? event.timestamp),
16230
- event: {
16231
- input,
16232
- metadata
16233
- }
16234
- });
16828
+ const span = startSpan(
16829
+ withSpanInstrumentationName(
16830
+ {
16831
+ name: `workflow:${workflowName}`,
16832
+ spanAttributes: { type: "task" /* TASK */ },
16833
+ startTime: eventTime(event.startedAt ?? event.timestamp),
16834
+ event: {
16835
+ input,
16836
+ metadata
16837
+ }
16838
+ },
16839
+ INSTRUMENTATION_NAMES.FLUE
16840
+ )
16841
+ );
16235
16842
  this.runsById.set(event.runId, { metadata, span });
16236
16843
  }
16237
16844
  handleRunResume(event, ctx) {
@@ -16251,12 +16858,17 @@ var FlueObserveBridge = class {
16251
16858
  safeLog(existing.span, { metadata });
16252
16859
  return;
16253
16860
  }
16254
- const span = startSpan({
16255
- name: `workflow:${workflowName}`,
16256
- spanAttributes: { type: "task" /* TASK */ },
16257
- startTime: eventTime(event.startedAt ?? event.timestamp),
16258
- event: { metadata }
16259
- });
16861
+ const span = startSpan(
16862
+ withSpanInstrumentationName(
16863
+ {
16864
+ name: `workflow:${workflowName}`,
16865
+ spanAttributes: { type: "task" /* TASK */ },
16866
+ startTime: eventTime(event.startedAt ?? event.timestamp),
16867
+ event: { metadata }
16868
+ },
16869
+ INSTRUMENTATION_NAMES.FLUE
16870
+ )
16871
+ );
16260
16872
  this.runsById.set(event.runId, { metadata, span });
16261
16873
  }
16262
16874
  handleRunEnd(event) {
@@ -16895,7 +17507,14 @@ function stateMatchesRun(state, runId) {
16895
17507
  return state.metadata["flue.run_id"] === runId;
16896
17508
  }
16897
17509
  function startFlueSpan(parent, args) {
16898
- return parent ? withCurrent(parent, () => startSpan(args)) : startSpan(args);
17510
+ return parent ? withCurrent(
17511
+ parent,
17512
+ () => startSpan(
17513
+ withSpanInstrumentationName(args, INSTRUMENTATION_NAMES.FLUE)
17514
+ )
17515
+ ) : startSpan(
17516
+ withSpanInstrumentationName(args, INSTRUMENTATION_NAMES.FLUE)
17517
+ );
16899
17518
  }
16900
17519
  function runWithCurrentSpanStore(span, next) {
16901
17520
  const state = _internalGetGlobalState();
@@ -16985,9 +17604,13 @@ var BraintrustLangChainCallbackHandler = class {
16985
17604
  ...this.options.debug ? { runId, parentRunId } : {}
16986
17605
  }
16987
17606
  };
16988
- let span = parentSpan.startSpan(args);
17607
+ const spanArgs = withSpanInstrumentationName(
17608
+ args,
17609
+ INSTRUMENTATION_NAMES.LANGCHAIN
17610
+ );
17611
+ let span = parentSpan.startSpan(spanArgs);
16989
17612
  if (!Object.is(this.options.logger, NOOP_SPAN) && Object.is(span, NOOP_SPAN)) {
16990
- span = initLogger().startSpan(args);
17613
+ span = initLogger().startSpan(spanArgs);
16991
17614
  }
16992
17615
  this.spans.set(runId, span);
16993
17616
  }
@@ -17826,10 +18449,15 @@ function startCodexRun(event, operation) {
17826
18449
  provider: "openai",
17827
18450
  ...event.moduleVersion ? { "openai_codex.version": event.moduleVersion } : {}
17828
18451
  };
17829
- const span = startSpan({
17830
- name: "OpenAI Codex",
17831
- spanAttributes: { type: "task" /* TASK */ }
17832
- });
18452
+ const span = startSpan(
18453
+ withSpanInstrumentationName(
18454
+ {
18455
+ name: "OpenAI Codex",
18456
+ spanAttributes: { type: "task" /* TASK */ }
18457
+ },
18458
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
18459
+ )
18460
+ );
17833
18461
  const startTime = getCurrentUnixTimestamp();
17834
18462
  safeLog2(span, {
17835
18463
  input: sanitizedInput,
@@ -17978,7 +18606,12 @@ async function createCompletedItemSpan(state, item) {
17978
18606
  if (!spanArgs) {
17979
18607
  return;
17980
18608
  }
17981
- const span = startSpan(spanArgs.start);
18609
+ const span = startSpan(
18610
+ withSpanInstrumentationName(
18611
+ spanArgs.start,
18612
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
18613
+ )
18614
+ );
17982
18615
  safeLog2(span, spanArgs.end);
17983
18616
  span.end();
17984
18617
  }
@@ -18020,15 +18653,20 @@ async function ensureActiveLlmSpan(state) {
18020
18653
  ...state.metadata["openai_codex.thread_id"] ? { "openai_codex.thread_id": state.metadata["openai_codex.thread_id"] } : {},
18021
18654
  "openai_codex.llm_sequence": sequence
18022
18655
  };
18023
- const span = startSpan({
18024
- event: {
18025
- ...sequence === 1 ? { input: state.input } : {},
18026
- metadata
18027
- },
18028
- name: "OpenAI Codex LLM",
18029
- parent: await state.span.export(),
18030
- spanAttributes: { type: "llm" /* LLM */ }
18031
- });
18656
+ const span = startSpan(
18657
+ withSpanInstrumentationName(
18658
+ {
18659
+ event: {
18660
+ ...sequence === 1 ? { input: state.input } : {},
18661
+ metadata
18662
+ },
18663
+ name: "OpenAI Codex LLM",
18664
+ parent: await state.span.export(),
18665
+ spanAttributes: { type: "llm" /* LLM */ }
18666
+ },
18667
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
18668
+ )
18669
+ );
18032
18670
  state.activeLlmSpan = {
18033
18671
  anonymousMessages: [],
18034
18672
  anonymousReasoning: [],
@@ -18074,7 +18712,15 @@ async function startCodexItemSpan(state, item) {
18074
18712
  if (!spanArgs) {
18075
18713
  return;
18076
18714
  }
18077
- state.activeItemSpans.set(itemId, startSpan(spanArgs.start));
18715
+ state.activeItemSpans.set(
18716
+ itemId,
18717
+ startSpan(
18718
+ withSpanInstrumentationName(
18719
+ spanArgs.start,
18720
+ INSTRUMENTATION_NAMES.OPENAI_CODEX
18721
+ )
18722
+ )
18723
+ );
18078
18724
  }
18079
18725
  function updateCodexItem(state, item) {
18080
18726
  if (item.type === "agent_message" && typeof item.text === "string") {
@@ -18446,7 +19092,7 @@ var AnthropicPlugin = class extends BasePlugin {
18446
19092
  );
18447
19093
  }
18448
19094
  subscribeToAnthropicToolRunner() {
18449
- const tracingChannel2 = anthropicChannels.betaMessagesToolRunner.tracingChannel();
19095
+ const tracingChannel = anthropicChannels.betaMessagesToolRunner.tracingChannel();
18450
19096
  const states = /* @__PURE__ */ new WeakMap();
18451
19097
  const handlers = {
18452
19098
  start: (event) => {
@@ -18454,12 +19100,17 @@ var AnthropicPlugin = class extends BasePlugin {
18454
19100
  return;
18455
19101
  }
18456
19102
  const params = event.arguments[0] ?? {};
18457
- const span = startSpan({
18458
- name: "anthropic.beta.messages.toolRunner",
18459
- spanAttributes: {
18460
- type: "task" /* TASK */
18461
- }
18462
- });
19103
+ const span = startSpan(
19104
+ withSpanInstrumentationName(
19105
+ {
19106
+ name: "anthropic.beta.messages.toolRunner",
19107
+ spanAttributes: {
19108
+ type: "task" /* TASK */
19109
+ }
19110
+ },
19111
+ INSTRUMENTATION_NAMES.ANTHROPIC
19112
+ )
19113
+ );
18463
19114
  span.log({
18464
19115
  input: processAttachmentsInInput(
18465
19116
  coalesceInput(params.messages ?? [], params.system)
@@ -18498,9 +19149,9 @@ var AnthropicPlugin = class extends BasePlugin {
18498
19149
  states.delete(event);
18499
19150
  }
18500
19151
  };
18501
- tracingChannel2.subscribe(handlers);
19152
+ tracingChannel.subscribe(handlers);
18502
19153
  this.unsubscribers.push(() => {
18503
- tracingChannel2.unsubscribe(handlers);
19154
+ tracingChannel.unsubscribe(handlers);
18504
19155
  });
18505
19156
  }
18506
19157
  };
@@ -18600,19 +19251,22 @@ function wrapAnthropicToolRunnerTool(tool, index, state) {
18600
19251
  return finalizeError(error);
18601
19252
  }
18602
19253
  },
18603
- {
18604
- event: {
18605
- input: getAnthropicToolRunnerInput(args),
18606
- metadata: {
18607
- "gen_ai.tool.name": toolName,
18608
- provider: "anthropic"
19254
+ withSpanInstrumentationName(
19255
+ {
19256
+ event: {
19257
+ input: getAnthropicToolRunnerInput(args),
19258
+ metadata: {
19259
+ "gen_ai.tool.name": toolName,
19260
+ provider: "anthropic"
19261
+ }
19262
+ },
19263
+ name: `tool: ${toolName}`,
19264
+ spanAttributes: {
19265
+ type: "tool" /* TOOL */
18609
19266
  }
18610
19267
  },
18611
- name: `tool: ${toolName}`,
18612
- spanAttributes: {
18613
- type: "tool" /* TOOL */
18614
- }
18615
- }
19268
+ INSTRUMENTATION_NAMES.ANTHROPIC
19269
+ )
18616
19270
  );
18617
19271
  },
18618
19272
  writable: runDescriptor?.writable ?? true
@@ -19222,22 +19876,27 @@ function wrapLocalClaudeToolHandler(handler, getMetadata) {
19222
19876
  const spanName = metadata.serverName ? `tool: ${metadata.serverName}/${metadata.toolName}` : `tool: ${metadata.toolName}`;
19223
19877
  const runWithResolvedParent = async () => {
19224
19878
  const parent = toolUseId && localToolParentResolver ? await localToolParentResolver(toolUseId).catch(() => void 0) : void 0;
19225
- const span = startSpan({
19226
- event: {
19227
- input: handlerArgs[0],
19228
- metadata: {
19229
- "claude_agent_sdk.raw_tool_name": rawToolName,
19230
- "gen_ai.tool.name": metadata.toolName,
19231
- ...toolUseId && { "gen_ai.tool.call.id": toolUseId },
19232
- ...metadata.serverName && {
19233
- "mcp.server": metadata.serverName
19234
- }
19235
- }
19236
- },
19237
- name: spanName,
19238
- ...parent && { parent },
19239
- spanAttributes: { type: "tool" /* TOOL */ }
19240
- });
19879
+ const span = startSpan(
19880
+ withSpanInstrumentationName(
19881
+ {
19882
+ event: {
19883
+ input: handlerArgs[0],
19884
+ metadata: {
19885
+ "claude_agent_sdk.raw_tool_name": rawToolName,
19886
+ "gen_ai.tool.name": metadata.toolName,
19887
+ ...toolUseId && { "gen_ai.tool.call.id": toolUseId },
19888
+ ...metadata.serverName && {
19889
+ "mcp.server": metadata.serverName
19890
+ }
19891
+ }
19892
+ },
19893
+ name: spanName,
19894
+ ...parent && { parent },
19895
+ spanAttributes: { type: "tool" /* TOOL */ }
19896
+ },
19897
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
19898
+ )
19899
+ );
19241
19900
  const runHandler = () => Reflect.apply(handler, this, handlerArgs);
19242
19901
  const finalizeSuccess = (result) => {
19243
19902
  span.log({ output: result });
@@ -19562,14 +20221,19 @@ async function createLLMSpanForMessages(messages, promptMessages, conversationHi
19562
20221
  ).filter(
19563
20222
  (c) => c !== void 0
19564
20223
  );
19565
- const span = existingSpan ?? startSpan({
19566
- name: "anthropic.messages.create",
19567
- parent: parentSpan,
19568
- spanAttributes: {
19569
- type: "llm" /* LLM */
19570
- },
19571
- startTime
19572
- });
20224
+ const span = existingSpan ?? startSpan(
20225
+ withSpanInstrumentationName(
20226
+ {
20227
+ name: "anthropic.messages.create",
20228
+ parent: parentSpan,
20229
+ spanAttributes: {
20230
+ type: "llm" /* LLM */
20231
+ },
20232
+ startTime
20233
+ },
20234
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
20235
+ )
20236
+ );
19573
20237
  span.log({
19574
20238
  input,
19575
20239
  metadata: model ? { model } : void 0,
@@ -19672,25 +20336,30 @@ function createToolTracingHooks(resolveParentSpan, activeToolSpans, mcpServers,
19672
20336
  return {};
19673
20337
  }
19674
20338
  const parsed = parseToolName(input.tool_name);
19675
- const toolSpan = startSpan({
19676
- event: {
19677
- input: input.tool_input,
19678
- metadata: {
19679
- "claude_agent_sdk.cwd": input.cwd,
19680
- "claude_agent_sdk.raw_tool_name": parsed.rawToolName,
19681
- "claude_agent_sdk.session_id": input.session_id,
19682
- "gen_ai.tool.call.id": toolUseID,
19683
- "gen_ai.tool.name": parsed.toolName,
19684
- ...parsed.mcpServer && { "mcp.server": parsed.mcpServer },
19685
- ...getMcpServerMetadata(parsed.mcpServer, mcpServers)
19686
- }
19687
- },
19688
- name: parsed.displayName,
19689
- parent: await resolveParentSpan(toolUseID, {
19690
- agentId: input.agent_id
19691
- }),
19692
- spanAttributes: { type: "tool" /* TOOL */ }
19693
- });
20339
+ const toolSpan = startSpan(
20340
+ withSpanInstrumentationName(
20341
+ {
20342
+ event: {
20343
+ input: input.tool_input,
20344
+ metadata: {
20345
+ "claude_agent_sdk.cwd": input.cwd,
20346
+ "claude_agent_sdk.raw_tool_name": parsed.rawToolName,
20347
+ "claude_agent_sdk.session_id": input.session_id,
20348
+ "gen_ai.tool.call.id": toolUseID,
20349
+ "gen_ai.tool.name": parsed.toolName,
20350
+ ...parsed.mcpServer && { "mcp.server": parsed.mcpServer },
20351
+ ...getMcpServerMetadata(parsed.mcpServer, mcpServers)
20352
+ }
20353
+ },
20354
+ name: parsed.displayName,
20355
+ parent: await resolveParentSpan(toolUseID, {
20356
+ agentId: input.agent_id
20357
+ }),
20358
+ spanAttributes: { type: "tool" /* TOOL */ }
20359
+ },
20360
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
20361
+ )
20362
+ );
19694
20363
  activeToolSpans.set(toolUseID, toolSpan);
19695
20364
  return {};
19696
20365
  };
@@ -20056,14 +20725,19 @@ async function ensureSubAgentSpan(subAgentDetailsByToolUseId, rootSpan, activeTo
20056
20725
  const spanName = formatSubAgentSpanName(details);
20057
20726
  const parentToolSpan = activeToolSpans.get(parentToolUseId);
20058
20727
  const parentSpan = parentToolSpan ? await parentToolSpan.export() : await rootSpan.export();
20059
- const subAgentSpan = startSpan({
20060
- event: {
20061
- metadata: subAgentDetailsToMetadata(details)
20062
- },
20063
- name: spanName,
20064
- parent: parentSpan,
20065
- spanAttributes: { type: "task" /* TASK */ }
20066
- });
20728
+ const subAgentSpan = startSpan(
20729
+ withSpanInstrumentationName(
20730
+ {
20731
+ event: {
20732
+ metadata: subAgentDetailsToMetadata(details)
20733
+ },
20734
+ name: spanName,
20735
+ parent: parentSpan,
20736
+ spanAttributes: { type: "task" /* TASK */ }
20737
+ },
20738
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
20739
+ )
20740
+ );
20067
20741
  subAgentSpans.set(parentToolUseId, subAgentSpan);
20068
20742
  return subAgentSpan;
20069
20743
  }
@@ -20084,14 +20758,19 @@ async function ensureActiveLlmSpanForParentToolUse(rootSpan, activeLlmSpansByPar
20084
20758
  );
20085
20759
  llmParentSpan = await subAgentSpan.export();
20086
20760
  }
20087
- const llmSpan = startSpan({
20088
- name: "anthropic.messages.create",
20089
- parent: llmParentSpan,
20090
- spanAttributes: {
20091
- type: "llm" /* LLM */
20092
- },
20093
- startTime
20094
- });
20761
+ const llmSpan = startSpan(
20762
+ withSpanInstrumentationName(
20763
+ {
20764
+ name: "anthropic.messages.create",
20765
+ parent: llmParentSpan,
20766
+ spanAttributes: {
20767
+ type: "llm" /* LLM */
20768
+ },
20769
+ startTime
20770
+ },
20771
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
20772
+ )
20773
+ );
20095
20774
  activeLlmSpansByParentToolUse.set(parentKey, llmSpan);
20096
20775
  return llmSpan;
20097
20776
  }
@@ -20360,12 +21039,17 @@ var ClaudeAgentSDKPlugin = class extends BasePlugin {
20360
21039
  }
20361
21040
  })();
20362
21041
  }
20363
- const span = startSpan({
20364
- name: "Claude Agent",
20365
- spanAttributes: {
20366
- type: "task" /* TASK */
20367
- }
20368
- });
21042
+ const span = startSpan(
21043
+ withSpanInstrumentationName(
21044
+ {
21045
+ name: "Claude Agent",
21046
+ spanAttributes: {
21047
+ type: "task" /* TASK */
21048
+ }
21049
+ },
21050
+ INSTRUMENTATION_NAMES.CLAUDE_AGENT_SDK
21051
+ )
21052
+ );
20369
21053
  const startTime = getCurrentUnixTimestamp();
20370
21054
  try {
20371
21055
  span.log({
@@ -20552,7 +21236,7 @@ var CursorSDKPlugin = class extends BasePlugin {
20552
21236
  this.subscribeToAgentFactory(cursorSDKChannels.resume);
20553
21237
  }
20554
21238
  subscribeToAgentFactory(channel) {
20555
- const tracingChannel2 = channel.tracingChannel();
21239
+ const tracingChannel = channel.tracingChannel();
20556
21240
  const handlers = {
20557
21241
  asyncEnd: (event) => {
20558
21242
  patchCursorAgentInPlace(event.result);
@@ -20560,9 +21244,9 @@ var CursorSDKPlugin = class extends BasePlugin {
20560
21244
  error: () => {
20561
21245
  }
20562
21246
  };
20563
- tracingChannel2.subscribe(handlers);
21247
+ tracingChannel.subscribe(handlers);
20564
21248
  this.unsubscribers.push(() => {
20565
- tracingChannel2.unsubscribe(handlers);
21249
+ tracingChannel.unsubscribe(handlers);
20566
21250
  });
20567
21251
  }
20568
21252
  subscribeToPrompt() {
@@ -20579,10 +21263,15 @@ var CursorSDKPlugin = class extends BasePlugin {
20579
21263
  provider: "cursor",
20580
21264
  ...event.moduleVersion ? { "cursor_sdk.version": event.moduleVersion } : {}
20581
21265
  };
20582
- const span = startSpan({
20583
- name: "Cursor Agent",
20584
- spanAttributes: { type: "task" /* TASK */ }
20585
- });
21266
+ const span = startSpan(
21267
+ withSpanInstrumentationName(
21268
+ {
21269
+ name: "Cursor Agent",
21270
+ spanAttributes: { type: "task" /* TASK */ }
21271
+ },
21272
+ INSTRUMENTATION_NAMES.CURSOR_SDK
21273
+ )
21274
+ );
20586
21275
  const startTime = getCurrentUnixTimestamp();
20587
21276
  safeLog3(span, {
20588
21277
  input: sanitizeUserMessage(message),
@@ -20644,10 +21333,15 @@ var CursorSDKPlugin = class extends BasePlugin {
20644
21333
  provider: "cursor",
20645
21334
  ...event.moduleVersion ? { "cursor_sdk.version": event.moduleVersion } : {}
20646
21335
  };
20647
- const span = startSpan({
20648
- name: "Cursor Agent",
20649
- spanAttributes: { type: "task" /* TASK */ }
20650
- });
21336
+ const span = startSpan(
21337
+ withSpanInstrumentationName(
21338
+ {
21339
+ name: "Cursor Agent",
21340
+ spanAttributes: { type: "task" /* TASK */ }
21341
+ },
21342
+ INSTRUMENTATION_NAMES.CURSOR_SDK
21343
+ )
21344
+ );
20651
21345
  const startTime = getCurrentUnixTimestamp();
20652
21346
  safeLog3(span, {
20653
21347
  input: sanitizeUserMessage(message),
@@ -21094,29 +21788,39 @@ async function startToolSpan(state, args) {
21094
21788
  if (args.truncated?.result !== void 0) {
21095
21789
  metadata["cursor_sdk.tool.result_truncated"] = args.truncated.result;
21096
21790
  }
21097
- const span = startSpan({
21098
- event: {
21099
- input: args.args,
21100
- metadata
21101
- },
21102
- name: `tool: ${name}`,
21103
- parent: await state.span.export(),
21104
- spanAttributes: { type: "tool" /* TOOL */ }
21105
- });
21791
+ const span = startSpan(
21792
+ withSpanInstrumentationName(
21793
+ {
21794
+ event: {
21795
+ input: args.args,
21796
+ metadata
21797
+ },
21798
+ name: `tool: ${name}`,
21799
+ parent: await state.span.export(),
21800
+ spanAttributes: { type: "tool" /* TOOL */ }
21801
+ },
21802
+ INSTRUMENTATION_NAMES.CURSOR_SDK
21803
+ )
21804
+ );
21106
21805
  let subAgentSpan;
21107
21806
  if (isSubAgentToolName(name)) {
21108
- subAgentSpan = startSpan({
21109
- event: {
21110
- input: args.args,
21111
- metadata: {
21112
- "cursor_sdk.subagent.tool_call_id": args.callId,
21113
- "gen_ai.tool.name": name
21114
- }
21115
- },
21116
- name: formatSubAgentSpanName2(args.toolCall, args.args),
21117
- parent: await span.export(),
21118
- spanAttributes: { type: "task" /* TASK */ }
21119
- });
21807
+ subAgentSpan = startSpan(
21808
+ withSpanInstrumentationName(
21809
+ {
21810
+ event: {
21811
+ input: args.args,
21812
+ metadata: {
21813
+ "cursor_sdk.subagent.tool_call_id": args.callId,
21814
+ "gen_ai.tool.name": name
21815
+ }
21816
+ },
21817
+ name: formatSubAgentSpanName2(args.toolCall, args.args),
21818
+ parent: await span.export(),
21819
+ spanAttributes: { type: "task" /* TASK */ }
21820
+ },
21821
+ INSTRUMENTATION_NAMES.CURSOR_SDK
21822
+ )
21823
+ );
21120
21824
  }
21121
21825
  return { span, subAgentSpan };
21122
21826
  }
@@ -21488,16 +22192,19 @@ var OpenAIAgentsTraceProcessor = class _OpenAIAgentsTraceProcessor {
21488
22192
  this.evictOldestTrace();
21489
22193
  }
21490
22194
  const current = currentSpan();
21491
- const span = current && current !== NOOP_SPAN ? current.startSpan({
21492
- name: trace.name,
21493
- type: "task" /* TASK */
21494
- }) : this.logger ? this.logger.startSpan({
21495
- name: trace.name,
21496
- type: "task" /* TASK */
21497
- }) : startSpan({
21498
- name: trace.name,
21499
- type: "task" /* TASK */
21500
- });
22195
+ const spanArgs = withSpanInstrumentationName(
22196
+ {
22197
+ name: trace.name,
22198
+ type: "task" /* TASK */
22199
+ },
22200
+ INSTRUMENTATION_NAMES.OPENAI_AGENTS
22201
+ );
22202
+ const span = current && current !== NOOP_SPAN ? current.startSpan(spanArgs) : this.logger ? this.logger.startSpan(spanArgs) : startSpan(
22203
+ withSpanInstrumentationName(
22204
+ spanArgs,
22205
+ INSTRUMENTATION_NAMES.OPENAI_AGENTS
22206
+ )
22207
+ );
21501
22208
  span.log({
21502
22209
  input: "Agent workflow started",
21503
22210
  metadata: {
@@ -21548,10 +22255,15 @@ var OpenAIAgentsTraceProcessor = class _OpenAIAgentsTraceProcessor {
21548
22255
  if (!parentSpan) {
21549
22256
  return Promise.resolve();
21550
22257
  }
21551
- const childSpan = parentSpan.startSpan({
21552
- name: spanNameFromAgents(span),
21553
- type: spanTypeFromAgents(span)
21554
- });
22258
+ const childSpan = parentSpan.startSpan(
22259
+ withSpanInstrumentationName(
22260
+ {
22261
+ name: spanNameFromAgents(span),
22262
+ type: spanTypeFromAgents(span)
22263
+ },
22264
+ INSTRUMENTATION_NAMES.OPENAI_AGENTS
22265
+ )
22266
+ );
21555
22267
  traceData.childSpans.set(span.spanId, childSpan);
21556
22268
  return Promise.resolve();
21557
22269
  }
@@ -21842,22 +22554,27 @@ var GoogleGenAIPlugin = class extends BasePlugin {
21842
22554
  this.subscribeToInteractionsCreateChannel();
21843
22555
  }
21844
22556
  subscribeToGenerateContentChannel() {
21845
- const tracingChannel2 = googleGenAIChannels.generateContent.tracingChannel();
22557
+ const tracingChannel = googleGenAIChannels.generateContent.tracingChannel();
21846
22558
  const states = /* @__PURE__ */ new WeakMap();
21847
22559
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart2(
21848
- tracingChannel2,
22560
+ tracingChannel,
21849
22561
  states,
21850
22562
  (event) => {
21851
22563
  const params = event.arguments[0];
21852
22564
  const input = serializeGenerateContentInput(params);
21853
22565
  const metadata = extractGenerateContentMetadata(params);
21854
- const span = startSpan({
21855
- name: "generate_content",
21856
- spanAttributes: {
21857
- type: "llm" /* LLM */
21858
- },
21859
- event: createWrapperParityEvent({ input, metadata })
21860
- });
22566
+ const span = startSpan(
22567
+ withSpanInstrumentationName(
22568
+ {
22569
+ name: "generate_content",
22570
+ spanAttributes: {
22571
+ type: "llm" /* LLM */
22572
+ },
22573
+ event: createWrapperParityEvent({ input, metadata })
22574
+ },
22575
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
22576
+ )
22577
+ );
21861
22578
  return {
21862
22579
  span,
21863
22580
  startTime: getCurrentUnixTimestamp()
@@ -21870,13 +22587,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
21870
22587
  const params = event.arguments[0];
21871
22588
  const input = serializeGenerateContentInput(params);
21872
22589
  const metadata = extractGenerateContentMetadata(params);
21873
- const span = startSpan({
21874
- name: "generate_content",
21875
- spanAttributes: {
21876
- type: "llm" /* LLM */
21877
- },
21878
- event: createWrapperParityEvent({ input, metadata })
21879
- });
22590
+ const span = startSpan(
22591
+ withSpanInstrumentationName(
22592
+ {
22593
+ name: "generate_content",
22594
+ spanAttributes: {
22595
+ type: "llm" /* LLM */
22596
+ },
22597
+ event: createWrapperParityEvent({ input, metadata })
22598
+ },
22599
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
22600
+ )
22601
+ );
21880
22602
  return {
21881
22603
  span,
21882
22604
  startTime: getCurrentUnixTimestamp()
@@ -21909,14 +22631,14 @@ var GoogleGenAIPlugin = class extends BasePlugin {
21909
22631
  logErrorAndEndSpan(states, event);
21910
22632
  }
21911
22633
  };
21912
- tracingChannel2.subscribe(handlers);
22634
+ tracingChannel.subscribe(handlers);
21913
22635
  this.unsubscribers.push(() => {
21914
22636
  unbindCurrentSpanStore?.();
21915
- tracingChannel2.unsubscribe(handlers);
22637
+ tracingChannel.unsubscribe(handlers);
21916
22638
  });
21917
22639
  }
21918
22640
  subscribeToGenerateContentStreamChannel() {
21919
- const tracingChannel2 = googleGenAIChannels.generateContentStream.tracingChannel();
22641
+ const tracingChannel = googleGenAIChannels.generateContentStream.tracingChannel();
21920
22642
  const handlers = {
21921
22643
  start: (event) => {
21922
22644
  const streamEvent = event;
@@ -21937,28 +22659,33 @@ var GoogleGenAIPlugin = class extends BasePlugin {
21937
22659
  error: () => {
21938
22660
  }
21939
22661
  };
21940
- tracingChannel2.subscribe(handlers);
22662
+ tracingChannel.subscribe(handlers);
21941
22663
  this.unsubscribers.push(() => {
21942
- tracingChannel2.unsubscribe(handlers);
22664
+ tracingChannel.unsubscribe(handlers);
21943
22665
  });
21944
22666
  }
21945
22667
  subscribeToEmbedContentChannel() {
21946
- const tracingChannel2 = googleGenAIChannels.embedContent.tracingChannel();
22668
+ const tracingChannel = googleGenAIChannels.embedContent.tracingChannel();
21947
22669
  const states = /* @__PURE__ */ new WeakMap();
21948
22670
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart2(
21949
- tracingChannel2,
22671
+ tracingChannel,
21950
22672
  states,
21951
22673
  (event) => {
21952
22674
  const params = event.arguments[0];
21953
22675
  const input = serializeEmbedContentInput(params);
21954
22676
  const metadata = extractEmbedContentMetadata(params);
21955
- const span = startSpan({
21956
- name: "embed_content",
21957
- spanAttributes: {
21958
- type: "llm" /* LLM */
21959
- },
21960
- event: createWrapperParityEvent({ input, metadata })
21961
- });
22677
+ const span = startSpan(
22678
+ withSpanInstrumentationName(
22679
+ {
22680
+ name: "embed_content",
22681
+ spanAttributes: {
22682
+ type: "llm" /* LLM */
22683
+ },
22684
+ event: createWrapperParityEvent({ input, metadata })
22685
+ },
22686
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
22687
+ )
22688
+ );
21962
22689
  return {
21963
22690
  span,
21964
22691
  startTime: getCurrentUnixTimestamp()
@@ -21971,13 +22698,18 @@ var GoogleGenAIPlugin = class extends BasePlugin {
21971
22698
  const params = event.arguments[0];
21972
22699
  const input = serializeEmbedContentInput(params);
21973
22700
  const metadata = extractEmbedContentMetadata(params);
21974
- const span = startSpan({
21975
- name: "embed_content",
21976
- spanAttributes: {
21977
- type: "llm" /* LLM */
21978
- },
21979
- event: createWrapperParityEvent({ input, metadata })
21980
- });
22701
+ const span = startSpan(
22702
+ withSpanInstrumentationName(
22703
+ {
22704
+ name: "embed_content",
22705
+ spanAttributes: {
22706
+ type: "llm" /* LLM */
22707
+ },
22708
+ event: createWrapperParityEvent({ input, metadata })
22709
+ },
22710
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
22711
+ )
22712
+ );
21981
22713
  return {
21982
22714
  span,
21983
22715
  startTime: getCurrentUnixTimestamp()
@@ -22006,10 +22738,10 @@ var GoogleGenAIPlugin = class extends BasePlugin {
22006
22738
  logErrorAndEndSpan(states, event);
22007
22739
  }
22008
22740
  };
22009
- tracingChannel2.subscribe(handlers);
22741
+ tracingChannel.subscribe(handlers);
22010
22742
  this.unsubscribers.push(() => {
22011
22743
  unbindCurrentSpanStore?.();
22012
- tracingChannel2.unsubscribe(handlers);
22744
+ tracingChannel.unsubscribe(handlers);
22013
22745
  });
22014
22746
  }
22015
22747
  subscribeToInteractionsCreateChannel() {
@@ -22045,10 +22777,10 @@ function ensureSpanState(states, event, create) {
22045
22777
  states.set(event, created);
22046
22778
  return created;
22047
22779
  }
22048
- function bindCurrentSpanStoreToStart2(tracingChannel2, states, create) {
22780
+ function bindCurrentSpanStoreToStart2(tracingChannel, states, create) {
22049
22781
  const state = _internalGetGlobalState();
22050
22782
  const contextManager = state?.contextManager;
22051
- const startChannel = tracingChannel2.start;
22783
+ const startChannel = tracingChannel.start;
22052
22784
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
22053
22785
  if (!startChannel?.bindStore || !currentSpanStore) {
22054
22786
  return void 0;
@@ -22088,16 +22820,21 @@ function patchGoogleGenAIStreamingResult(args) {
22088
22820
  const requestStartTime = startTime ?? getCurrentUnixTimestamp();
22089
22821
  const ensureSpan = () => {
22090
22822
  if (!span) {
22091
- span = startSpan({
22092
- name: "generate_content_stream",
22093
- spanAttributes: {
22094
- type: "llm" /* LLM */
22095
- },
22096
- event: {
22097
- input,
22098
- metadata
22099
- }
22100
- });
22823
+ span = startSpan(
22824
+ withSpanInstrumentationName(
22825
+ {
22826
+ name: "generate_content_stream",
22827
+ spanAttributes: {
22828
+ type: "llm" /* LLM */
22829
+ },
22830
+ event: {
22831
+ input,
22832
+ metadata
22833
+ }
22834
+ },
22835
+ INSTRUMENTATION_NAMES.GOOGLE_GENAI
22836
+ )
22837
+ );
22101
22838
  }
22102
22839
  return span;
22103
22840
  };
@@ -22546,11 +23283,11 @@ function summarizeEmbedContentOutput(response) {
22546
23283
  };
22547
23284
  }
22548
23285
  function populateUsageMetrics(metrics, usage) {
22549
- if (usage.promptTokenCount !== void 0) {
22550
- metrics.prompt_tokens = usage.promptTokenCount;
23286
+ if (usage.promptTokenCount !== void 0 || usage.toolUsePromptTokenCount !== void 0) {
23287
+ metrics.prompt_tokens = (usage.promptTokenCount ?? 0) + (usage.toolUsePromptTokenCount ?? 0);
22551
23288
  }
22552
- if (usage.candidatesTokenCount !== void 0) {
22553
- metrics.completion_tokens = usage.candidatesTokenCount;
23289
+ if (usage.candidatesTokenCount !== void 0 || usage.thoughtsTokenCount !== void 0) {
23290
+ metrics.completion_tokens = (usage.candidatesTokenCount ?? 0) + (usage.thoughtsTokenCount ?? 0);
22554
23291
  }
22555
23292
  if (usage.totalTokenCount !== void 0) {
22556
23293
  metrics.tokens = usage.totalTokenCount;
@@ -22561,13 +23298,26 @@ function populateUsageMetrics(metrics, usage) {
22561
23298
  if (usage.thoughtsTokenCount !== void 0) {
22562
23299
  metrics.completion_reasoning_tokens = usage.thoughtsTokenCount;
22563
23300
  }
23301
+ for (const detail of usage.promptTokensDetails ?? []) {
23302
+ if (detail.modality === "AUDIO" && detail.tokenCount !== void 0) {
23303
+ metrics.prompt_audio_tokens = (metrics.prompt_audio_tokens ?? 0) + detail.tokenCount;
23304
+ }
23305
+ }
23306
+ for (const detail of usage.candidatesTokensDetails ?? []) {
23307
+ if (detail.modality === "AUDIO" && detail.tokenCount !== void 0) {
23308
+ metrics.completion_audio_tokens = (metrics.completion_audio_tokens ?? 0) + detail.tokenCount;
23309
+ }
23310
+ if (detail.modality === "IMAGE" && detail.tokenCount !== void 0) {
23311
+ metrics.completion_image_tokens = (metrics.completion_image_tokens ?? 0) + detail.tokenCount;
23312
+ }
23313
+ }
22564
23314
  }
22565
23315
  function populateInteractionUsageMetrics(metrics, usage) {
22566
23316
  if (typeof usage.total_input_tokens === "number") {
22567
23317
  metrics.prompt_tokens = usage.total_input_tokens;
22568
23318
  }
22569
23319
  if (typeof usage.total_output_tokens === "number") {
22570
- metrics.completion_tokens = usage.total_output_tokens;
23320
+ metrics.completion_tokens = usage.total_output_tokens + (typeof usage.total_thought_tokens === "number" ? usage.total_thought_tokens : 0);
22571
23321
  }
22572
23322
  if (typeof usage.total_tokens === "number") {
22573
23323
  metrics.tokens = usage.total_tokens;
@@ -22578,6 +23328,24 @@ function populateInteractionUsageMetrics(metrics, usage) {
22578
23328
  if (typeof usage.total_thought_tokens === "number") {
22579
23329
  metrics.completion_reasoning_tokens = usage.total_thought_tokens;
22580
23330
  }
23331
+ for (const detail of Array.isArray(usage.input_tokens_by_modality) ? usage.input_tokens_by_modality : []) {
23332
+ if (typeof detail?.modality === "string" && detail.modality.toLowerCase() === "audio" && typeof detail.tokens === "number") {
23333
+ metrics.prompt_audio_tokens = (metrics.prompt_audio_tokens ?? 0) + detail.tokens;
23334
+ }
23335
+ }
23336
+ for (const detail of Array.isArray(usage.output_tokens_by_modality) ? usage.output_tokens_by_modality : []) {
23337
+ if (typeof detail?.modality !== "string" || typeof detail.tokens !== "number") {
23338
+ continue;
23339
+ }
23340
+ switch (detail.modality.toLowerCase()) {
23341
+ case "audio":
23342
+ metrics.completion_audio_tokens = (metrics.completion_audio_tokens ?? 0) + detail.tokens;
23343
+ break;
23344
+ case "image":
23345
+ metrics.completion_image_tokens = (metrics.completion_image_tokens ?? 0) + detail.tokens;
23346
+ break;
23347
+ }
23348
+ }
22581
23349
  }
22582
23350
  function aggregateGenerateContentChunks(chunks, startTime, firstTokenTime) {
22583
23351
  const end = getCurrentUnixTimestamp();
@@ -23288,6 +24056,259 @@ function extractTextGenerationStreamMetadata(chunks) {
23288
24056
  return void 0;
23289
24057
  }
23290
24058
 
24059
+ // src/instrumentation/plugins/huggingface-transformers-plugin.ts
24060
+ var REQUEST_METADATA_KEYS = [
24061
+ "temperature",
24062
+ "top_p",
24063
+ "max_tokens",
24064
+ "stop"
24065
+ ];
24066
+ var HuggingFaceTransformersPlugin = class extends BasePlugin {
24067
+ onEnable() {
24068
+ this.subscribeToPipelineFactory();
24069
+ this.unsubscribers.push(
24070
+ traceAsyncChannel(huggingFaceTransformersChannels.pipelineCall, {
24071
+ name: (_args, event) => {
24072
+ const task = getTask(event);
24073
+ const operation = task?.replaceAll("-", "_") ?? "unknown";
24074
+ return `huggingface.transformers.${operation}`;
24075
+ },
24076
+ type: "llm" /* LLM */,
24077
+ shouldTrace: (_args, event) => isSupportedHuggingFaceTransformersTask(
24078
+ getTask(event)
24079
+ ),
24080
+ extractInput: (args, event) => ({
24081
+ input: extractInput(
24082
+ getTask(event),
24083
+ args
24084
+ ),
24085
+ metadata: extractMetadata(
24086
+ event,
24087
+ args
24088
+ )
24089
+ }),
24090
+ extractOutput: (result, event) => extractOutput(
24091
+ getTask(event),
24092
+ result
24093
+ ),
24094
+ extractMetrics: () => ({})
24095
+ })
24096
+ );
24097
+ }
24098
+ onDisable() {
24099
+ this.unsubscribers = unsubscribeAll(this.unsubscribers);
24100
+ }
24101
+ subscribeToPipelineFactory() {
24102
+ const channel = huggingFaceTransformersChannels.pipeline.tracingChannel();
24103
+ const handlers = {
24104
+ asyncEnd: (event) => {
24105
+ if (typeof event.result !== "function") {
24106
+ return;
24107
+ }
24108
+ registerHuggingFaceTransformersPipeline(
24109
+ event.result,
24110
+ event.arguments?.[0],
24111
+ event.arguments?.[1]
24112
+ );
24113
+ }
24114
+ };
24115
+ channel.subscribe(handlers);
24116
+ this.unsubscribers.push(() => channel.unsubscribe(handlers));
24117
+ }
24118
+ };
24119
+ function getTask(event) {
24120
+ const self = event.self;
24121
+ const registeredTask = getHuggingFaceTransformersPipelineInfo(self)?.task;
24122
+ if (registeredTask !== void 0) {
24123
+ return registeredTask;
24124
+ }
24125
+ if (typeof self?.task === "string") {
24126
+ return self.task;
24127
+ }
24128
+ return void 0;
24129
+ }
24130
+ function extractMetadata(event, args) {
24131
+ const metadata = {
24132
+ provider: "huggingface"
24133
+ };
24134
+ const registeredModel = getHuggingFaceTransformersPipelineInfo(
24135
+ event.self
24136
+ )?.model;
24137
+ const model = registeredModel ?? modelIdentifier(event.self);
24138
+ if (model) {
24139
+ metadata.model = model;
24140
+ }
24141
+ const task = getTask(event);
24142
+ const options = task === "question-answering" ? args[2] : args[1];
24143
+ if (isObject(options)) {
24144
+ for (const key of REQUEST_METADATA_KEYS) {
24145
+ if (options[key] !== void 0) {
24146
+ metadata[key] = options[key];
24147
+ }
24148
+ }
24149
+ }
24150
+ return metadata;
24151
+ }
24152
+ function modelIdentifier(pipeline) {
24153
+ const model = pipeline?.model;
24154
+ if (!isObject(model)) {
24155
+ return void 0;
24156
+ }
24157
+ const config = isObject(model.config) ? model.config : void 0;
24158
+ for (const value of [
24159
+ config?._name_or_path,
24160
+ config?.name_or_path,
24161
+ config?.model_id,
24162
+ config?.modelId,
24163
+ model.name
24164
+ ]) {
24165
+ if (typeof value === "string" && value.length > 0) {
24166
+ return value;
24167
+ }
24168
+ }
24169
+ return void 0;
24170
+ }
24171
+ function extractInput(task, args) {
24172
+ switch (task) {
24173
+ case "feature-extraction":
24174
+ return args[0];
24175
+ case "question-answering": {
24176
+ const question = args[0];
24177
+ const context = args[1];
24178
+ if (Array.isArray(question) && Array.isArray(context) && question.every((value) => typeof value === "string") && context.every((value) => typeof value === "string")) {
24179
+ return question.map((value, index) => [
24180
+ {
24181
+ role: "user",
24182
+ content: `Context:
24183
+ ${context[index] ?? ""}
24184
+
24185
+ Question:
24186
+ ${value}`
24187
+ }
24188
+ ]);
24189
+ }
24190
+ if (typeof question === "string" && typeof context === "string") {
24191
+ return [
24192
+ {
24193
+ role: "user",
24194
+ content: `Context:
24195
+ ${context}
24196
+
24197
+ Question:
24198
+ ${question}`
24199
+ }
24200
+ ];
24201
+ }
24202
+ return { context, question };
24203
+ }
24204
+ }
24205
+ const input = args[0];
24206
+ if (task === "text-generation" && isChat(input)) {
24207
+ return input;
24208
+ }
24209
+ if (task === "text-generation" && Array.isArray(input) && input.every(isChat)) {
24210
+ return input;
24211
+ }
24212
+ if (typeof input === "string") {
24213
+ return [{ role: "user", content: input }];
24214
+ }
24215
+ if (Array.isArray(input) && input.every((value) => typeof value === "string")) {
24216
+ return input.map((value) => [
24217
+ {
24218
+ role: "user",
24219
+ content: value
24220
+ }
24221
+ ]);
24222
+ }
24223
+ return input;
24224
+ }
24225
+ function isChat(value) {
24226
+ return Array.isArray(value) && value.length > 0 && value.every(
24227
+ (message) => isObject(message) && typeof message.role === "string" && "content" in message
24228
+ );
24229
+ }
24230
+ function extractOutput(task, result) {
24231
+ switch (task) {
24232
+ case "feature-extraction":
24233
+ return summarizeEmbedding(result);
24234
+ case "question-answering":
24235
+ return choicesFromAnswers(result);
24236
+ default:
24237
+ return choicesFromGenerations(result);
24238
+ }
24239
+ }
24240
+ function summarizeEmbedding(result) {
24241
+ if (!isObject(result) || !Array.isArray(result.dims)) {
24242
+ return void 0;
24243
+ }
24244
+ const { dims } = result;
24245
+ if (dims.length === 0 || !dims.every((dimension) => typeof dimension === "number")) {
24246
+ return void 0;
24247
+ }
24248
+ if (dims.length === 1) {
24249
+ return { embedding_length: dims[0] };
24250
+ }
24251
+ if (dims.length === 2) {
24252
+ return {
24253
+ embedding_count: dims[0],
24254
+ embedding_length: dims[1]
24255
+ };
24256
+ }
24257
+ return {
24258
+ embedding_batch_count: dims[0],
24259
+ embedding_count: dims[1],
24260
+ embedding_length: dims.at(-1) ?? 0
24261
+ };
24262
+ }
24263
+ function choicesFromAnswers(result) {
24264
+ const answers = Array.isArray(result) ? result.flat() : [result];
24265
+ const choices = answers.flatMap((answer, index) => {
24266
+ if (!isObject(answer) || typeof answer.answer !== "string") {
24267
+ return [];
24268
+ }
24269
+ return [
24270
+ {
24271
+ index,
24272
+ finish_reason: "stop",
24273
+ message: {
24274
+ role: "assistant",
24275
+ content: answer.answer
24276
+ }
24277
+ }
24278
+ ];
24279
+ });
24280
+ return choices.length > 0 ? choices : void 0;
24281
+ }
24282
+ function choicesFromGenerations(result) {
24283
+ const generations = Array.isArray(result) ? result.flat() : [result];
24284
+ const choices = generations.flatMap((generation, index) => {
24285
+ if (!isObject(generation)) {
24286
+ return [];
24287
+ }
24288
+ const generated = generation.generated_text ?? generation.summary_text;
24289
+ let content;
24290
+ if (typeof generated === "string") {
24291
+ content = generated;
24292
+ } else if (isChat(generated)) {
24293
+ content = generated.at(-1)?.content;
24294
+ }
24295
+ if (typeof content !== "string") {
24296
+ return [];
24297
+ }
24298
+ return [
24299
+ {
24300
+ index,
24301
+ finish_reason: "stop",
24302
+ message: {
24303
+ role: "assistant",
24304
+ content
24305
+ }
24306
+ }
24307
+ ];
24308
+ });
24309
+ return choices.length > 0 ? choices : void 0;
24310
+ }
24311
+
23291
24312
  // src/instrumentation/plugins/openrouter-agent-plugin.ts
23292
24313
  var OpenRouterAgentPlugin = class extends BasePlugin {
23293
24314
  onEnable() {
@@ -23667,7 +24688,7 @@ function isWrappedTool(tool) {
23667
24688
  return Boolean(tool[OPENROUTER_WRAPPED_TOOL]);
23668
24689
  }
23669
24690
  function traceToolExecution(args) {
23670
- const tracingChannel2 = openRouterAgentChannels.toolExecute.tracingChannel();
24691
+ const tracingChannel = openRouterAgentChannels.toolExecute.tracingChannel();
23671
24692
  const input = args.args.length > 0 ? args.args[0] : void 0;
23672
24693
  const event = {
23673
24694
  arguments: [input],
@@ -23677,33 +24698,33 @@ function traceToolExecution(args) {
23677
24698
  toolCallId: args.toolCallId,
23678
24699
  toolName: args.toolName
23679
24700
  };
23680
- tracingChannel2.start.publish(event);
24701
+ tracingChannel.start.publish(event);
23681
24702
  try {
23682
24703
  const result = args.execute();
23683
- return publishToolResult(tracingChannel2, event, result);
24704
+ return publishToolResult(tracingChannel, event, result);
23684
24705
  } catch (error) {
23685
24706
  event.error = normalizeError(error);
23686
- tracingChannel2.error.publish(event);
24707
+ tracingChannel.error.publish(event);
23687
24708
  throw error;
23688
24709
  }
23689
24710
  }
23690
- function publishToolResult(tracingChannel2, event, result) {
24711
+ function publishToolResult(tracingChannel, event, result) {
23691
24712
  if (isPromiseLike(result)) {
23692
24713
  return result.then(
23693
24714
  (resolved) => {
23694
24715
  event.result = resolved;
23695
- tracingChannel2.asyncEnd.publish(event);
24716
+ tracingChannel.asyncEnd.publish(event);
23696
24717
  return resolved;
23697
24718
  },
23698
24719
  (error) => {
23699
24720
  event.error = normalizeError(error);
23700
- tracingChannel2.error.publish(event);
24721
+ tracingChannel.error.publish(event);
23701
24722
  throw error;
23702
24723
  }
23703
24724
  );
23704
24725
  }
23705
24726
  event.result = result;
23706
- tracingChannel2.asyncEnd.publish(event);
24727
+ tracingChannel.asyncEnd.publish(event);
23707
24728
  return result;
23708
24729
  }
23709
24730
  function getToolCallId(context) {
@@ -24573,7 +25594,7 @@ function isWrappedTool2(tool) {
24573
25594
  return Boolean(tool[OPENROUTER_WRAPPED_TOOL2]);
24574
25595
  }
24575
25596
  function traceToolExecution2(args) {
24576
- const tracingChannel2 = openRouterChannels.toolExecute.tracingChannel();
25597
+ const tracingChannel = openRouterChannels.toolExecute.tracingChannel();
24577
25598
  const input = args.args.length > 0 ? args.args[0] : void 0;
24578
25599
  const event = {
24579
25600
  arguments: [input],
@@ -24583,33 +25604,33 @@ function traceToolExecution2(args) {
24583
25604
  toolCallId: args.toolCallId,
24584
25605
  toolName: args.toolName
24585
25606
  };
24586
- tracingChannel2.start.publish(event);
25607
+ tracingChannel.start.publish(event);
24587
25608
  try {
24588
25609
  const result = args.execute();
24589
- return publishToolResult2(tracingChannel2, event, result);
25610
+ return publishToolResult2(tracingChannel, event, result);
24590
25611
  } catch (error) {
24591
25612
  event.error = normalizeError2(error);
24592
- tracingChannel2.error.publish(event);
25613
+ tracingChannel.error.publish(event);
24593
25614
  throw error;
24594
25615
  }
24595
25616
  }
24596
- function publishToolResult2(tracingChannel2, event, result) {
25617
+ function publishToolResult2(tracingChannel, event, result) {
24597
25618
  if (isPromiseLike(result)) {
24598
25619
  return result.then(
24599
25620
  (resolved) => {
24600
25621
  event.result = resolved;
24601
- tracingChannel2.asyncEnd.publish(event);
25622
+ tracingChannel.asyncEnd.publish(event);
24602
25623
  return resolved;
24603
25624
  },
24604
25625
  (error) => {
24605
25626
  event.error = normalizeError2(error);
24606
- tracingChannel2.error.publish(event);
25627
+ tracingChannel.error.publish(event);
24607
25628
  throw error;
24608
25629
  }
24609
25630
  );
24610
25631
  }
24611
25632
  event.result = result;
24612
- tracingChannel2.asyncEnd.publish(event);
25633
+ tracingChannel.asyncEnd.publish(event);
24613
25634
  return result;
24614
25635
  }
24615
25636
  function getToolCallId2(context) {
@@ -25727,17 +26748,22 @@ var GoogleADKPlugin = class extends BasePlugin {
25727
26748
  this.activeAgentSpans.clear();
25728
26749
  }
25729
26750
  subscribeToRunnerRunAsync() {
25730
- const tracingChannel2 = googleADKChannels.runnerRunAsync.tracingChannel();
26751
+ const tracingChannel = googleADKChannels.runnerRunAsync.tracingChannel();
25731
26752
  const states = /* @__PURE__ */ new WeakMap();
25732
26753
  const createState = (event) => {
25733
26754
  const params = event.arguments[0] ?? {};
25734
26755
  const contextKey = extractRunnerContextKey(params);
25735
- const span = startSpan({
25736
- name: "Google ADK Runner",
25737
- spanAttributes: {
25738
- type: "task" /* TASK */
25739
- }
25740
- });
26756
+ const span = startSpan(
26757
+ withSpanInstrumentationName(
26758
+ {
26759
+ name: "Google ADK Runner",
26760
+ spanAttributes: {
26761
+ type: "task" /* TASK */
26762
+ }
26763
+ },
26764
+ INSTRUMENTATION_NAMES.GOOGLE_ADK
26765
+ )
26766
+ );
25741
26767
  const startTime = getCurrentUnixTimestamp();
25742
26768
  try {
25743
26769
  const metadata = extractRunnerMetadata(params);
@@ -25753,7 +26779,7 @@ var GoogleADKPlugin = class extends BasePlugin {
25753
26779
  return { span, startTime, events: [], contextKey };
25754
26780
  };
25755
26781
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart3(
25756
- tracingChannel2,
26782
+ tracingChannel,
25757
26783
  states,
25758
26784
  createState
25759
26785
  );
@@ -25805,14 +26831,14 @@ var GoogleADKPlugin = class extends BasePlugin {
25805
26831
  states.delete(event);
25806
26832
  }
25807
26833
  };
25808
- tracingChannel2.subscribe(handlers);
26834
+ tracingChannel.subscribe(handlers);
25809
26835
  this.unsubscribers.push(() => {
25810
26836
  unbindCurrentSpanStore?.();
25811
- tracingChannel2.unsubscribe(handlers);
26837
+ tracingChannel.unsubscribe(handlers);
25812
26838
  });
25813
26839
  }
25814
26840
  subscribeToAgentRunAsync() {
25815
- const tracingChannel2 = googleADKChannels.agentRunAsync.tracingChannel();
26841
+ const tracingChannel = googleADKChannels.agentRunAsync.tracingChannel();
25816
26842
  const states = /* @__PURE__ */ new WeakMap();
25817
26843
  const createState = (event) => {
25818
26844
  const parentContext = event.arguments[0];
@@ -25823,18 +26849,23 @@ var GoogleADKPlugin = class extends BasePlugin {
25823
26849
  this.activeRunnerSpans
25824
26850
  );
25825
26851
  const contextKey = extractInvocationContextKey(parentContext);
25826
- const span = startSpan({
25827
- name: agentName ? `Agent: ${agentName}` : "Google ADK Agent",
25828
- spanAttributes: {
25829
- type: "task" /* TASK */
25830
- },
25831
- ...runnerParentSpan ? {
25832
- parentSpanIds: {
25833
- spanId: runnerParentSpan.spanId,
25834
- rootSpanId: runnerParentSpan.rootSpanId
25835
- }
25836
- } : {}
25837
- });
26852
+ const span = startSpan(
26853
+ withSpanInstrumentationName(
26854
+ {
26855
+ name: agentName ? `Agent: ${agentName}` : "Google ADK Agent",
26856
+ spanAttributes: {
26857
+ type: "task" /* TASK */
26858
+ },
26859
+ ...runnerParentSpan ? {
26860
+ parentSpanIds: {
26861
+ spanId: runnerParentSpan.spanId,
26862
+ rootSpanId: runnerParentSpan.rootSpanId
26863
+ }
26864
+ } : {}
26865
+ },
26866
+ INSTRUMENTATION_NAMES.GOOGLE_ADK
26867
+ )
26868
+ );
25838
26869
  const startTime = getCurrentUnixTimestamp();
25839
26870
  try {
25840
26871
  const metadata = {
@@ -25856,7 +26887,7 @@ var GoogleADKPlugin = class extends BasePlugin {
25856
26887
  return { span, startTime, events: [], contextKey, name: agentName };
25857
26888
  };
25858
26889
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart3(
25859
- tracingChannel2,
26890
+ tracingChannel,
25860
26891
  states,
25861
26892
  createState
25862
26893
  );
@@ -25908,14 +26939,14 @@ var GoogleADKPlugin = class extends BasePlugin {
25908
26939
  states.delete(event);
25909
26940
  }
25910
26941
  };
25911
- tracingChannel2.subscribe(handlers);
26942
+ tracingChannel.subscribe(handlers);
25912
26943
  this.unsubscribers.push(() => {
25913
26944
  unbindCurrentSpanStore?.();
25914
- tracingChannel2.unsubscribe(handlers);
26945
+ tracingChannel.unsubscribe(handlers);
25915
26946
  });
25916
26947
  }
25917
26948
  subscribeToToolRunAsync() {
25918
- const tracingChannel2 = googleADKChannels.toolRunAsync.tracingChannel();
26949
+ const tracingChannel = googleADKChannels.toolRunAsync.tracingChannel();
25919
26950
  const states = /* @__PURE__ */ new WeakMap();
25920
26951
  const handlers = {
25921
26952
  start: (event) => {
@@ -25927,22 +26958,27 @@ var GoogleADKPlugin = class extends BasePlugin {
25927
26958
  this.activeAgentSpans,
25928
26959
  this.activeRunnerSpans
25929
26960
  );
25930
- const createSpan = () => startSpan({
25931
- name: toolName ? `tool: ${toolName}` : "Google ADK Tool",
25932
- spanAttributes: {
25933
- type: "tool" /* TOOL */
25934
- },
25935
- event: {
25936
- input: req.args,
25937
- metadata: {
25938
- provider: "google-adk",
25939
- ...toolName && { "google_adk.tool_name": toolName },
25940
- ...extractToolCallId(req) && {
25941
- "google_adk.tool_call_id": extractToolCallId(req)
26961
+ const createSpan = () => startSpan(
26962
+ withSpanInstrumentationName(
26963
+ {
26964
+ name: toolName ? `tool: ${toolName}` : "Google ADK Tool",
26965
+ spanAttributes: {
26966
+ type: "tool" /* TOOL */
26967
+ },
26968
+ event: {
26969
+ input: req.args,
26970
+ metadata: {
26971
+ provider: "google-adk",
26972
+ ...toolName && { "google_adk.tool_name": toolName },
26973
+ ...extractToolCallId(req) && {
26974
+ "google_adk.tool_call_id": extractToolCallId(req)
26975
+ }
26976
+ }
25942
26977
  }
25943
- }
25944
- }
25945
- });
26978
+ },
26979
+ INSTRUMENTATION_NAMES.GOOGLE_ADK
26980
+ )
26981
+ );
25946
26982
  const span = parentSpan ? withCurrent(parentSpan, () => createSpan()) : createSpan();
25947
26983
  const startTime = getCurrentUnixTimestamp();
25948
26984
  states.set(event, { span, startTime });
@@ -25977,9 +27013,9 @@ var GoogleADKPlugin = class extends BasePlugin {
25977
27013
  states.delete(event);
25978
27014
  }
25979
27015
  };
25980
- tracingChannel2.subscribe(handlers);
27016
+ tracingChannel.subscribe(handlers);
25981
27017
  this.unsubscribers.push(() => {
25982
- tracingChannel2.unsubscribe(handlers);
27018
+ tracingChannel.unsubscribe(handlers);
25983
27019
  });
25984
27020
  }
25985
27021
  };
@@ -26055,10 +27091,10 @@ function bindAsyncIterableToCurrentSpan(stream, span) {
26055
27091
  }
26056
27092
  return stream;
26057
27093
  }
26058
- function bindCurrentSpanStoreToStart3(tracingChannel2, states, create) {
27094
+ function bindCurrentSpanStoreToStart3(tracingChannel, states, create) {
26059
27095
  const state = _internalGetGlobalState();
26060
27096
  const contextManager = state?.contextManager;
26061
- const startChannel = tracingChannel2.start;
27097
+ const startChannel = tracingChannel.start;
26062
27098
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
26063
27099
  if (!startChannel?.bindStore || !currentSpanStore) {
26064
27100
  return void 0;
@@ -26310,15 +27346,32 @@ function aggregateUsageFromEvents(events) {
26310
27346
  if (usage.thoughtsTokenCount !== void 0) {
26311
27347
  aggregated.thoughtsTokenCount = (aggregated.thoughtsTokenCount ?? 0) + usage.thoughtsTokenCount;
26312
27348
  }
27349
+ if (usage.toolUsePromptTokenCount !== void 0) {
27350
+ aggregated.toolUsePromptTokenCount = (aggregated.toolUsePromptTokenCount ?? 0) + usage.toolUsePromptTokenCount;
27351
+ }
27352
+ for (const detailsField of [
27353
+ "promptTokensDetails",
27354
+ "cacheTokensDetails",
27355
+ "candidatesTokensDetails",
27356
+ "toolUsePromptTokensDetails"
27357
+ ]) {
27358
+ const details = usage[detailsField];
27359
+ if (details !== void 0) {
27360
+ aggregated[detailsField] = [
27361
+ ...aggregated[detailsField] ?? [],
27362
+ ...details
27363
+ ];
27364
+ }
27365
+ }
26313
27366
  }
26314
27367
  return hasUsage ? aggregated : void 0;
26315
27368
  }
26316
27369
  function populateUsageMetrics2(metrics, usage) {
26317
- if (usage.promptTokenCount !== void 0) {
26318
- metrics.prompt_tokens = usage.promptTokenCount;
27370
+ if (usage.promptTokenCount !== void 0 || usage.toolUsePromptTokenCount !== void 0) {
27371
+ metrics.prompt_tokens = (usage.promptTokenCount ?? 0) + (usage.toolUsePromptTokenCount ?? 0);
26319
27372
  }
26320
- if (usage.candidatesTokenCount !== void 0) {
26321
- metrics.completion_tokens = usage.candidatesTokenCount;
27373
+ if (usage.candidatesTokenCount !== void 0 || usage.thoughtsTokenCount !== void 0) {
27374
+ metrics.completion_tokens = (usage.candidatesTokenCount ?? 0) + (usage.thoughtsTokenCount ?? 0);
26322
27375
  }
26323
27376
  if (usage.totalTokenCount !== void 0) {
26324
27377
  metrics.tokens = usage.totalTokenCount;
@@ -26329,6 +27382,19 @@ function populateUsageMetrics2(metrics, usage) {
26329
27382
  if (usage.thoughtsTokenCount !== void 0) {
26330
27383
  metrics.completion_reasoning_tokens = usage.thoughtsTokenCount;
26331
27384
  }
27385
+ for (const detail of usage.promptTokensDetails ?? []) {
27386
+ if (detail.modality === "AUDIO" && detail.tokenCount !== void 0) {
27387
+ metrics.prompt_audio_tokens = (metrics.prompt_audio_tokens ?? 0) + detail.tokenCount;
27388
+ }
27389
+ }
27390
+ for (const detail of usage.candidatesTokensDetails ?? []) {
27391
+ if (detail.modality === "AUDIO" && detail.tokenCount !== void 0) {
27392
+ metrics.completion_audio_tokens = (metrics.completion_audio_tokens ?? 0) + detail.tokenCount;
27393
+ }
27394
+ if (detail.modality === "IMAGE" && detail.tokenCount !== void 0) {
27395
+ metrics.completion_image_tokens = (metrics.completion_image_tokens ?? 0) + detail.tokenCount;
27396
+ }
27397
+ }
26332
27398
  }
26333
27399
  function cleanMetrics4(metrics) {
26334
27400
  const cleaned = {};
@@ -27785,10 +28851,10 @@ var GenkitPlugin = class extends BasePlugin {
27785
28851
  this.subscribeToActionStream();
27786
28852
  }
27787
28853
  subscribeToActionRun() {
27788
- const tracingChannel2 = genkitChannels.actionRun.tracingChannel();
28854
+ const tracingChannel = genkitChannels.actionRun.tracingChannel();
27789
28855
  const states = /* @__PURE__ */ new WeakMap();
27790
28856
  const unbindCurrentSpanStore = bindActionCurrentSpanStoreToStart(
27791
- tracingChannel2,
28857
+ tracingChannel,
27792
28858
  states,
27793
28859
  (event) => startActionRunSpan(event)
27794
28860
  );
@@ -27825,17 +28891,17 @@ var GenkitPlugin = class extends BasePlugin {
27825
28891
  states.delete(event);
27826
28892
  }
27827
28893
  };
27828
- tracingChannel2.subscribe(handlers);
28894
+ tracingChannel.subscribe(handlers);
27829
28895
  this.unsubscribers.push(() => {
27830
28896
  unbindCurrentSpanStore?.();
27831
- tracingChannel2.unsubscribe(handlers);
28897
+ tracingChannel.unsubscribe(handlers);
27832
28898
  });
27833
28899
  }
27834
28900
  subscribeToActionSpan() {
27835
- const tracingChannel2 = genkitCoreChannels.actionSpan.tracingChannel();
28901
+ const tracingChannel = genkitCoreChannels.actionSpan.tracingChannel();
27836
28902
  const states = /* @__PURE__ */ new WeakMap();
27837
28903
  const unbindCurrentSpanStore = bindActionCurrentSpanStoreToStart(
27838
- tracingChannel2,
28904
+ tracingChannel,
27839
28905
  states,
27840
28906
  (event) => startActionSpan(event)
27841
28907
  );
@@ -27873,10 +28939,10 @@ var GenkitPlugin = class extends BasePlugin {
27873
28939
  states.delete(event);
27874
28940
  }
27875
28941
  };
27876
- tracingChannel2.subscribe(handlers);
28942
+ tracingChannel.subscribe(handlers);
27877
28943
  this.unsubscribers.push(() => {
27878
28944
  unbindCurrentSpanStore?.();
27879
- tracingChannel2.unsubscribe(handlers);
28945
+ tracingChannel.unsubscribe(handlers);
27880
28946
  });
27881
28947
  }
27882
28948
  subscribeToActionStream() {
@@ -27916,16 +28982,21 @@ function startActionSpanState(args) {
27916
28982
  if (!shouldTraceAction(args.metadata, args.runStepName)) {
27917
28983
  return void 0;
27918
28984
  }
27919
- const span = startSpan({
27920
- name: actionSpanName(args.metadata, args.runStepName),
27921
- spanAttributes: {
27922
- type: actionSpanType(args.metadata)
27923
- }
27924
- });
27925
- const startTime = getCurrentUnixTimestamp();
27926
- span.log({
27927
- input: args.input,
27928
- metadata: actionMetadataForLog(args.metadata, args.runStepName)
28985
+ const span = startSpan(
28986
+ withSpanInstrumentationName(
28987
+ {
28988
+ name: actionSpanName(args.metadata, args.runStepName),
28989
+ spanAttributes: {
28990
+ type: actionSpanType(args.metadata)
28991
+ }
28992
+ },
28993
+ INSTRUMENTATION_NAMES.GENKIT
28994
+ )
28995
+ );
28996
+ const startTime = getCurrentUnixTimestamp();
28997
+ span.log({
28998
+ input: args.input,
28999
+ metadata: actionMetadataForLog(args.metadata, args.runStepName)
27929
29000
  });
27930
29001
  return { span, startTime };
27931
29002
  }
@@ -27940,10 +29011,10 @@ function ensureActionSpanState(states, event, create) {
27940
29011
  }
27941
29012
  return created;
27942
29013
  }
27943
- function bindActionCurrentSpanStoreToStart(tracingChannel2, states, create) {
29014
+ function bindActionCurrentSpanStoreToStart(tracingChannel, states, create) {
27944
29015
  const state = _internalGetGlobalState();
27945
29016
  const contextManager = state?.contextManager;
27946
- const startChannel = tracingChannel2.start;
29017
+ const startChannel = tracingChannel.start;
27947
29018
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
27948
29019
  if (!startChannel?.bindStore || !currentSpanStore) {
27949
29020
  return void 0;
@@ -28370,11 +29441,16 @@ async function handleTurnStart(state, agentId) {
28370
29441
  return;
28371
29442
  }
28372
29443
  const parentId = await getParentIdForAgent(state, agentId);
28373
- const span = startSpan({
28374
- name: "Copilot Turn",
28375
- parent: parentId,
28376
- spanAttributes: { type: "task" /* TASK */ }
28377
- });
29444
+ const span = startSpan(
29445
+ withSpanInstrumentationName(
29446
+ {
29447
+ name: "Copilot Turn",
29448
+ parent: parentId,
29449
+ spanAttributes: { type: "task" /* TASK */ }
29450
+ },
29451
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
29452
+ )
29453
+ );
28378
29454
  const pendingUserMessage = state.pendingUserMessages.get(key);
28379
29455
  if (pendingUserMessage) {
28380
29456
  span.log({ input: pendingUserMessage });
@@ -28405,11 +29481,16 @@ async function handleUsage(state, agentId, usage) {
28405
29481
  const parentId = turn ? await turn.id : await state.session.id;
28406
29482
  const content = state.currentMessageContent.get(key);
28407
29483
  const { metrics, metadata } = extractMetricsFromUsage(usage);
28408
- const llmSpan = startSpan({
28409
- name: "github.copilot.llm",
28410
- parent: parentId,
28411
- spanAttributes: { type: "llm" /* LLM */ }
28412
- });
29484
+ const llmSpan = startSpan(
29485
+ withSpanInstrumentationName(
29486
+ {
29487
+ name: "github.copilot.llm",
29488
+ parent: parentId,
29489
+ spanAttributes: { type: "llm" /* LLM */ }
29490
+ },
29491
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
29492
+ )
29493
+ );
28413
29494
  llmSpan.log({
28414
29495
  output: content ?? void 0,
28415
29496
  metadata,
@@ -28435,11 +29516,16 @@ async function handleToolStart(state, agentId, toolCallId, toolName, args, mcpSe
28435
29516
  }
28436
29517
  const parentId = await getToolParentId(state, agentId);
28437
29518
  const displayName = mcpServerName ? `tool: ${mcpServerName}/${toolName}` : `tool: ${toolName}`;
28438
- const span = startSpan({
28439
- name: displayName,
28440
- parent: parentId,
28441
- spanAttributes: { type: "tool" /* TOOL */ }
28442
- });
29519
+ const span = startSpan(
29520
+ withSpanInstrumentationName(
29521
+ {
29522
+ name: displayName,
29523
+ parent: parentId,
29524
+ spanAttributes: { type: "tool" /* TOOL */ }
29525
+ },
29526
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
29527
+ )
29528
+ );
28443
29529
  const metadata = {
28444
29530
  "gen_ai.tool.name": toolName,
28445
29531
  "gen_ai.tool.call.id": toolCallId
@@ -28475,11 +29561,16 @@ async function handleSubagentStarted(state, agentId, toolCallId, agentDisplayNam
28475
29561
  }
28476
29562
  const tool = state.activeTools.get(toolCallId);
28477
29563
  const parentId = tool ? await tool.id : await state.session.id;
28478
- const span = startSpan({
28479
- name: `Agent: ${agentDisplayName}`,
28480
- parent: parentId,
28481
- spanAttributes: { type: "task" /* TASK */ }
28482
- });
29564
+ const span = startSpan(
29565
+ withSpanInstrumentationName(
29566
+ {
29567
+ name: `Agent: ${agentDisplayName}`,
29568
+ parent: parentId,
29569
+ spanAttributes: { type: "task" /* TASK */ }
29570
+ },
29571
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
29572
+ )
29573
+ );
28483
29574
  span.log({
28484
29575
  metadata: {
28485
29576
  "github_copilot.agent_name": agentDisplayName,
@@ -28705,10 +29796,15 @@ function makeSessionHandlers(sessionStates, configArgIndex, includeProviderMetad
28705
29796
  if (!config || typeof config !== "object") {
28706
29797
  return;
28707
29798
  }
28708
- const sessionSpan = startSpan({
28709
- name: "Copilot Session",
28710
- spanAttributes: { type: "task" /* TASK */ }
28711
- });
29799
+ const sessionSpan = startSpan(
29800
+ withSpanInstrumentationName(
29801
+ {
29802
+ name: "Copilot Session",
29803
+ spanAttributes: { type: "task" /* TASK */ }
29804
+ },
29805
+ INSTRUMENTATION_NAMES.GITHUB_COPILOT
29806
+ )
29807
+ );
28712
29808
  const metadata = {};
28713
29809
  if (config.model) {
28714
29810
  metadata["github_copilot.model"] = config.model;
@@ -28810,7 +29906,7 @@ var LangChainPlugin = class extends BasePlugin {
28810
29906
  this.injectedManagers = /* @__PURE__ */ new WeakSet();
28811
29907
  }
28812
29908
  subscribeToConfigure(channel) {
28813
- const tracingChannel2 = channel.tracingChannel();
29909
+ const tracingChannel = channel.tracingChannel();
28814
29910
  const handlers = {
28815
29911
  start: (event) => {
28816
29912
  injectHandlerIntoArguments(event.arguments);
@@ -28819,9 +29915,9 @@ var LangChainPlugin = class extends BasePlugin {
28819
29915
  this.injectHandler(event.result);
28820
29916
  }
28821
29917
  };
28822
- tracingChannel2.subscribe(handlers);
29918
+ tracingChannel.subscribe(handlers);
28823
29919
  this.unsubscribers.push(() => {
28824
- tracingChannel2.unsubscribe(handlers);
29920
+ tracingChannel.unsubscribe(handlers);
28825
29921
  });
28826
29922
  }
28827
29923
  injectHandler(result) {
@@ -29042,25 +30138,30 @@ var LangSmithPlugin = class extends BasePlugin {
29042
30138
  const traceId = stringValue2(ownValue(run, "trace_id")) ?? id;
29043
30139
  const parentId = stringValue2(ownValue(run, "parent_run_id")) ?? stringValue2(ownValue(ownValue(run, "parent_run"), "id"));
29044
30140
  const startTime = timestampSeconds(ownValue(run, "start_time"));
29045
- return startSpan({
29046
- name: stringValue2(ownValue(run, "name")) ?? "LangSmith run",
29047
- spanId: id,
29048
- parentSpanIds: {
29049
- parentSpanIds: parentId ? [parentId] : [],
29050
- rootSpanId: traceId
29051
- },
29052
- spanAttributes: {
29053
- type: mapRunType(ownValue(run, "run_type"))
29054
- },
29055
- ...startTime === void 0 ? {} : { startTime },
29056
- event: { id }
29057
- });
30141
+ return startSpan(
30142
+ withSpanInstrumentationName(
30143
+ {
30144
+ name: stringValue2(ownValue(run, "name")) ?? "LangSmith run",
30145
+ spanId: id,
30146
+ parentSpanIds: {
30147
+ parentSpanIds: parentId ? [parentId] : [],
30148
+ rootSpanId: traceId
30149
+ },
30150
+ spanAttributes: {
30151
+ type: mapRunType(ownValue(run, "run_type"))
30152
+ },
30153
+ ...startTime === void 0 ? {} : { startTime },
30154
+ event: { id }
30155
+ },
30156
+ INSTRUMENTATION_NAMES.LANGSMITH
30157
+ )
30158
+ );
29058
30159
  }
29059
30160
  logRun(span, run, previous, includeOutput) {
29060
30161
  const inputs = preferOwnValue(run, previous, "inputs");
29061
30162
  const outputs = preferOwnValue(run, previous, "outputs");
29062
30163
  const error = errorMessage(preferOwnValue(run, previous, "error"));
29063
- const metadata = extractMetadata(run, previous);
30164
+ const metadata = extractMetadata2(run, previous);
29064
30165
  const tags = extractTags(preferOwnValue(run, previous, "tags"));
29065
30166
  const metrics = extractMetrics(run, previous);
29066
30167
  span.log({
@@ -29165,7 +30266,7 @@ function mapRunType(runType) {
29165
30266
  return "task" /* TASK */;
29166
30267
  }
29167
30268
  }
29168
- function extractMetadata(run, previous) {
30269
+ function extractMetadata2(run, previous) {
29169
30270
  const extra = preferOwnValue(run, previous, "extra");
29170
30271
  const rawMetadata = ownValue(extra, "metadata");
29171
30272
  if (!isRecord2(rawMetadata)) {
@@ -29385,14 +30486,19 @@ function startPiPromptRun(event, onFinalize) {
29385
30486
  ...session.model?.id || agent.state?.model?.id ? { model: session.model?.id ?? agent.state?.model?.id } : {},
29386
30487
  ...event.moduleVersion ? { "pi_coding_agent.version": event.moduleVersion } : {}
29387
30488
  };
29388
- const span = startSpan({
29389
- event: {
29390
- input: extractPromptInput(event.arguments[0], event.arguments[1]),
29391
- metadata
29392
- },
29393
- name: "AgentSession.prompt",
29394
- spanAttributes: { type: "task" /* TASK */ }
29395
- });
30489
+ const span = startSpan(
30490
+ withSpanInstrumentationName(
30491
+ {
30492
+ event: {
30493
+ input: extractPromptInput(event.arguments[0], event.arguments[1]),
30494
+ metadata
30495
+ },
30496
+ name: "AgentSession.prompt",
30497
+ spanAttributes: { type: "task" /* TASK */ }
30498
+ },
30499
+ INSTRUMENTATION_NAMES.PI_CODING_AGENT
30500
+ )
30501
+ );
29396
30502
  const streamPatchState = installPiStreamPatch(agent);
29397
30503
  const options = event.arguments[1];
29398
30504
  const promptText = event.arguments[0];
@@ -29562,15 +30668,20 @@ async function startPiLlmSpan(state, model, context, options) {
29562
30668
  ...extractToolMetadata(context.tools),
29563
30669
  "pi_coding_agent.operation": "agent.streamFn"
29564
30670
  };
29565
- const span = startSpan({
29566
- event: {
29567
- input: processInputAttachments(normalizePiContextInput(context)),
29568
- metadata
29569
- },
29570
- name: getLlmSpanName(model),
29571
- parent: await state.span.export(),
29572
- spanAttributes: { type: "llm" /* LLM */ }
29573
- });
30671
+ const span = startSpan(
30672
+ withSpanInstrumentationName(
30673
+ {
30674
+ event: {
30675
+ input: processInputAttachments(normalizePiContextInput(context)),
30676
+ metadata
30677
+ },
30678
+ name: getLlmSpanName(model),
30679
+ parent: await state.span.export(),
30680
+ spanAttributes: { type: "llm" /* LLM */ }
30681
+ },
30682
+ INSTRUMENTATION_NAMES.PI_CODING_AGENT
30683
+ )
30684
+ );
29574
30685
  const llmState = {
29575
30686
  finalized: false,
29576
30687
  metadata,
@@ -29738,15 +30849,20 @@ async function startPiToolSpan(state, event) {
29738
30849
  "pi_coding_agent.tool.name": event.toolName
29739
30850
  };
29740
30851
  try {
29741
- const span = startSpan({
29742
- event: {
29743
- input: event.args,
29744
- metadata
29745
- },
29746
- name: event.toolName || "tool",
29747
- parent: await state.span.export(),
29748
- spanAttributes: { type: "tool" /* TOOL */ }
29749
- });
30852
+ const span = startSpan(
30853
+ withSpanInstrumentationName(
30854
+ {
30855
+ event: {
30856
+ input: event.args,
30857
+ metadata
30858
+ },
30859
+ name: event.toolName || "tool",
30860
+ parent: await state.span.export(),
30861
+ spanAttributes: { type: "tool" /* TOOL */ }
30862
+ },
30863
+ INSTRUMENTATION_NAMES.PI_CODING_AGENT
30864
+ )
30865
+ );
29750
30866
  state.activeToolSpans.set(event.toolCallId, {
29751
30867
  restoreAutoInstrumentation,
29752
30868
  span
@@ -30249,9 +31365,9 @@ var StrandsAgentSDKPlugin = class extends BasePlugin {
30249
31365
  });
30250
31366
  }
30251
31367
  subscribeToMultiAgentStream(channel, operation) {
30252
- const tracingChannel2 = channel.tracingChannel();
31368
+ const tracingChannel = channel.tracingChannel();
30253
31369
  const states = /* @__PURE__ */ new WeakMap();
30254
- const unbindAutoInstrumentationSuppression = bindAutoInstrumentationSuppressionToStart(tracingChannel2);
31370
+ const unbindAutoInstrumentationSuppression = bindAutoInstrumentationSuppressionToStart(tracingChannel);
30255
31371
  const handlers = {
30256
31372
  start: (event) => {
30257
31373
  const state = startMultiAgentStream(
@@ -30305,10 +31421,10 @@ var StrandsAgentSDKPlugin = class extends BasePlugin {
30305
31421
  states.delete(event);
30306
31422
  }
30307
31423
  };
30308
- tracingChannel2.subscribe(handlers);
31424
+ tracingChannel.subscribe(handlers);
30309
31425
  this.unsubscribers.push(() => {
30310
31426
  unbindAutoInstrumentationSuppression?.();
30311
- tracingChannel2.unsubscribe(handlers);
31427
+ tracingChannel.unsubscribe(handlers);
30312
31428
  });
30313
31429
  }
30314
31430
  };
@@ -30330,22 +31446,32 @@ function startAgentStream(event, activeChildParents) {
30330
31446
  );
30331
31447
  const span = parentSpan ? withCurrent(
30332
31448
  parentSpan,
30333
- () => startSpan({
30334
- event: {
30335
- input,
30336
- metadata
31449
+ () => startSpan(
31450
+ withSpanInstrumentationName(
31451
+ {
31452
+ event: {
31453
+ input,
31454
+ metadata
31455
+ },
31456
+ name: formatAgentSpanName(agent),
31457
+ spanAttributes: { type: "task" /* TASK */ }
31458
+ },
31459
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
31460
+ )
31461
+ )
31462
+ ) : startSpan(
31463
+ withSpanInstrumentationName(
31464
+ {
31465
+ event: {
31466
+ input,
31467
+ metadata
31468
+ },
31469
+ name: formatAgentSpanName(agent),
31470
+ spanAttributes: { type: "task" /* TASK */ }
30337
31471
  },
30338
- name: formatAgentSpanName(agent),
30339
- spanAttributes: { type: "task" /* TASK */ }
30340
- })
30341
- ) : startSpan({
30342
- event: {
30343
- input,
30344
- metadata
30345
- },
30346
- name: formatAgentSpanName(agent),
30347
- spanAttributes: { type: "task" /* TASK */ }
30348
- });
31472
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
31473
+ )
31474
+ );
30349
31475
  return {
30350
31476
  activeTools: /* @__PURE__ */ new Map(),
30351
31477
  attachmentCache,
@@ -30367,22 +31493,32 @@ function startMultiAgentStream(event, operation, activeChildParents) {
30367
31493
  const input = processStrandsInputAttachments(event.arguments[0]);
30368
31494
  const span = parentSpan ? withCurrent(
30369
31495
  parentSpan,
30370
- () => startSpan({
30371
- event: {
30372
- input,
30373
- metadata
31496
+ () => startSpan(
31497
+ withSpanInstrumentationName(
31498
+ {
31499
+ event: {
31500
+ input,
31501
+ metadata
31502
+ },
31503
+ name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
31504
+ spanAttributes: { type: "task" /* TASK */ }
31505
+ },
31506
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
31507
+ )
31508
+ )
31509
+ ) : startSpan(
31510
+ withSpanInstrumentationName(
31511
+ {
31512
+ event: {
31513
+ input,
31514
+ metadata
31515
+ },
31516
+ name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
31517
+ spanAttributes: { type: "task" /* TASK */ }
30374
31518
  },
30375
- name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
30376
- spanAttributes: { type: "task" /* TASK */ }
30377
- })
30378
- ) : startSpan({
30379
- event: {
30380
- input,
30381
- metadata
30382
- },
30383
- name: operation === "Graph.stream" ? "Strands Graph" : "Strands Swarm",
30384
- spanAttributes: { type: "task" /* TASK */ }
30385
- });
31519
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
31520
+ )
31521
+ );
30386
31522
  return {
30387
31523
  activeNodes: /* @__PURE__ */ new Map(),
30388
31524
  finalized: false,
@@ -30471,6 +31607,15 @@ function handleMultiAgentStreamEvent(state, event, activeChildParents) {
30471
31607
  logInstrumentationError5("Strands Agent SDK multi-agent event", error);
30472
31608
  }
30473
31609
  }
31610
+ function buildModelSpanInput(event, attachmentCache) {
31611
+ const systemPrompt = typeof event.agent?.systemPrompt === "string" && event.agent.systemPrompt.length > 0 ? event.agent.systemPrompt : void 0;
31612
+ const processedMessages = Array.isArray(event.agent?.messages) ? processStrandsInputAttachments(event.agent.messages, attachmentCache) : void 0;
31613
+ if (!systemPrompt) {
31614
+ return processedMessages;
31615
+ }
31616
+ const systemMessage = { role: "system", content: systemPrompt };
31617
+ return Array.isArray(processedMessages) ? [systemMessage, ...processedMessages] : [systemMessage];
31618
+ }
30474
31619
  function startModelSpan(state, event) {
30475
31620
  if (state.activeModel) {
30476
31621
  finalizeModelSpan(state);
@@ -30484,17 +31629,19 @@ function startModelSpan(state, event) {
30484
31629
  };
30485
31630
  const span = withCurrent(
30486
31631
  state.span,
30487
- () => startSpan({
30488
- event: {
30489
- input: Array.isArray(event.agent?.messages) ? processStrandsInputAttachments(
30490
- event.agent.messages,
30491
- state.attachmentCache
30492
- ) : void 0,
30493
- metadata
30494
- },
30495
- name: formatModelSpanName(model),
30496
- spanAttributes: { type: "llm" /* LLM */ }
30497
- })
31632
+ () => startSpan(
31633
+ withSpanInstrumentationName(
31634
+ {
31635
+ event: {
31636
+ input: buildModelSpanInput(event, state.attachmentCache),
31637
+ metadata
31638
+ },
31639
+ name: formatModelSpanName(model),
31640
+ spanAttributes: { type: "llm" /* LLM */ }
31641
+ },
31642
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
31643
+ )
31644
+ )
30498
31645
  );
30499
31646
  state.activeModel = {
30500
31647
  metadata,
@@ -30546,20 +31693,25 @@ function startToolSpan2(state, event) {
30546
31693
  const name = extractToolName3(toolUse, event.tool);
30547
31694
  const span = withCurrent(
30548
31695
  state.span,
30549
- () => startSpan({
30550
- event: {
30551
- input: toolUse?.input,
30552
- metadata: {
30553
- "gen_ai.tool.call.id": toolUse?.toolUseId,
30554
- "gen_ai.tool.name": name,
30555
- "strands.operation": "tool.call",
30556
- "strands.tool.name": name,
30557
- provider: "strands"
30558
- }
30559
- },
30560
- name: `tool: ${name}`,
30561
- spanAttributes: { type: "tool" /* TOOL */ }
30562
- })
31696
+ () => startSpan(
31697
+ withSpanInstrumentationName(
31698
+ {
31699
+ event: {
31700
+ input: toolUse?.input,
31701
+ metadata: {
31702
+ "gen_ai.tool.call.id": toolUse?.toolUseId,
31703
+ "gen_ai.tool.name": name,
31704
+ "strands.operation": "tool.call",
31705
+ "strands.tool.name": name,
31706
+ provider: "strands"
31707
+ }
31708
+ },
31709
+ name: `tool: ${name}`,
31710
+ spanAttributes: { type: "tool" /* TOOL */ }
31711
+ },
31712
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
31713
+ )
31714
+ )
30563
31715
  );
30564
31716
  state.activeTools.set(key, {
30565
31717
  span,
@@ -30630,11 +31782,16 @@ function startNodeSpan(state, event, activeChildParents) {
30630
31782
  };
30631
31783
  const span = withCurrent(
30632
31784
  state.span,
30633
- () => startSpan({
30634
- event: { metadata },
30635
- name: `node: ${nodeId}`,
30636
- spanAttributes: { type: "task" /* TASK */ }
30637
- })
31785
+ () => startSpan(
31786
+ withSpanInstrumentationName(
31787
+ {
31788
+ event: { metadata },
31789
+ name: `node: ${nodeId}`,
31790
+ spanAttributes: { type: "task" /* TASK */ }
31791
+ },
31792
+ INSTRUMENTATION_NAMES.STRANDS_AGENT_SDK
31793
+ )
31794
+ )
30638
31795
  );
30639
31796
  const nodeState = {
30640
31797
  ...child ? { child } : {},
@@ -31116,6 +32273,527 @@ function logInstrumentationError5(context, error) {
31116
32273
  debugLogger.debug(`${context}:`, error);
31117
32274
  }
31118
32275
 
32276
+ // src/instrumentation/plugins/cloudflare-ai-chat-instrumentation.ts
32277
+ var wrappedTurnRunners = /* @__PURE__ */ new WeakSet();
32278
+ var wrappedResponseHooks = /* @__PURE__ */ new WeakSet();
32279
+ function instrumentCloudflareAIChatAgent(agent) {
32280
+ try {
32281
+ const original = Reflect.get(agent, "_runExclusiveChatTurn");
32282
+ if (typeof original !== "function" || wrappedTurnRunners.has(original)) {
32283
+ return agent;
32284
+ }
32285
+ const wrapped = async function(...args) {
32286
+ return cloudflareAIChatChannels.runExclusiveChatTurn.tracePromise(
32287
+ () => Reflect.apply(original, this, args),
32288
+ {
32289
+ arguments: args,
32290
+ self: this
32291
+ }
32292
+ );
32293
+ };
32294
+ wrappedTurnRunners.add(wrapped);
32295
+ defineWrappedMethod(agent, "_runExclusiveChatTurn", original, wrapped);
32296
+ } catch (error) {
32297
+ debugLogger.debug("Failed to wrap @cloudflare/ai-chat turn runner:", error);
32298
+ }
32299
+ return agent;
32300
+ }
32301
+ function instrumentCloudflareAIChatResponseHook(agent) {
32302
+ try {
32303
+ const original = Reflect.get(agent, "onChatResponse");
32304
+ if (typeof original !== "function" || wrappedResponseHooks.has(original)) {
32305
+ return;
32306
+ }
32307
+ const wrapped = function(result) {
32308
+ const args = [result];
32309
+ return cloudflareAIChatChannels.onChatResponse.traceSync(
32310
+ () => Reflect.apply(original, this, args),
32311
+ {
32312
+ arguments: args,
32313
+ self: this
32314
+ }
32315
+ );
32316
+ };
32317
+ wrappedResponseHooks.add(wrapped);
32318
+ defineWrappedMethod(agent, "onChatResponse", original, wrapped);
32319
+ } catch (error) {
32320
+ debugLogger.debug(
32321
+ "Failed to wrap @cloudflare/ai-chat response hook:",
32322
+ error
32323
+ );
32324
+ }
32325
+ }
32326
+ function defineWrappedMethod(target, property, original, wrapped) {
32327
+ const ownDescriptor = Object.getOwnPropertyDescriptor(target, property);
32328
+ Object.defineProperty(target, property, {
32329
+ configurable: ownDescriptor?.configurable ?? true,
32330
+ enumerable: ownDescriptor?.enumerable ?? false,
32331
+ value: wrapped,
32332
+ writable: ownDescriptor && "writable" in ownDescriptor ? ownDescriptor.writable : true
32333
+ });
32334
+ try {
32335
+ Object.defineProperty(wrapped, "name", {
32336
+ configurable: true,
32337
+ value: original.name
32338
+ });
32339
+ } catch {
32340
+ }
32341
+ }
32342
+
32343
+ // src/instrumentation/plugins/cloudflare-ai-chat-plugin.ts
32344
+ var BLOCKED_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
32345
+ var RESPONSE_STATE_RETENTION_MS = 6e4;
32346
+ var CloudflareAIChatPlugin = class extends BasePlugin {
32347
+ activeStates = /* @__PURE__ */ new Set();
32348
+ activeTurns = /* @__PURE__ */ new WeakMap();
32349
+ eventStates = /* @__PURE__ */ new WeakMap();
32350
+ onEnable() {
32351
+ this.subscribeToResponseHook();
32352
+ this.subscribeToTurnRunner();
32353
+ }
32354
+ onDisable() {
32355
+ for (const unsubscribe of this.unsubscribers) {
32356
+ unsubscribe();
32357
+ }
32358
+ this.unsubscribers = [];
32359
+ for (const state of this.activeStates) {
32360
+ this.cleanupState(state);
32361
+ }
32362
+ this.activeStates.clear();
32363
+ }
32364
+ subscribeToTurnRunner() {
32365
+ const tracingChannel = cloudflareAIChatChannels.runExclusiveChatTurn.tracingChannel();
32366
+ const unbindCurrentSpanStore = this.bindCurrentSpanStore(tracingChannel);
32367
+ const handlers = {
32368
+ start: (event) => {
32369
+ this.ensureEventState(event);
32370
+ },
32371
+ asyncEnd: (event) => {
32372
+ this.finishEvent(event);
32373
+ },
32374
+ error: (event) => {
32375
+ this.finishEvent(event, event.error);
32376
+ }
32377
+ };
32378
+ tracingChannel.subscribe(handlers);
32379
+ this.unsubscribers.push(() => {
32380
+ unbindCurrentSpanStore?.();
32381
+ tracingChannel.unsubscribe(handlers);
32382
+ });
32383
+ }
32384
+ subscribeToResponseHook() {
32385
+ const tracingChannel = cloudflareAIChatChannels.onChatResponse.tracingChannel();
32386
+ const handlers = {
32387
+ start: (event) => {
32388
+ let state;
32389
+ try {
32390
+ const agent = asObject(event.self);
32391
+ const result = event.arguments[0];
32392
+ state = agent ? this.findResponseState(
32393
+ agent,
32394
+ stringValue3(ownValue2(result, "requestId"))
32395
+ ) : void 0;
32396
+ if (!state) {
32397
+ return;
32398
+ }
32399
+ state.responseObserved = true;
32400
+ const output = serializeMessage(ownValue2(result, "message"));
32401
+ const status = stringValue3(ownValue2(result, "status"));
32402
+ const error = ownValue2(result, "error");
32403
+ const input = ownValue2(result, "continuation") === true ? state.input : serializeMessages(readProperty(agent, "messages"))?.filter(
32404
+ (message) => typeof output?.id !== "string" || message.id !== output.id
32405
+ );
32406
+ state.span.log({
32407
+ ...input !== void 0 ? { input } : {},
32408
+ ...output !== void 0 ? { output } : {},
32409
+ ...status === "error" && error !== void 0 ? { error } : {}
32410
+ });
32411
+ } catch (error) {
32412
+ debugLogger.debug(
32413
+ "Failed to process @cloudflare/ai-chat response hook:",
32414
+ error
32415
+ );
32416
+ } finally {
32417
+ if (state?.settled) {
32418
+ this.cleanupState(state);
32419
+ }
32420
+ }
32421
+ }
32422
+ };
32423
+ tracingChannel.subscribe(handlers);
32424
+ this.unsubscribers.push(() => tracingChannel.unsubscribe(handlers));
32425
+ }
32426
+ bindCurrentSpanStore(tracingChannel) {
32427
+ const globalState = _internalGetGlobalState();
32428
+ const contextManager = globalState?.contextManager;
32429
+ const startChannel = tracingChannel.start;
32430
+ const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
32431
+ if (!startChannel || !currentSpanStore || !contextManager) {
32432
+ return void 0;
32433
+ }
32434
+ startChannel.bindStore(currentSpanStore, (event) => {
32435
+ const state = this.ensureEventState(event);
32436
+ return state ? contextManager.wrapSpanForStore(state.span) : currentSpanStore.getStore();
32437
+ });
32438
+ return () => startChannel.unbindStore(currentSpanStore);
32439
+ }
32440
+ ensureEventState(event) {
32441
+ const eventKey = event;
32442
+ const known = this.eventStates.get(eventKey);
32443
+ if (known) {
32444
+ return known;
32445
+ }
32446
+ try {
32447
+ const agent = asObject(event.self);
32448
+ const requestId = stringValue3(event.arguments[0]);
32449
+ const key = requestId ?? /* @__PURE__ */ Symbol("cloudflare-ai-chat-turn");
32450
+ const activeForAgent = agent ? this.getActiveTurns(agent) : void 0;
32451
+ const existing = activeForAgent?.get(key);
32452
+ const state = existing && !existing.settled ? existing : this.createTurnState(agent, key);
32453
+ if (existing && !existing.settled) {
32454
+ state.depth += 1;
32455
+ }
32456
+ this.eventStates.set(eventKey, state);
32457
+ this.bindTurnCallback(event, agent, state);
32458
+ if (agent) {
32459
+ instrumentCloudflareAIChatResponseHook(agent);
32460
+ }
32461
+ return state;
32462
+ } catch (error) {
32463
+ debugLogger.debug(
32464
+ "Failed to start @cloudflare/ai-chat instrumentation:",
32465
+ error
32466
+ );
32467
+ return void 0;
32468
+ }
32469
+ }
32470
+ createTurnState(agent, key) {
32471
+ const span = startSpan(
32472
+ withSpanInstrumentationName(
32473
+ {
32474
+ name: "AIChatAgent.onChatMessage",
32475
+ spanAttributes: { type: "task" /* TASK */ }
32476
+ },
32477
+ INSTRUMENTATION_NAMES.CLOUDFLARE_AI_CHAT
32478
+ )
32479
+ );
32480
+ const state = {
32481
+ agent,
32482
+ depth: 1,
32483
+ ended: false,
32484
+ key,
32485
+ responseObserved: false,
32486
+ settled: false,
32487
+ span
32488
+ };
32489
+ this.activeStates.add(state);
32490
+ if (agent) {
32491
+ this.getActiveTurns(agent).set(key, state);
32492
+ }
32493
+ return state;
32494
+ }
32495
+ bindTurnCallback(event, agent, state) {
32496
+ const callback = event.arguments[1];
32497
+ if (typeof callback !== "function") {
32498
+ return;
32499
+ }
32500
+ try {
32501
+ event.arguments[1] = function(...args) {
32502
+ return withCurrent(state.span, () => {
32503
+ try {
32504
+ const input = serializeMessages(readProperty(agent, "messages"));
32505
+ if (input !== void 0 && state.input === void 0) {
32506
+ state.input = input;
32507
+ state.span.log({ input });
32508
+ }
32509
+ } catch (error) {
32510
+ debugLogger.debug(
32511
+ "Failed to capture @cloudflare/ai-chat messages:",
32512
+ error
32513
+ );
32514
+ }
32515
+ return Reflect.apply(callback, this, args);
32516
+ });
32517
+ };
32518
+ } catch (error) {
32519
+ debugLogger.debug(
32520
+ "Failed to bind @cloudflare/ai-chat turn callback context:",
32521
+ error
32522
+ );
32523
+ }
32524
+ }
32525
+ finishEvent(event, error) {
32526
+ const eventKey = event;
32527
+ const state = this.eventStates.get(eventKey);
32528
+ if (!state || state.ended) {
32529
+ return;
32530
+ }
32531
+ this.eventStates.delete(eventKey);
32532
+ if (error !== void 0 && state.pendingError === void 0) {
32533
+ state.pendingError = error;
32534
+ }
32535
+ state.depth -= 1;
32536
+ if (state.depth === 0) {
32537
+ state.settled = true;
32538
+ this.endState(state);
32539
+ if (state.responseObserved || error !== void 0) {
32540
+ this.cleanupState(state);
32541
+ } else {
32542
+ state.cleanupTimer = setTimeout(
32543
+ () => this.cleanupState(state),
32544
+ RESPONSE_STATE_RETENTION_MS
32545
+ );
32546
+ if (typeof state.cleanupTimer === "object" && state.cleanupTimer !== null && "unref" in state.cleanupTimer && typeof state.cleanupTimer.unref === "function") {
32547
+ state.cleanupTimer.unref();
32548
+ }
32549
+ }
32550
+ }
32551
+ }
32552
+ endState(state) {
32553
+ if (state.ended) {
32554
+ return;
32555
+ }
32556
+ state.ended = true;
32557
+ try {
32558
+ if (state.pendingError !== void 0) {
32559
+ state.span.log({ error: state.pendingError });
32560
+ }
32561
+ } finally {
32562
+ state.span.end();
32563
+ }
32564
+ }
32565
+ cleanupState(state) {
32566
+ if (state.cleanupTimer !== void 0) {
32567
+ clearTimeout(state.cleanupTimer);
32568
+ state.cleanupTimer = void 0;
32569
+ }
32570
+ try {
32571
+ this.endState(state);
32572
+ } finally {
32573
+ this.activeStates.delete(state);
32574
+ if (state.agent) {
32575
+ const activeForAgent = this.activeTurns.get(state.agent);
32576
+ if (activeForAgent?.get(state.key) === state) {
32577
+ activeForAgent.delete(state.key);
32578
+ }
32579
+ }
32580
+ }
32581
+ }
32582
+ getActiveTurns(agent) {
32583
+ let turns = this.activeTurns.get(agent);
32584
+ if (!turns) {
32585
+ turns = /* @__PURE__ */ new Map();
32586
+ this.activeTurns.set(agent, turns);
32587
+ }
32588
+ return turns;
32589
+ }
32590
+ findResponseState(agent, requestId) {
32591
+ const turns = this.activeTurns.get(agent);
32592
+ if (!turns) {
32593
+ return void 0;
32594
+ }
32595
+ if (requestId !== void 0) {
32596
+ return turns.get(requestId);
32597
+ }
32598
+ const active = [...turns.values()];
32599
+ return active.length === 1 ? active[0] : void 0;
32600
+ }
32601
+ };
32602
+ function asObject(value) {
32603
+ return value !== null && (typeof value === "object" || typeof value === "function") ? value : void 0;
32604
+ }
32605
+ function readProperty(value, key) {
32606
+ const object = asObject(value);
32607
+ return object ? Reflect.get(object, key) : void 0;
32608
+ }
32609
+ function ownValue2(value, key) {
32610
+ const object = asObject(value);
32611
+ if (!object) {
32612
+ return void 0;
32613
+ }
32614
+ const descriptor = Object.getOwnPropertyDescriptor(object, key);
32615
+ return descriptor && "value" in descriptor ? descriptor.value : void 0;
32616
+ }
32617
+ function stringValue3(value) {
32618
+ return typeof value === "string" ? value : void 0;
32619
+ }
32620
+ function serializeMessages(value) {
32621
+ if (!Array.isArray(value)) {
32622
+ return void 0;
32623
+ }
32624
+ return value.flatMap((message) => {
32625
+ const serialized = serializeMessage(message);
32626
+ return serialized === void 0 ? [] : [serialized];
32627
+ });
32628
+ }
32629
+ function serializeMessage(value) {
32630
+ const message = asObject(value);
32631
+ if (!message) {
32632
+ return void 0;
32633
+ }
32634
+ const serialized = [];
32635
+ const id = ownValue2(message, "id");
32636
+ const role = ownValue2(message, "role");
32637
+ const parts = ownValue2(message, "parts");
32638
+ if (typeof id === "string") {
32639
+ serialized.push(["id", id]);
32640
+ }
32641
+ if (typeof role === "string") {
32642
+ serialized.push(["role", role]);
32643
+ }
32644
+ const sanitizedParts = sanitizeLoggedValue2(parts);
32645
+ if (sanitizedParts !== void 0) {
32646
+ serialized.push(["parts", sanitizedParts]);
32647
+ }
32648
+ return serialized.length > 0 ? Object.fromEntries(serialized) : void 0;
32649
+ }
32650
+ function sanitizeLoggedValue2(value, seen = /* @__PURE__ */ new WeakSet(), depth = 0) {
32651
+ if (value === null || typeof value === "string" || typeof value === "boolean") {
32652
+ return value;
32653
+ }
32654
+ if (typeof value === "number") {
32655
+ return Number.isFinite(value) ? value : void 0;
32656
+ }
32657
+ const object = asObject(value);
32658
+ if (!object || depth >= 20 || typeof value === "function") {
32659
+ return void 0;
32660
+ }
32661
+ if (seen.has(object)) {
32662
+ return "[Circular]";
32663
+ }
32664
+ seen.add(object);
32665
+ if (Array.isArray(value)) {
32666
+ return value.map((entry) => sanitizeLoggedValue2(entry, seen, depth + 1));
32667
+ }
32668
+ const entries = [];
32669
+ for (const [key, descriptor] of Object.entries(
32670
+ Object.getOwnPropertyDescriptors(object)
32671
+ )) {
32672
+ if (BLOCKED_KEYS.has(key) || !descriptor.enumerable || !("value" in descriptor)) {
32673
+ continue;
32674
+ }
32675
+ const sanitized = sanitizeLoggedValue2(descriptor.value, seen, depth + 1);
32676
+ if (sanitized !== void 0) {
32677
+ entries.push([key, sanitized]);
32678
+ }
32679
+ }
32680
+ return Object.fromEntries(entries);
32681
+ }
32682
+
32683
+ // src/instrumentation/plugins/cloudflare-agents-plugin.ts
32684
+ var CLOUDFLARE_WORKERS_CONTEXT = {
32685
+ span_origin: {
32686
+ environment: { type: "server", name: "cloudflare_workers" }
32687
+ }
32688
+ };
32689
+ var CloudflareAgentsPlugin = class extends BasePlugin {
32690
+ onEnable() {
32691
+ const channel = cloudflareAgentsChannels.runAgentTool.tracingChannel();
32692
+ const spans = /* @__PURE__ */ new WeakMap();
32693
+ const handlers = {
32694
+ start: (event) => {
32695
+ try {
32696
+ const agentClass = event.arguments[0];
32697
+ const options = event.arguments[1];
32698
+ if (ownValue3(options, "detached")) {
32699
+ return;
32700
+ }
32701
+ const name = ownValue3(agentClass, "name");
32702
+ if (typeof name !== "string" || name.length === 0) {
32703
+ debugLogger.warn(
32704
+ "Skipping Cloudflare Agents runAgentTool span because the child agent class has no name."
32705
+ );
32706
+ return;
32707
+ }
32708
+ const span = _internalStartSpanWithContext(
32709
+ withSpanInstrumentationName(
32710
+ {
32711
+ name,
32712
+ spanAttributes: { type: "tool" /* TOOL */ },
32713
+ event: {
32714
+ input: ownValue3(options, "input")
32715
+ }
32716
+ },
32717
+ INSTRUMENTATION_NAMES.CLOUDFLARE_AGENTS
32718
+ ),
32719
+ CLOUDFLARE_WORKERS_CONTEXT
32720
+ );
32721
+ spans.set(event, span);
32722
+ } catch (error) {
32723
+ logInstrumentationError6("start", error);
32724
+ }
32725
+ },
32726
+ asyncEnd: (event) => {
32727
+ const span = spans.get(event);
32728
+ if (!span) {
32729
+ return;
32730
+ }
32731
+ spans.delete(event);
32732
+ try {
32733
+ const status = ownValue3(event.result, "status");
32734
+ if (status === "completed") {
32735
+ span.log({ output: ownValue3(event.result, "output") });
32736
+ } else {
32737
+ const error = ownValue3(event.result, "error");
32738
+ if (typeof error === "string") {
32739
+ span.log({ error });
32740
+ }
32741
+ }
32742
+ } catch (error) {
32743
+ logInstrumentationError6("completion", error);
32744
+ } finally {
32745
+ safelyEndSpan(span);
32746
+ }
32747
+ },
32748
+ error: (event) => {
32749
+ const span = spans.get(event);
32750
+ if (!span) {
32751
+ return;
32752
+ }
32753
+ spans.delete(event);
32754
+ try {
32755
+ span.log({ error: event.error });
32756
+ } catch (error) {
32757
+ logInstrumentationError6("rejection", error);
32758
+ } finally {
32759
+ safelyEndSpan(span);
32760
+ }
32761
+ }
32762
+ };
32763
+ channel.subscribe(handlers);
32764
+ this.unsubscribers.push(() => channel.unsubscribe(handlers));
32765
+ }
32766
+ onDisable() {
32767
+ for (const unsubscribe of this.unsubscribers) {
32768
+ unsubscribe();
32769
+ }
32770
+ this.unsubscribers = [];
32771
+ }
32772
+ };
32773
+ function ownValue3(value, key) {
32774
+ if (!isObjectLike2(value)) {
32775
+ return void 0;
32776
+ }
32777
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
32778
+ return descriptor && "value" in descriptor ? descriptor.value : void 0;
32779
+ }
32780
+ function isObjectLike2(value) {
32781
+ return typeof value === "object" && value !== null || typeof value === "function";
32782
+ }
32783
+ function safelyEndSpan(span) {
32784
+ try {
32785
+ span.end();
32786
+ } catch (error) {
32787
+ logInstrumentationError6("span end", error);
32788
+ }
32789
+ }
32790
+ function logInstrumentationError6(operation, error) {
32791
+ debugLogger.error(
32792
+ `Failed to process Cloudflare Agents ${operation} instrumentation:`,
32793
+ error
32794
+ );
32795
+ }
32796
+
31119
32797
  // src/instrumentation/braintrust-plugin.ts
31120
32798
  var BraintrustPlugin = class extends BasePlugin {
31121
32799
  config;
@@ -31128,6 +32806,7 @@ var BraintrustPlugin = class extends BasePlugin {
31128
32806
  openAIAgentsPlugin = null;
31129
32807
  googleGenAIPlugin = null;
31130
32808
  huggingFacePlugin = null;
32809
+ huggingFaceTransformersPlugin = null;
31131
32810
  openRouterPlugin = null;
31132
32811
  openRouterAgentPlugin = null;
31133
32812
  mistralPlugin = null;
@@ -31142,6 +32821,8 @@ var BraintrustPlugin = class extends BasePlugin {
31142
32821
  langSmithPlugin = null;
31143
32822
  piCodingAgentPlugin = null;
31144
32823
  strandsAgentSDKPlugin = null;
32824
+ cloudflareAIChatPlugin = null;
32825
+ cloudflareAgentsPlugin = null;
31145
32826
  constructor(config = {}) {
31146
32827
  super();
31147
32828
  this.config = config;
@@ -31183,6 +32864,8 @@ var BraintrustPlugin = class extends BasePlugin {
31183
32864
  if (integrations.huggingface !== false) {
31184
32865
  this.huggingFacePlugin = new HuggingFacePlugin();
31185
32866
  this.huggingFacePlugin.enable();
32867
+ this.huggingFaceTransformersPlugin = new HuggingFaceTransformersPlugin();
32868
+ this.huggingFaceTransformersPlugin.enable();
31186
32869
  }
31187
32870
  if (integrations.openrouter !== false) {
31188
32871
  this.openRouterPlugin = new OpenRouterPlugin();
@@ -31228,6 +32911,14 @@ var BraintrustPlugin = class extends BasePlugin {
31228
32911
  this.strandsAgentSDKPlugin = new StrandsAgentSDKPlugin();
31229
32912
  this.strandsAgentSDKPlugin.enable();
31230
32913
  }
32914
+ if (integrations.cloudflareAIChat !== false) {
32915
+ this.cloudflareAIChatPlugin = new CloudflareAIChatPlugin();
32916
+ this.cloudflareAIChatPlugin.enable();
32917
+ }
32918
+ if (integrations.cloudflareAgents !== false) {
32919
+ this.cloudflareAgentsPlugin = new CloudflareAgentsPlugin();
32920
+ this.cloudflareAgentsPlugin.enable();
32921
+ }
31231
32922
  if (integrations.flue !== false) {
31232
32923
  this.fluePlugin = new FluePlugin();
31233
32924
  this.fluePlugin.enable();
@@ -31280,6 +32971,10 @@ var BraintrustPlugin = class extends BasePlugin {
31280
32971
  this.huggingFacePlugin.disable();
31281
32972
  this.huggingFacePlugin = null;
31282
32973
  }
32974
+ if (this.huggingFaceTransformersPlugin) {
32975
+ this.huggingFaceTransformersPlugin.disable();
32976
+ this.huggingFaceTransformersPlugin = null;
32977
+ }
31283
32978
  if (this.openRouterPlugin) {
31284
32979
  this.openRouterPlugin.disable();
31285
32980
  this.openRouterPlugin = null;
@@ -31324,6 +33019,14 @@ var BraintrustPlugin = class extends BasePlugin {
31324
33019
  this.strandsAgentSDKPlugin.disable();
31325
33020
  this.strandsAgentSDKPlugin = null;
31326
33021
  }
33022
+ if (this.cloudflareAIChatPlugin) {
33023
+ this.cloudflareAIChatPlugin.disable();
33024
+ this.cloudflareAIChatPlugin = null;
33025
+ }
33026
+ if (this.cloudflareAgentsPlugin) {
33027
+ this.cloudflareAgentsPlugin.disable();
33028
+ this.cloudflareAgentsPlugin = null;
33029
+ }
31327
33030
  if (this.fluePlugin) {
31328
33031
  this.fluePlugin.disable();
31329
33032
  this.fluePlugin = null;
@@ -31340,7 +33043,9 @@ var BraintrustPlugin = class extends BasePlugin {
31340
33043
  };
31341
33044
 
31342
33045
  // src/instrumentation/registry.ts
31343
- var REGISTRY_STATE_KEY = /* @__PURE__ */ Symbol.for("braintrust.registry");
33046
+ var REGISTRY_STATE_KEY = /* @__PURE__ */ Symbol.for(
33047
+ `braintrust.registry.global-hooks.v${GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION}`
33048
+ );
31344
33049
  function getSharedState() {
31345
33050
  const state = globalThis[/* @__PURE__ */ Symbol.for("braintrust-state")];
31346
33051
  return state && typeof state === "object" ? state : void 0;
@@ -31571,17 +33276,20 @@ var BraintrustObservabilityExporter = class {
31571
33276
  }
31572
33277
  onStart(exported) {
31573
33278
  if (this.spans.has(exported.id)) return;
31574
- const args = {
31575
- name: exported.name,
31576
- spanAttributes: { type: spanTypeFor(exported.type) },
31577
- startTime: epochSeconds(exported.startTime),
31578
- // Use the Mastra span id as the Braintrust row id so that
31579
- // `logFeedback({ id: <mastra span id> })` (and Mastra's score events)
31580
- // attach to the right row. Without this, `SpanImpl` auto-generates a
31581
- // row id (`this._id = eventId ?? idGenerator.getSpanId()`) that no
31582
- // external caller could know.
31583
- event: { id: exported.id }
31584
- };
33279
+ const args = withSpanInstrumentationName(
33280
+ {
33281
+ name: exported.name,
33282
+ spanAttributes: { type: spanTypeFor(exported.type) },
33283
+ startTime: epochSeconds(exported.startTime),
33284
+ // Use the Mastra span id as the Braintrust row id so that
33285
+ // `logFeedback({ id: <mastra span id> })` (and Mastra's score events)
33286
+ // attach to the right row. Without this, `SpanImpl` auto-generates a
33287
+ // row id (`this._id = eventId ?? idGenerator.getSpanId()`) that no
33288
+ // external caller could know.
33289
+ event: { id: exported.id }
33290
+ },
33291
+ INSTRUMENTATION_NAMES.MASTRA
33292
+ );
31585
33293
  const parentRecord = exported.parentSpanId ? this.spans.get(exported.parentSpanId) : void 0;
31586
33294
  if (!this.capturedParent) {
31587
33295
  const probe = currentSpan();
@@ -31653,7 +33361,6 @@ function wrapMastraAgent(agent, _options) {
31653
33361
 
31654
33362
  // src/node/config.ts
31655
33363
  import { AsyncLocalStorage } from "node:async_hooks";
31656
- import * as diagnostics_channel from "node:diagnostics_channel";
31657
33364
  import * as path from "node:path";
31658
33365
  import * as fs from "node:fs/promises";
31659
33366
  import * as os from "node:os";
@@ -31940,8 +33647,6 @@ function configureNode() {
31940
33647
  };
31941
33648
  isomorph_default.getCallerLocation = getCallerLocation;
31942
33649
  isomorph_default.newAsyncLocalStorage = () => new AsyncLocalStorage();
31943
- isomorph_default.newTracingChannel = (nameOrChannels) => diagnostics_channel.tracingChannel(nameOrChannels);
31944
- patchTracingChannel(diagnostics_channel.tracingChannel);
31945
33650
  isomorph_default.processOn = (event, handler) => {
31946
33651
  process.on(event, handler);
31947
33652
  };
@@ -31967,6 +33672,12 @@ function configureNode() {
31967
33672
  isomorph_default.gzip = promisify(zlib.gzip);
31968
33673
  isomorph_default.gunzip = promisify(zlib.gunzip);
31969
33674
  isomorph_default.hash = (data) => crypto.createHash("sha256").update(data).digest("hex");
33675
+ isomorph_default.hmacSha256 = (key, data) => crypto.createHmac("sha256", key).update(data).digest("hex");
33676
+ isomorph_default.timingSafeEqual = (left, right) => {
33677
+ const leftBuffer = Buffer.from(left);
33678
+ const rightBuffer = Buffer.from(right);
33679
+ return leftBuffer.length === rightBuffer.length && crypto.timingSafeEqual(leftBuffer, rightBuffer);
33680
+ };
31970
33681
  _internalSetInitialState();
31971
33682
  const disabled = readDisabledInstrumentationEnvConfig(
31972
33683
  isomorph_default.getEnv("BRAINTRUST_DISABLE_INSTRUMENTATION")
@@ -32172,6 +33883,7 @@ export {
32172
33883
  braintrustFlueObserver,
32173
33884
  BRAINTRUST_LANGCHAIN_CALLBACK_HANDLER_NAME,
32174
33885
  BraintrustLangChainCallbackHandler,
33886
+ instrumentCloudflareAIChatAgent,
32175
33887
  configureInstrumentation,
32176
33888
  BraintrustObservabilityExporter,
32177
33889
  wrapMastraAgent,