braintrust 3.25.0 → 3.27.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 (79) hide show
  1. package/NOTICE +6 -0
  2. package/dev/dist/index.d.mts +130 -2
  3. package/dev/dist/index.d.ts +130 -2
  4. package/dev/dist/index.js +4133 -1421
  5. package/dev/dist/index.mjs +3242 -530
  6. package/dist/apply-auto-instrumentation.js +526 -426
  7. package/dist/apply-auto-instrumentation.mjs +329 -229
  8. package/dist/auto-instrumentations/bundler/esbuild.cjs +1198 -364
  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 +6 -8
  12. package/dist/auto-instrumentations/bundler/next.cjs +1227 -413
  13. package/dist/auto-instrumentations/bundler/next.mjs +7 -29
  14. package/dist/auto-instrumentations/bundler/rollup.cjs +1198 -364
  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 +6 -8
  18. package/dist/auto-instrumentations/bundler/vite.cjs +1249 -387
  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 +34 -8
  22. package/dist/auto-instrumentations/bundler/webpack-loader.cjs +1368 -324
  23. package/dist/auto-instrumentations/bundler/webpack-loader.d.ts +20 -12
  24. package/dist/auto-instrumentations/bundler/webpack.cjs +1198 -364
  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 +6 -4
  28. package/dist/auto-instrumentations/chunk-2AMDGD65.mjs +1396 -0
  29. package/dist/auto-instrumentations/{chunk-7P6563SW.mjs → chunk-BW33ULMW.mjs} +2 -6
  30. package/dist/auto-instrumentations/{chunk-M6DLIJ2Z.mjs → chunk-I55G56ZL.mjs} +114 -221
  31. package/dist/auto-instrumentations/chunk-JPUFNW7X.mjs +649 -0
  32. package/dist/auto-instrumentations/{chunk-JPVCUKTY.mjs → chunk-XEYKUBLY.mjs} +191 -73
  33. package/dist/auto-instrumentations/{chunk-CZ24KNHT.mjs → chunk-ZNHTSSGI.mjs} +231 -69
  34. package/dist/auto-instrumentations/hook.mjs +406 -183
  35. package/dist/auto-instrumentations/index.cjs +853 -49
  36. package/dist/auto-instrumentations/index.d.mts +10 -2
  37. package/dist/auto-instrumentations/index.d.ts +10 -2
  38. package/dist/auto-instrumentations/index.mjs +10 -1
  39. package/dist/auto-instrumentations/loader/cjs-patch.cjs +566 -221
  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 +871 -199
  49. package/dist/browser.d.ts +871 -199
  50. package/dist/browser.js +3737 -549
  51. package/dist/browser.mjs +3737 -549
  52. package/dist/{chunk-ABR2QWDP.mjs → chunk-CZM5JIQL.mjs} +788 -132
  53. package/dist/{chunk-P25IOOU4.js → chunk-MF7NU6BT.js} +795 -139
  54. package/dist/{chunk-GSIDVFE6.js → chunk-QRHGVBKU.js} +3580 -1463
  55. package/dist/{chunk-2SANLSWX.mjs → chunk-YKD22IMR.mjs} +2505 -388
  56. package/dist/cli.js +3244 -533
  57. package/dist/edge-light.d.mts +1 -1
  58. package/dist/edge-light.d.ts +1 -1
  59. package/dist/edge-light.js +3737 -552
  60. package/dist/edge-light.mjs +3737 -552
  61. package/dist/index.d.mts +871 -199
  62. package/dist/index.d.ts +871 -199
  63. package/dist/index.js +893 -446
  64. package/dist/index.mjs +463 -16
  65. package/dist/instrumentation/index.d.mts +138 -6
  66. package/dist/instrumentation/index.d.ts +138 -6
  67. package/dist/instrumentation/index.js +3362 -559
  68. package/dist/instrumentation/index.mjs +3362 -559
  69. package/dist/vitest-evals-reporter.js +45 -43
  70. package/dist/vitest-evals-reporter.mjs +5 -3
  71. package/dist/workerd.d.mts +1 -1
  72. package/dist/workerd.d.ts +1 -1
  73. package/dist/workerd.js +3737 -552
  74. package/dist/workerd.mjs +3737 -552
  75. package/licenses/node-diagnostics-channel/LICENSE +19 -0
  76. package/package.json +34 -35
  77. package/dist/auto-instrumentations/chunk-VT6DDNKM.mjs +0 -856
  78. package/dist/auto-instrumentations/plugin-D0KHwSJv.d.mts +0 -44
  79. package/dist/auto-instrumentations/plugin-G6fgxk1b.d.ts +0 -44
@@ -1,8 +1,15 @@
1
1
  import {
2
+ GLOBAL_INSTRUMENTATION_HOOKS_KEY,
3
+ GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION,
4
+ GLOBAL_INSTRUMENTATION_HOOKS_REGISTRY_BRAND,
5
+ GLOBAL_INSTRUMENTATION_HOOK_BRAND,
2
6
  aiSDKChannels,
3
7
  anthropicChannels,
4
8
  classifyMastraTarget,
5
9
  claudeAgentSDKChannels,
10
+ cloudflareAIChatChannels,
11
+ cloudflareAgentsChannels,
12
+ cloudflareThinkChannels,
6
13
  cohereChannels,
7
14
  cursorSDKChannels,
8
15
  flueChannels,
@@ -14,26 +21,26 @@ import {
14
21
  groqChannels,
15
22
  harnessAgentChannels,
16
23
  huggingFaceChannels,
24
+ huggingFaceTransformersChannels,
17
25
  isInstrumentationIntegrationDisabled,
18
26
  langChainChannels,
19
27
  langSmithChannels,
20
28
  mistralChannels,
29
+ ollamaChannels,
21
30
  openAIAgentsCoreChannels,
22
31
  openAIChannels,
23
32
  openAICodexChannels,
24
33
  openRouterAgentChannels,
25
34
  openRouterChannels,
26
35
  patchMastraSource,
27
- patchTracingChannel,
28
36
  piCodingAgentChannels,
29
37
  readDisabledInstrumentationEnvConfig,
30
38
  smithyClientChannels,
31
39
  smithyCoreChannels,
32
40
  strandsAgentSDKChannels
33
- } from "./chunk-ABR2QWDP.mjs";
41
+ } from "./chunk-CZM5JIQL.mjs";
34
42
 
35
43
  // src/node/apply-auto-instrumentation-entry.ts
36
- import * as diagnostics_channel from "node:diagnostics_channel";
37
44
  import { register } from "node:module";
38
45
  import { pathToFileURL } from "node:url";
39
46
 
@@ -544,7 +551,40 @@ var anthropicConfigs = [
544
551
  methodName: "toolRunner",
545
552
  kind: "Sync"
546
553
  }
547
- }
554
+ },
555
+ // Managed Agents Sessions event streams are discovered automatically, but
556
+ // remain passive until the user calls collectAnthropicSession() on the
557
+ // returned stream.
558
+ ...["mjs", "js"].map(
559
+ (extension) => ({
560
+ channelName: anthropicChannels.betaSessionsEventsStream.channelName,
561
+ module: {
562
+ name: "@anthropic-ai/sdk",
563
+ versionRange: ">=0.86.0",
564
+ filePath: `resources/beta/sessions/events.${extension}`
565
+ },
566
+ functionQuery: {
567
+ className: "Events",
568
+ methodName: "stream",
569
+ kind: "Async"
570
+ }
571
+ })
572
+ ),
573
+ ...["mjs", "js"].map(
574
+ (extension) => ({
575
+ channelName: anthropicChannels.betaSessionsThreadsEventsStream.channelName,
576
+ module: {
577
+ name: "@anthropic-ai/sdk",
578
+ versionRange: ">=0.86.0",
579
+ filePath: `resources/beta/sessions/threads/events.${extension}`
580
+ },
581
+ functionQuery: {
582
+ className: "Events",
583
+ methodName: "stream",
584
+ kind: "Async"
585
+ }
586
+ })
587
+ )
548
588
  ];
549
589
 
550
590
  // src/auto-instrumentations/configs/bedrock-runtime.ts
@@ -634,6 +674,64 @@ var claudeAgentSDKConfigs = [
634
674
  }
635
675
  ];
636
676
 
677
+ // src/auto-instrumentations/configs/cloudflare-ai-chat.ts
678
+ var cloudflareAIChatVersionRange = ">=0.9.0 <0.10.0";
679
+ var cloudflareAIChatConfigs = [
680
+ {
681
+ // AIChatAgent subclasses replace onChatMessage, so there is no stable
682
+ // public implementation for the transformer to target. This runner is
683
+ // the narrowest shared boundary around every chat turn; keep the version
684
+ // range tight because it is an internal method.
685
+ channelName: cloudflareAIChatChannels.runExclusiveChatTurn.channelName,
686
+ module: {
687
+ name: "@cloudflare/ai-chat",
688
+ versionRange: cloudflareAIChatVersionRange,
689
+ filePath: "dist/index.js"
690
+ },
691
+ functionQuery: {
692
+ className: "AIChatAgent",
693
+ methodName: "_runExclusiveChatTurn",
694
+ kind: "Async"
695
+ }
696
+ }
697
+ ];
698
+
699
+ // src/auto-instrumentations/configs/cloudflare-agents.ts
700
+ var cloudflareAgentsVersionRange = ">=0.17.0 <0.18.0";
701
+ var cloudflareAgentsConfigs = [
702
+ {
703
+ channelName: cloudflareAgentsChannels.runAgentTool.channelName,
704
+ module: {
705
+ name: "agents",
706
+ versionRange: cloudflareAgentsVersionRange,
707
+ filePath: "dist/index.js"
708
+ },
709
+ functionQuery: {
710
+ className: "Agent",
711
+ methodName: "runAgentTool",
712
+ kind: "Async"
713
+ }
714
+ }
715
+ ];
716
+
717
+ // src/auto-instrumentations/configs/cloudflare-think.ts
718
+ var cloudflareThinkVersionRange = ">=0.13.0 <0.14.0";
719
+ var cloudflareThinkConfigs = [
720
+ {
721
+ channelName: cloudflareThinkChannels.runInferenceLoop.channelName,
722
+ module: {
723
+ name: "@cloudflare/think",
724
+ versionRange: cloudflareThinkVersionRange,
725
+ filePath: "dist/think.js"
726
+ },
727
+ functionQuery: {
728
+ className: "Think",
729
+ methodName: "_runInferenceLoop",
730
+ kind: "Async"
731
+ }
732
+ }
733
+ ];
734
+
637
735
  // src/auto-instrumentations/configs/cohere.ts
638
736
  var cohereConfigs = [
639
737
  {
@@ -1786,6 +1884,67 @@ var huggingFaceConfigs = [
1786
1884
  }
1787
1885
  ];
1788
1886
 
1887
+ // src/auto-instrumentations/configs/huggingface-transformers.ts
1888
+ var moduleFiles = [
1889
+ {
1890
+ filePath: "dist/transformers.mjs",
1891
+ versionRange: ">=3.0.0 <3.4.0"
1892
+ },
1893
+ {
1894
+ filePath: "dist/transformers.cjs",
1895
+ versionRange: ">=3.0.0 <3.4.0"
1896
+ },
1897
+ {
1898
+ filePath: "dist/transformers.js",
1899
+ versionRange: ">=3.0.0 <3.4.0"
1900
+ },
1901
+ {
1902
+ filePath: "dist/transformers.node.mjs",
1903
+ versionRange: ">=3.4.0 <5.0.0"
1904
+ },
1905
+ {
1906
+ filePath: "dist/transformers.node.cjs",
1907
+ versionRange: ">=3.4.0 <5.0.0"
1908
+ },
1909
+ {
1910
+ filePath: "dist/transformers.web.js",
1911
+ versionRange: ">=3.4.0 <5.0.0"
1912
+ }
1913
+ ];
1914
+ var pipelineClasses = [
1915
+ "TextGenerationPipeline",
1916
+ "Text2TextGenerationPipeline",
1917
+ "FeatureExtractionPipeline",
1918
+ "QuestionAnsweringPipeline"
1919
+ ];
1920
+ var huggingFaceTransformersConfigs = moduleFiles.flatMap(({ filePath, versionRange: versionRange2 }) => [
1921
+ {
1922
+ channelName: huggingFaceTransformersChannels.pipeline.channelName,
1923
+ module: {
1924
+ name: "@huggingface/transformers",
1925
+ versionRange: versionRange2,
1926
+ filePath
1927
+ },
1928
+ functionQuery: {
1929
+ functionName: "pipeline",
1930
+ kind: "Async"
1931
+ }
1932
+ },
1933
+ ...pipelineClasses.map((className) => ({
1934
+ channelName: huggingFaceTransformersChannels.pipelineCall.channelName,
1935
+ module: {
1936
+ name: "@huggingface/transformers",
1937
+ versionRange: versionRange2,
1938
+ filePath
1939
+ },
1940
+ functionQuery: {
1941
+ className,
1942
+ methodName: "_call",
1943
+ kind: "Async"
1944
+ }
1945
+ }))
1946
+ ]);
1947
+
1789
1948
  // src/auto-instrumentations/configs/langchain.ts
1790
1949
  var langChainCoreVersionRange = ">=0.3.42";
1791
1950
  var langChainCallbackManagerFilePath = "dist/callbacks/manager.js";
@@ -2142,6 +2301,31 @@ var mistralConfigs = [
2142
2301
  }
2143
2302
  ];
2144
2303
 
2304
+ // src/auto-instrumentations/configs/ollama.ts
2305
+ var methods = [
2306
+ ["chat", ollamaChannels.chat.channelName],
2307
+ ["generate", ollamaChannels.generate.channelName],
2308
+ ["embed", ollamaChannels.embed.channelName]
2309
+ ];
2310
+ var implementationFiles = ["dist/browser.mjs", "dist/browser.cjs"];
2311
+ var ollamaConfigs = [
2312
+ ...implementationFiles.flatMap(
2313
+ (filePath) => methods.map(([methodName, channelName]) => ({
2314
+ channelName,
2315
+ module: {
2316
+ name: "ollama",
2317
+ versionRange: ">=0.6.0 <0.7.0",
2318
+ filePath
2319
+ },
2320
+ functionQuery: {
2321
+ className: "Ollama",
2322
+ methodName,
2323
+ kind: "Async"
2324
+ }
2325
+ }))
2326
+ )
2327
+ ];
2328
+
2145
2329
  // src/auto-instrumentations/configs/openai-agents.ts
2146
2330
  var lifecycleMethods = [
2147
2331
  ["onTraceStart", openAIAgentsCoreChannels.onTraceStart.channelName],
@@ -2431,6 +2615,19 @@ var openRouterConfigs = [
2431
2615
  kind: "Async"
2432
2616
  }
2433
2617
  },
2618
+ {
2619
+ channelName: openRouterChannels.betaResponsesSend.channelName,
2620
+ module: {
2621
+ name: "@openrouter/sdk",
2622
+ versionRange: ">=1.1.2 <2.0.0",
2623
+ filePath: "esm/sdk/betaresponses.js"
2624
+ },
2625
+ functionQuery: {
2626
+ className: "BetaResponses",
2627
+ methodName: "send",
2628
+ kind: "Async"
2629
+ }
2630
+ },
2434
2631
  {
2435
2632
  channelName: openRouterChannels.callModel.channelName,
2436
2633
  module: {
@@ -2544,6 +2741,18 @@ var defaultInstrumentationConfigGroups = [
2544
2741
  integrations: ["claudeAgentSDK"],
2545
2742
  configs: claudeAgentSDKConfigs
2546
2743
  },
2744
+ {
2745
+ integrations: ["cloudflareAIChat"],
2746
+ configs: cloudflareAIChatConfigs
2747
+ },
2748
+ {
2749
+ integrations: ["cloudflareAgents"],
2750
+ configs: cloudflareAgentsConfigs
2751
+ },
2752
+ {
2753
+ integrations: ["cloudflareThink"],
2754
+ configs: cloudflareThinkConfigs
2755
+ },
2547
2756
  { integrations: ["cursor", "cursorSDK"], configs: cursorSDKConfigs },
2548
2757
  {
2549
2758
  integrations: ["openAIAgents"],
@@ -2553,7 +2762,10 @@ var defaultInstrumentationConfigGroups = [
2553
2762
  integrations: ["google", "googleGenAI"],
2554
2763
  configs: googleGenAIConfigs
2555
2764
  },
2556
- { integrations: ["huggingface"], configs: huggingFaceConfigs },
2765
+ {
2766
+ integrations: ["huggingface"],
2767
+ configs: [...huggingFaceConfigs, ...huggingFaceTransformersConfigs]
2768
+ },
2557
2769
  {
2558
2770
  integrations: ["langchain", "langgraph"],
2559
2771
  configs: langchainConfigs
@@ -2565,6 +2777,7 @@ var defaultInstrumentationConfigGroups = [
2565
2777
  configs: openRouterAgentConfigs
2566
2778
  },
2567
2779
  { integrations: ["mistral"], configs: mistralConfigs },
2780
+ { integrations: ["ollama"], configs: ollamaConfigs },
2568
2781
  { integrations: ["googleADK"], configs: googleADKConfigs },
2569
2782
  { integrations: ["cohere"], configs: cohereConfigs },
2570
2783
  { integrations: ["groq"], configs: groqConfigs },
@@ -2631,52 +2844,76 @@ import { SourceMapGenerator } from "source-map";
2631
2844
  // src/auto-instrumentations/orchestrion-js/transforms.ts
2632
2845
  import esquery from "esquery";
2633
2846
  import { parse } from "meriyah";
2634
- var tracingChannelPredicate = (node) => node.declarations?.[0]?.id?.properties?.[0]?.value?.name === "tr_ch_apm_tracingChannel";
2635
2847
  var CHANNEL_REGEX = /[^\w]/g;
2848
+ var SHARED_HOOK_LOOKUP = "tr_ch_bt$get_hook";
2636
2849
  function formatChannelVariable(channelName) {
2637
- return `tr_ch_apm$${channelName.replace(CHANNEL_REGEX, "_")}`;
2850
+ return `tr_ch_bt$${channelName.replace(CHANNEL_REGEX, "_")}`;
2851
+ }
2852
+ function formatChannelGetter(channelName) {
2853
+ return `tr_ch_bt$get_${channelName.replace(CHANNEL_REGEX, "_")}`;
2638
2854
  }
2639
2855
  var transforms = {
2640
- tracingChannelImport({ dcModule, moduleType }, node) {
2641
- if (node.body.some(tracingChannelPredicate)) {
2642
- return;
2643
- }
2644
- const options = { module: moduleType === "esm" };
2645
- const index = node.body.findIndex(
2646
- (child) => child.directive === "use strict"
2647
- );
2648
- const dc = moduleType === "esm" ? `import tr_ch_apm_dc from "${dcModule}"` : `const tr_ch_apm_dc = ${"require"}("${dcModule}")`;
2649
- const tracingChannel2 = "const { tracingChannel: tr_ch_apm_tracingChannel } = tr_ch_apm_dc";
2650
- const hasSubscribers = `const tr_ch_apm_hasSubscribers = ch => ch.start.hasSubscribers
2651
- || ch.end.hasSubscribers
2652
- || ch.asyncStart.hasSubscribers
2653
- || ch.asyncEnd.hasSubscribers
2654
- || ch.error.hasSubscribers`;
2655
- node.body.splice(
2656
- index + 1,
2657
- 0,
2658
- parse(dc, options).body[0],
2659
- parse(tracingChannel2, options).body[0],
2660
- parse(hasSubscribers, options).body[0]
2661
- );
2662
- },
2663
- tracingChannelDeclaration(state2, node) {
2856
+ tracingHookDeclaration(state2, node) {
2664
2857
  const {
2665
2858
  channelName,
2666
2859
  module: { name }
2667
2860
  } = state2;
2668
2861
  const channelVariable = formatChannelVariable(channelName);
2862
+ const channelGetter = formatChannelGetter(channelName);
2863
+ const hasSharedHookLookup = node.body.some(
2864
+ (child) => child.declarations?.[0]?.id?.name === SHARED_HOOK_LOOKUP
2865
+ );
2669
2866
  if (node.body.some(
2670
- (child) => child.declarations?.[0]?.id?.name === channelVariable
2867
+ (child) => child.declarations?.[0]?.id?.name === channelGetter
2671
2868
  )) {
2672
2869
  return;
2673
2870
  }
2674
- transforms.tracingChannelImport(state2, node, null, []);
2675
- const index = node.body.findIndex(tracingChannelPredicate);
2871
+ const sharedHookLookup = hasSharedHookLookup ? "" : `
2872
+ const ${SHARED_HOOK_LOOKUP} = (__bt$hookName) => {
2873
+ try {
2874
+ const __bt$hooks = globalThis[${JSON.stringify(
2875
+ GLOBAL_INSTRUMENTATION_HOOKS_KEY
2876
+ )}];
2877
+ if (
2878
+ !(__bt$hooks instanceof Map) ||
2879
+ __bt$hooks[Symbol.for(${JSON.stringify(
2880
+ GLOBAL_INSTRUMENTATION_HOOKS_REGISTRY_BRAND
2881
+ )})] !== ${GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION}
2882
+ ) return undefined;
2883
+ const __bt$hook = Map.prototype.get.call(
2884
+ __bt$hooks,
2885
+ __bt$hookName
2886
+ );
2887
+ if (
2888
+ (__bt$hook === null ||
2889
+ (typeof __bt$hook !== "object" &&
2890
+ typeof __bt$hook !== "function")) ||
2891
+ __bt$hook[Symbol.for(${JSON.stringify(
2892
+ GLOBAL_INSTRUMENTATION_HOOK_BRAND
2893
+ )})] !== ${GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION} ||
2894
+ typeof __bt$hook.traceInvocation !== "function"
2895
+ ) return undefined;
2896
+ return __bt$hook;
2897
+ } catch {
2898
+ return undefined;
2899
+ }
2900
+ };
2901
+ `;
2676
2902
  const code = `
2677
- const ${channelVariable} = tr_ch_apm_tracingChannel("orchestrion:${name}:${channelName}")
2903
+ ${sharedHookLookup}
2904
+ let ${channelVariable};
2905
+ const ${channelGetter} = () =>
2906
+ ${channelVariable} ??= ${SHARED_HOOK_LOOKUP}(
2907
+ ${JSON.stringify(`orchestrion:${name}:${channelName}`)}
2908
+ );
2678
2909
  `;
2679
- node.body.splice(index + 1, 0, parse(code).body[0]);
2910
+ const sharedHookLookupIndex = node.body.findIndex(
2911
+ (child) => child.declarations?.[0]?.id?.name === SHARED_HOOK_LOOKUP
2912
+ );
2913
+ const index = sharedHookLookupIndex === -1 ? node.body.findIndex(
2914
+ (child) => child.directive === "use strict"
2915
+ ) : sharedHookLookupIndex;
2916
+ node.body.splice(index + 1, 0, ...parse(code).body);
2680
2917
  },
2681
2918
  traceCallback: traceAny,
2682
2919
  tracePromise: traceAny,
@@ -2691,25 +2928,21 @@ function traceAny(state2, node, _parent, ancestry) {
2691
2928
  }
2692
2929
  }
2693
2930
  function traceFunction(state2, node, program) {
2694
- transforms.tracingChannelDeclaration(state2, program, null, []);
2931
+ transforms.tracingHookDeclaration(state2, program, null, []);
2695
2932
  const { functionQuery } = state2;
2696
2933
  const methodName = "methodName" in functionQuery ? functionQuery.methodName : void 0;
2697
2934
  const privateMethodName = "privateMethodName" in functionQuery ? functionQuery.privateMethodName : void 0;
2698
2935
  const functionName = "functionName" in functionQuery ? functionQuery.functionName : void 0;
2699
2936
  const isConstructor = methodName === "constructor" || !methodName && !privateMethodName && !functionName;
2700
2937
  const type = isConstructor ? "ArrowFunctionExpression" : "FunctionExpression";
2701
- node.body = wrap(
2702
- state2,
2703
- {
2704
- type,
2705
- params: node.params,
2706
- body: node.body,
2707
- async: node.async,
2708
- expression: false,
2709
- generator: node.generator
2710
- },
2711
- program
2712
- );
2938
+ node.body = wrap(state2, {
2939
+ type,
2940
+ params: node.params,
2941
+ body: node.body,
2942
+ async: node.async,
2943
+ expression: false,
2944
+ generator: node.generator
2945
+ });
2713
2946
  node.generator = false;
2714
2947
  node.async = false;
2715
2948
  wrapSuper(node);
@@ -2721,11 +2954,11 @@ function traceInstanceMethod(state2, node, program) {
2721
2954
  return;
2722
2955
  }
2723
2956
  const classBody = node.body;
2724
- if (classBody.body.some(({ key }) => key.name === methodName)) {
2957
+ if (classBody.body.some(({ key }) => key?.name === methodName)) {
2725
2958
  return;
2726
2959
  }
2727
2960
  let ctor = classBody.body.find(({ kind }) => kind === "constructor");
2728
- transforms.tracingChannelDeclaration(state2, program, null, []);
2961
+ transforms.tracingHookDeclaration(state2, program, null, []);
2729
2962
  if (!ctor) {
2730
2963
  ctor = parse(
2731
2964
  node.superClass ? "class A extends Object { constructor (...args) { super(...args) } }" : "class A { constructor () {} }"
@@ -2733,47 +2966,36 @@ function traceInstanceMethod(state2, node, program) {
2733
2966
  classBody.body.unshift(ctor);
2734
2967
  }
2735
2968
  const ctorBody = parse(`
2736
- const __apm$${methodName} = this["${methodName}"]
2969
+ const __bt$${methodName} = this["${methodName}"]
2737
2970
  this["${methodName}"] = function () {}
2738
2971
  `).body;
2739
2972
  const fn = ctorBody[1].expression.right;
2740
2973
  fn.async = operator === "tracePromise";
2741
- fn.body = wrap(
2742
- state2,
2743
- { type: "Identifier", name: `__apm$${methodName}` },
2744
- program
2745
- );
2974
+ fn.body = wrap(state2, {
2975
+ type: "Identifier",
2976
+ name: `__bt$${methodName}`
2977
+ });
2746
2978
  wrapSuper(fn);
2747
2979
  ctor.value.body.body.push(...ctorBody);
2748
2980
  }
2749
- function wrap(state2, node, program) {
2750
- const { operator, moduleVersion } = state2;
2751
- const wrapper = operator === "traceCallback" ? wrapCallback(state2) : operator === "tracePromise" ? wrapPromise(state2) : wrapSync(state2);
2981
+ function wrap(state2, node) {
2982
+ const wrapper = wrapInvocation(state2);
2752
2983
  const block = wrapper.body[0].body;
2753
2984
  const common = parse(
2754
2985
  node.type === "ArrowFunctionExpression" ? `
2755
- const __apm$ctx = {
2756
- arguments,
2757
- moduleVersion: ${JSON.stringify(moduleVersion)}
2758
- };
2759
- const __apm$traced = () => {
2760
- const __apm$wrapped = () => {};
2761
- return __apm$wrapped(...arguments);
2986
+ const __bt$target = (...__bt$args) => {
2987
+ const __bt$wrapped = () => {};
2988
+ return __bt$wrapped(...__bt$args);
2762
2989
  };
2763
2990
  ` : `
2764
- const __apm$ctx = {
2765
- arguments,
2766
- self: this,
2767
- moduleVersion: ${JSON.stringify(moduleVersion)}
2768
- };
2769
- const __apm$traced = () => {
2770
- const __apm$wrapped = () => {};
2771
- return __apm$wrapped.apply(this, arguments);
2991
+ const __bt$target = function (...__bt$args) {
2992
+ const __bt$wrapped = () => {};
2993
+ return __bt$wrapped.apply(this, __bt$args);
2772
2994
  };
2773
2995
  `
2774
2996
  ).body;
2775
2997
  block.body.unshift(...common);
2776
- esquery.query(block, "[id.name=__apm$wrapped]")[0].init = node;
2998
+ esquery.query(block, "[id.name=__bt$wrapped]")[0].init = node;
2777
2999
  return block;
2778
3000
  }
2779
3001
  function wrapSuper(node) {
@@ -2785,11 +3007,11 @@ function wrapSuper(node) {
2785
3007
  const { name } = node2.property;
2786
3008
  let child;
2787
3009
  if (parent.callee) {
2788
- const { expression } = parse(`__apm$super['${name}'].call(this)`).body[0];
3010
+ const { expression } = parse(`__bt$super['${name}'].call(this)`).body[0];
2789
3011
  parent.callee = child = expression.callee;
2790
3012
  parent.arguments.unshift(...expression.arguments);
2791
3013
  } else {
2792
- parent.expression = child = parse(`__apm$super['${name}']`).body[0];
3014
+ parent.expression = child = parse(`__bt$super['${name}']`).body[0];
2793
3015
  }
2794
3016
  child.computed = parent.callee.computed;
2795
3017
  child.optional = parent.callee.optional;
@@ -2800,151 +3022,32 @@ function wrapSuper(node) {
2800
3022
  const member = parse(`
2801
3023
  class Wrapper {
2802
3024
  wrapper () {
2803
- __apm$super['${name}'] = super['${name}']
3025
+ __bt$super['${name}'] = super['${name}']
2804
3026
  }
2805
3027
  }
2806
3028
  `).body[0].body.body[0].value.body.body[0];
2807
3029
  node.body.body.unshift(member);
2808
3030
  }
2809
3031
  if (members.size > 0) {
2810
- node.body.body.unshift(parse("const __apm$super = {}").body[0]);
3032
+ node.body.body.unshift(parse("const __bt$super = {}").body[0]);
2811
3033
  }
2812
3034
  }
2813
- function wrapCallback(state2) {
2814
- const {
2815
- channelName,
2816
- functionQuery: { callbackIndex = -1 }
2817
- } = state2;
2818
- const channelVariable = formatChannelVariable(channelName);
2819
- return parse(`
2820
- function wrapper () {
2821
- const __apm$cb = Array.prototype.at.call(arguments, ${callbackIndex});
2822
-
2823
- if (!${channelVariable}.start.hasSubscribers) return __apm$traced();
2824
-
2825
- function __apm$wrappedCb(err, res) {
2826
- if (err) {
2827
- __apm$ctx.error = err;
2828
- ${channelVariable}.error.publish(__apm$ctx);
2829
- } else {
2830
- __apm$ctx.result = res;
2831
- }
2832
-
2833
- ${channelVariable}.asyncStart.runStores(__apm$ctx, () => {
2834
- try {
2835
- if (__apm$cb) {
2836
- return __apm$cb.apply(this, arguments);
2837
- }
2838
- } finally {
2839
- ${channelVariable}.asyncEnd.publish(__apm$ctx);
2840
- }
2841
- });
2842
- }
2843
-
2844
- if (typeof __apm$cb !== 'function') {
2845
- return __apm$traced();
2846
- }
2847
- Array.prototype.splice.call(arguments, ${callbackIndex}, 1, __apm$wrappedCb);
2848
-
2849
- return ${channelVariable}.start.runStores(__apm$ctx, () => {
2850
- try {
2851
- return __apm$traced();
2852
- } catch (err) {
2853
- __apm$ctx.error = err;
2854
- ${channelVariable}.error.publish(__apm$ctx);
2855
- throw err;
2856
- } finally {
2857
- __apm$ctx.self ??= this;
2858
- ${channelVariable}.end.publish(__apm$ctx);
2859
- }
2860
- });
2861
- }
2862
- `);
2863
- }
2864
- function wrapPromise(state2) {
2865
- const { channelName } = state2;
2866
- const channelVariable = formatChannelVariable(channelName);
3035
+ function wrapInvocation(state2) {
3036
+ const { channelName, moduleVersion, operator, functionQuery } = state2;
3037
+ const channelGetter = formatChannelGetter(channelName);
3038
+ const callbackIndex = functionQuery.callbackIndex ?? -1;
2867
3039
  return parse(`
2868
3040
  function wrapper () {
2869
- if (!tr_ch_apm_hasSubscribers(${channelVariable})) return __apm$traced();
2870
-
2871
- return ${channelVariable}.start.runStores(__apm$ctx, () => {
2872
- try {
2873
- let promise = __apm$traced();
2874
- if (typeof promise?.then !== 'function') {
2875
- __apm$ctx.result = promise;
2876
- return promise;
2877
- }
2878
- // Mirror Node.js core diagnostics_channel behaviour: for native Promise
2879
- // instances, chain normally (safe since there is no subclass API to
2880
- // preserve). For Promise subclasses and other thenables, side-chain the
2881
- // callbacks for event publishing and return the original so that any
2882
- // subclass-specific methods (e.g. APIPromise.withResponse()) remain
2883
- // accessible to the caller.
2884
- if (promise instanceof Promise && promise.constructor === Promise) {
2885
- return promise.then(
2886
- result => {
2887
- __apm$ctx.result = result;
2888
- ${channelVariable}.asyncStart.publish(__apm$ctx);
2889
- ${channelVariable}.asyncEnd.publish(__apm$ctx);
2890
- return result;
2891
- },
2892
- err => {
2893
- __apm$ctx.error = err;
2894
- ${channelVariable}.error.publish(__apm$ctx);
2895
- ${channelVariable}.asyncStart.publish(__apm$ctx);
2896
- ${channelVariable}.asyncEnd.publish(__apm$ctx);
2897
- throw err;
2898
- }
2899
- );
2900
- }
2901
- promise.then(
2902
- result => {
2903
- __apm$ctx.result = result;
2904
- ${channelVariable}.asyncStart.publish(__apm$ctx);
2905
- ${channelVariable}.asyncEnd.publish(__apm$ctx);
2906
- },
2907
- err => {
2908
- __apm$ctx.error = err;
2909
- ${channelVariable}.error.publish(__apm$ctx);
2910
- ${channelVariable}.asyncStart.publish(__apm$ctx);
2911
- ${channelVariable}.asyncEnd.publish(__apm$ctx);
2912
- }
2913
- );
2914
- return promise;
2915
- } catch (err) {
2916
- __apm$ctx.error = err;
2917
- ${channelVariable}.error.publish(__apm$ctx);
2918
- throw err;
2919
- } finally {
2920
- __apm$ctx.self ??= this;
2921
- ${channelVariable}.end.publish(__apm$ctx);
2922
- }
2923
- });
2924
- }
2925
- `);
2926
- }
2927
- function wrapSync(state2) {
2928
- const { channelName } = state2;
2929
- const channelVariable = formatChannelVariable(channelName);
2930
- return parse(`
2931
- function wrapper () {
2932
- if (!tr_ch_apm_hasSubscribers(${channelVariable})) return __apm$traced();
2933
-
2934
- return ${channelVariable}.start.runStores(__apm$ctx, () => {
2935
- try {
2936
- const result = __apm$traced();
2937
- __apm$ctx.result = result;
2938
- return result;
2939
- } catch (err) {
2940
- __apm$ctx.error = err;
2941
- ${channelVariable}.error.publish(__apm$ctx);
2942
- throw err;
2943
- } finally {
2944
- __apm$ctx.self ??= this;
2945
- ${channelVariable}.end.publish(__apm$ctx);
2946
- }
2947
- });
3041
+ const __bt$hook = ${channelGetter}();
3042
+ if (!__bt$hook) return __bt$target.apply(this, arguments);
3043
+ return __bt$hook.traceInvocation(
3044
+ ${JSON.stringify(operator)},
3045
+ __bt$target,
3046
+ this,
3047
+ arguments,
3048
+ { moduleVersion: ${JSON.stringify(moduleVersion)} },
3049
+ ${callbackIndex}
3050
+ );
2948
3051
  }
2949
3052
  `);
2950
3053
  }
@@ -2955,16 +3058,14 @@ var Transformer = class {
2955
3058
  version;
2956
3059
  filePath;
2957
3060
  configs = [];
2958
- dcModule;
2959
- constructor(moduleName, version, filePath, configs, dcModule) {
3061
+ constructor(moduleName, version, filePath, configs) {
2960
3062
  this.moduleName = moduleName;
2961
3063
  this.version = version;
2962
3064
  this.filePath = filePath;
2963
3065
  this.configs = configs;
2964
- this.dcModule = dcModule;
2965
3066
  }
2966
3067
  /**
2967
- * Instruments `code` by injecting diagnostics_channel tracing around the
3068
+ * Instruments `code` by injecting global tracing hooks around the
2968
3069
  * target functions defined by this transformer's configs.
2969
3070
  */
2970
3071
  transform(code, moduleType) {
@@ -3002,8 +3103,6 @@ var Transformer = class {
3002
3103
  const query = astQuery || this.fromFunctionQuery(resolvedFunctionQuery);
3003
3104
  const state2 = {
3004
3105
  ...config,
3005
- dcModule: this.dcModule,
3006
- moduleType,
3007
3106
  moduleVersion: this.version,
3008
3107
  functionQuery: resolvedFunctionQuery,
3009
3108
  operator: this.getOperator(resolvedFunctionQuery.kind)
@@ -3153,11 +3252,9 @@ var Transformer = class {
3153
3252
  // src/auto-instrumentations/orchestrion-js/matcher.ts
3154
3253
  var InstrumentationMatcher = class {
3155
3254
  configs = [];
3156
- dcModule;
3157
3255
  transformers = {};
3158
- constructor(configs, dcModule) {
3256
+ constructor(configs) {
3159
3257
  this.configs = configs;
3160
- this.dcModule = dcModule || "diagnostics_channel";
3161
3258
  }
3162
3259
  /**
3163
3260
  * Returns a Transformer for the given module/file/version, or undefined if no
@@ -3179,8 +3276,7 @@ var InstrumentationMatcher = class {
3179
3276
  moduleName,
3180
3277
  version,
3181
3278
  filePath,
3182
- configs,
3183
- this.dcModule
3279
+ configs
3184
3280
  );
3185
3281
  return this.transformers[id];
3186
3282
  }
@@ -3190,8 +3286,8 @@ var InstrumentationMatcher = class {
3190
3286
  };
3191
3287
 
3192
3288
  // src/auto-instrumentations/orchestrion-js/index.ts
3193
- function create(configs, dcModule) {
3194
- return new InstrumentationMatcher(configs, dcModule);
3289
+ function create(configs) {
3290
+ return new InstrumentationMatcher(configs);
3195
3291
  }
3196
3292
 
3197
3293
  // src/auto-instrumentations/loader/cjs-patch.ts
@@ -3280,6 +3376,9 @@ function applySpecialCasePatch(input) {
3280
3376
  if (input.packageName === "openai" && input.modulePath.includes("api-promise")) {
3281
3377
  return input.source + OPENAI_API_PROMISE_PATCH;
3282
3378
  }
3379
+ if (input.browser) {
3380
+ return null;
3381
+ }
3283
3382
  const mastraTarget = classifyMastraTarget(
3284
3383
  input.packageName,
3285
3384
  input.modulePath
@@ -3308,7 +3407,7 @@ var ModulePatch = class {
3308
3407
  /**
3309
3408
  * Patches the Node.js module class method that is responsible for compiling code.
3310
3409
  * If a module is found that has an instrumentator, it will transform the code before compiling it
3311
- * with tracing channel methods.
3410
+ * with global hook calls.
3312
3411
  */
3313
3412
  patch() {
3314
3413
  const self = this;
@@ -3367,7 +3466,9 @@ function resolveModulePrototype() {
3367
3466
  }
3368
3467
 
3369
3468
  // src/node/apply-auto-instrumentation-entry.ts
3370
- var stateKey = /* @__PURE__ */ Symbol.for("braintrust.applyAutoInstrumentation");
3469
+ var stateKey = /* @__PURE__ */ Symbol.for(
3470
+ `braintrust.applyAutoInstrumentation.global-hooks.v${GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION}`
3471
+ );
3371
3472
  var existingState = Object.getOwnPropertyDescriptor(
3372
3473
  globalThis,
3373
3474
  stateKey
@@ -3384,7 +3485,6 @@ if (state !== existingState) {
3384
3485
  });
3385
3486
  }
3386
3487
  if (!state.applied) {
3387
- patchTracingChannel(diagnostics_channel.tracingChannel);
3388
3488
  const allConfigs = getDefaultAutoInstrumentationConfigs();
3389
3489
  const currentModuleUrl = getCurrentModuleUrl();
3390
3490
  register("./auto-instrumentations/loader/esm-hook.mjs", {