braintrust 3.13.0 → 3.14.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 (50) hide show
  1. package/dev/dist/index.d.mts +6 -8
  2. package/dev/dist/index.d.ts +6 -8
  3. package/dev/dist/index.js +809 -466
  4. package/dev/dist/index.mjs +367 -24
  5. package/dist/apply-auto-instrumentation.js +204 -174
  6. package/dist/apply-auto-instrumentation.mjs +35 -5
  7. package/dist/auto-instrumentations/bundler/esbuild.cjs +225 -1
  8. package/dist/auto-instrumentations/bundler/esbuild.mjs +2 -1
  9. package/dist/auto-instrumentations/bundler/next.cjs +225 -1
  10. package/dist/auto-instrumentations/bundler/next.mjs +3 -2
  11. package/dist/auto-instrumentations/bundler/rollup.cjs +225 -1
  12. package/dist/auto-instrumentations/bundler/rollup.mjs +2 -1
  13. package/dist/auto-instrumentations/bundler/vite.cjs +225 -1
  14. package/dist/auto-instrumentations/bundler/vite.mjs +2 -1
  15. package/dist/auto-instrumentations/bundler/webpack-loader.cjs +8 -0
  16. package/dist/auto-instrumentations/bundler/webpack.cjs +225 -1
  17. package/dist/auto-instrumentations/bundler/webpack.mjs +3 -2
  18. package/dist/auto-instrumentations/chunk-J57YF7WS.mjs +208 -0
  19. package/dist/auto-instrumentations/{chunk-WFEUJACP.mjs → chunk-OTUQ7KH5.mjs} +1 -1
  20. package/dist/auto-instrumentations/chunk-QFMACSOL.mjs +280 -0
  21. package/dist/auto-instrumentations/{chunk-GJOO4ESL.mjs → chunk-XKAAVWT6.mjs} +23 -1
  22. package/dist/auto-instrumentations/hook.mjs +7980 -7
  23. package/dist/auto-instrumentations/loader/cjs-patch.cjs +194 -4
  24. package/dist/auto-instrumentations/loader/cjs-patch.mjs +13 -27
  25. package/dist/auto-instrumentations/loader/esm-hook.mjs +24 -10
  26. package/dist/browser.d.mts +127 -11
  27. package/dist/browser.d.ts +127 -11
  28. package/dist/browser.js +293 -24
  29. package/dist/browser.mjs +293 -24
  30. package/dist/{chunk-26JGOELH.js → chunk-NKD77KGB.js} +179 -1
  31. package/dist/{chunk-75IQCUB2.mjs → chunk-NU2GSPHX.mjs} +179 -1
  32. package/dist/cli.js +374 -51
  33. package/dist/edge-light.d.mts +1 -1
  34. package/dist/edge-light.d.ts +1 -1
  35. package/dist/edge-light.js +293 -24
  36. package/dist/edge-light.mjs +293 -24
  37. package/dist/index.d.mts +127 -11
  38. package/dist/index.d.ts +127 -11
  39. package/dist/index.js +1113 -838
  40. package/dist/index.mjs +305 -30
  41. package/dist/instrumentation/index.d.mts +7 -8
  42. package/dist/instrumentation/index.d.ts +7 -8
  43. package/dist/instrumentation/index.js +101 -24
  44. package/dist/instrumentation/index.mjs +101 -24
  45. package/dist/workerd.d.mts +1 -1
  46. package/dist/workerd.d.ts +1 -1
  47. package/dist/workerd.js +293 -24
  48. package/dist/workerd.mjs +293 -24
  49. package/package.json +1 -7
  50. package/dist/auto-instrumentations/chunk-MWZXZQUO.mjs +0 -81
package/dist/browser.mjs CHANGED
@@ -3938,6 +3938,76 @@ var LRUCache = class {
3938
3938
  }
3939
3939
  };
3940
3940
 
3941
+ // src/prompt-cache/cache-config.ts
3942
+ var CACHE_LOCATION_ENV_VAR = "BRAINTRUST_CACHE_LOCATION";
3943
+ var DEFAULT_CACHE_MEMORY_MAX = 1 << 10;
3944
+ var DEFAULT_CACHE_DISK_MAX = 1 << 20;
3945
+ var warnedInvalidCacheModeEnvValue = false;
3946
+ var warnedUnavailableDiskCacheMode = false;
3947
+ function warnInvalidCacheMode(value) {
3948
+ if (warnedInvalidCacheModeEnvValue) {
3949
+ return;
3950
+ }
3951
+ warnedInvalidCacheModeEnvValue = true;
3952
+ debugLogger.warn(
3953
+ `Invalid ${CACHE_LOCATION_ENV_VAR} value "${value}". Expected "mixed", "memory", "disk", or "none". Falling back to "mixed".`
3954
+ );
3955
+ }
3956
+ function warnUnavailableDiskCache() {
3957
+ if (warnedUnavailableDiskCacheMode) {
3958
+ return;
3959
+ }
3960
+ warnedUnavailableDiskCacheMode = true;
3961
+ debugLogger.warn(
3962
+ `Disk cache is not supported on this platform, so ${CACHE_LOCATION_ENV_VAR}="disk" disables prompt and parameters caching.`
3963
+ );
3964
+ }
3965
+ function parseCacheMode() {
3966
+ const value = isomorph_default.getEnv(CACHE_LOCATION_ENV_VAR);
3967
+ const normalized = value?.trim().toLowerCase();
3968
+ if (!normalized) {
3969
+ return "mixed";
3970
+ }
3971
+ if (normalized === "mixed" || normalized === "memory" || normalized === "disk" || normalized === "none") {
3972
+ return normalized;
3973
+ }
3974
+ warnInvalidCacheMode(value ?? "");
3975
+ return "mixed";
3976
+ }
3977
+ function parsePositiveIntegerEnv(envVar, defaultValue) {
3978
+ const value = Number(isomorph_default.getEnv(envVar));
3979
+ return Number.isInteger(value) && value > 0 ? value : defaultValue;
3980
+ }
3981
+ function createCacheLayers({
3982
+ memoryMaxEnvVar,
3983
+ diskCacheDirEnvVar,
3984
+ diskMaxEnvVar,
3985
+ getDefaultDiskCacheDir
3986
+ }) {
3987
+ const mode = parseCacheMode();
3988
+ const memoryCache = mode === "mixed" || mode === "memory" ? new LRUCache({
3989
+ max: parsePositiveIntegerEnv(
3990
+ memoryMaxEnvVar,
3991
+ DEFAULT_CACHE_MEMORY_MAX
3992
+ )
3993
+ }) : void 0;
3994
+ let diskCache;
3995
+ if (mode === "mixed" || mode === "disk") {
3996
+ if (canUseDiskCache()) {
3997
+ diskCache = new DiskCache({
3998
+ cacheDir: isomorph_default.getEnv(diskCacheDirEnvVar) ?? getDefaultDiskCacheDir(),
3999
+ max: parsePositiveIntegerEnv(diskMaxEnvVar, DEFAULT_CACHE_DISK_MAX)
4000
+ });
4001
+ } else if (mode === "disk") {
4002
+ warnUnavailableDiskCache();
4003
+ }
4004
+ }
4005
+ if (diskCache) {
4006
+ return { memoryCache, diskCache };
4007
+ }
4008
+ return { memoryCache };
4009
+ }
4010
+
3941
4011
  // src/prompt-cache/prompt-cache.ts
3942
4012
  function createCacheKey(key) {
3943
4013
  if (key.id) {
@@ -3965,16 +4035,18 @@ var PromptCache = class {
3965
4035
  */
3966
4036
  async get(key) {
3967
4037
  const cacheKey = createCacheKey(key);
3968
- const memoryPrompt = this.memoryCache.get(cacheKey);
3969
- if (memoryPrompt !== void 0) {
3970
- return memoryPrompt;
4038
+ if (this.memoryCache) {
4039
+ const memoryPrompt = this.memoryCache.get(cacheKey);
4040
+ if (memoryPrompt !== void 0) {
4041
+ return memoryPrompt;
4042
+ }
3971
4043
  }
3972
4044
  if (this.diskCache) {
3973
4045
  const diskPrompt = await this.diskCache.get(cacheKey);
3974
4046
  if (!diskPrompt) {
3975
4047
  return void 0;
3976
4048
  }
3977
- this.memoryCache.set(cacheKey, diskPrompt);
4049
+ this.memoryCache?.set(cacheKey, diskPrompt);
3978
4050
  return diskPrompt;
3979
4051
  }
3980
4052
  return void 0;
@@ -3989,7 +4061,7 @@ var PromptCache = class {
3989
4061
  */
3990
4062
  async set(key, value) {
3991
4063
  const cacheKey = createCacheKey(key);
3992
- this.memoryCache.set(cacheKey, value);
4064
+ this.memoryCache?.set(cacheKey, value);
3993
4065
  if (this.diskCache) {
3994
4066
  await this.diskCache.set(cacheKey, value);
3995
4067
  }
@@ -4019,23 +4091,25 @@ var ParametersCache = class {
4019
4091
  }
4020
4092
  async get(key) {
4021
4093
  const cacheKey = createCacheKey2(key);
4022
- const memoryParams = this.memoryCache.get(cacheKey);
4023
- if (memoryParams !== void 0) {
4024
- return memoryParams;
4094
+ if (this.memoryCache) {
4095
+ const memoryParams = this.memoryCache.get(cacheKey);
4096
+ if (memoryParams !== void 0) {
4097
+ return memoryParams;
4098
+ }
4025
4099
  }
4026
4100
  if (this.diskCache) {
4027
4101
  const diskParams = await this.diskCache.get(cacheKey);
4028
4102
  if (!diskParams) {
4029
4103
  return void 0;
4030
4104
  }
4031
- this.memoryCache.set(cacheKey, diskParams);
4105
+ this.memoryCache?.set(cacheKey, diskParams);
4032
4106
  return diskParams;
4033
4107
  }
4034
4108
  return void 0;
4035
4109
  }
4036
4110
  async set(key, value) {
4037
4111
  const cacheKey = createCacheKey2(key);
4038
- this.memoryCache.set(cacheKey, value);
4112
+ this.memoryCache?.set(cacheKey, value);
4039
4113
  if (this.diskCache) {
4040
4114
  await this.diskCache.set(cacheKey, value);
4041
4115
  }
@@ -4567,21 +4641,22 @@ var BraintrustState = class _BraintrustState {
4567
4641
  setGlobalDebugLogLevel(void 0);
4568
4642
  }
4569
4643
  this.resetLoginInfo();
4570
- const memoryCache = new LRUCache({
4571
- max: Number(isomorph_default.getEnv("BRAINTRUST_PROMPT_CACHE_MEMORY_MAX")) ?? 1 << 10
4644
+ const { memoryCache, diskCache } = createCacheLayers({
4645
+ memoryMaxEnvVar: "BRAINTRUST_PROMPT_CACHE_MEMORY_MAX",
4646
+ diskCacheDirEnvVar: "BRAINTRUST_PROMPT_CACHE_DIR",
4647
+ diskMaxEnvVar: "BRAINTRUST_PROMPT_CACHE_DISK_MAX",
4648
+ getDefaultDiskCacheDir: () => `${isomorph_default.getEnv("HOME") ?? isomorph_default.homedir()}/.braintrust/prompt_cache`
4572
4649
  });
4573
- const diskCache = canUseDiskCache() ? new DiskCache({
4574
- cacheDir: isomorph_default.getEnv("BRAINTRUST_PROMPT_CACHE_DIR") ?? `${isomorph_default.getEnv("HOME") ?? isomorph_default.homedir()}/.braintrust/prompt_cache`,
4575
- max: Number(isomorph_default.getEnv("BRAINTRUST_PROMPT_CACHE_DISK_MAX")) ?? 1 << 20
4576
- }) : void 0;
4577
4650
  this.promptCache = new PromptCache({ memoryCache, diskCache });
4578
- const parametersMemoryCache = new LRUCache({
4579
- max: Number(isomorph_default.getEnv("BRAINTRUST_PARAMETERS_CACHE_MEMORY_MAX")) ?? 1 << 10
4651
+ const {
4652
+ memoryCache: parametersMemoryCache,
4653
+ diskCache: parametersDiskCache
4654
+ } = createCacheLayers({
4655
+ memoryMaxEnvVar: "BRAINTRUST_PARAMETERS_CACHE_MEMORY_MAX",
4656
+ diskCacheDirEnvVar: "BRAINTRUST_PARAMETERS_CACHE_DIR",
4657
+ diskMaxEnvVar: "BRAINTRUST_PARAMETERS_CACHE_DISK_MAX",
4658
+ getDefaultDiskCacheDir: () => `${isomorph_default.getEnv("HOME") ?? isomorph_default.homedir()}/.braintrust/parameters_cache`
4580
4659
  });
4581
- const parametersDiskCache = canUseDiskCache() ? new DiskCache({
4582
- cacheDir: isomorph_default.getEnv("BRAINTRUST_PARAMETERS_CACHE_DIR") ?? `${isomorph_default.getEnv("HOME") ?? isomorph_default.homedir()}/.braintrust/parameters_cache`,
4583
- max: Number(isomorph_default.getEnv("BRAINTRUST_PARAMETERS_CACHE_DISK_MAX")) ?? 1 << 20
4584
- }) : void 0;
4585
4660
  this.parametersCache = new ParametersCache({
4586
4661
  memoryCache: parametersMemoryCache,
4587
4662
  diskCache: parametersDiskCache
@@ -25598,7 +25673,7 @@ var BraintrustPlugin = class extends BasePlugin {
25598
25673
  this.config = config;
25599
25674
  }
25600
25675
  onEnable() {
25601
- const integrations = this.config.integrations || {};
25676
+ const integrations = this.config.integrations ?? {};
25602
25677
  if (integrations.openai !== false) {
25603
25678
  this.openaiPlugin = new OpenAIPlugin();
25604
25679
  this.openaiPlugin.enable();
@@ -25663,7 +25738,7 @@ var BraintrustPlugin = class extends BasePlugin {
25663
25738
  this.genkitPlugin = new GenkitPlugin();
25664
25739
  this.genkitPlugin.enable();
25665
25740
  }
25666
- if (getIntegrationConfig(integrations, "gitHubCopilot") !== false) {
25741
+ if (integrations.gitHubCopilot !== false) {
25667
25742
  this.gitHubCopilotPlugin = new GitHubCopilotPlugin();
25668
25743
  this.gitHubCopilotPlugin.enable();
25669
25744
  }
@@ -25776,6 +25851,7 @@ var envIntegrationAliases = {
25776
25851
  cursorsdk: "cursorSDK",
25777
25852
  flue: "flue",
25778
25853
  "flue-runtime": "flue",
25854
+ mastra: "mastra",
25779
25855
  "openai-agents": "openAIAgents",
25780
25856
  openaiagents: "openAIAgents",
25781
25857
  "openai-agents-core": "openAIAgents",
@@ -25818,6 +25894,7 @@ function getDefaultInstrumentationIntegrations() {
25818
25894
  cursor: true,
25819
25895
  cursorSDK: true,
25820
25896
  flue: true,
25897
+ mastra: true,
25821
25898
  openAIAgents: true,
25822
25899
  openrouter: true,
25823
25900
  openrouterAgent: true,
@@ -26075,6 +26152,7 @@ __export(exports_exports, {
26075
26152
  BaseExperiment: () => BaseExperiment,
26076
26153
  BraintrustLangChainCallbackHandler: () => BraintrustLangChainCallbackHandler,
26077
26154
  BraintrustMiddleware: () => BraintrustMiddleware,
26155
+ BraintrustObservabilityExporter: () => BraintrustObservabilityExporter,
26078
26156
  BraintrustState: () => BraintrustState,
26079
26157
  BraintrustStream: () => BraintrustStream,
26080
26158
  CachedSpanFetcher: () => CachedSpanFetcher,
@@ -27691,6 +27769,196 @@ function toolRunnerProxy(toolRunner, anthropic, channel2) {
27691
27769
  }
27692
27770
 
27693
27771
  // src/wrappers/mastra.ts
27772
+ var MASTRA_BRAINTRUST_EXPORTER_NAME = "braintrust";
27773
+ var SPAN_TYPE_MAP = {
27774
+ agent_run: "task" /* TASK */,
27775
+ model_generation: "llm" /* LLM */,
27776
+ model_step: "llm" /* LLM */,
27777
+ model_chunk: "llm" /* LLM */,
27778
+ tool_call: "tool" /* TOOL */,
27779
+ mcp_tool_call: "tool" /* TOOL */,
27780
+ workflow_run: "task" /* TASK */,
27781
+ workflow_step: "function" /* FUNCTION */,
27782
+ workflow_conditional: "function" /* FUNCTION */,
27783
+ workflow_conditional_eval: "function" /* FUNCTION */,
27784
+ workflow_parallel: "function" /* FUNCTION */,
27785
+ workflow_loop: "function" /* FUNCTION */,
27786
+ workflow_sleep: "function" /* FUNCTION */,
27787
+ workflow_wait_event: "function" /* FUNCTION */,
27788
+ memory_operation: "function" /* FUNCTION */,
27789
+ workspace_action: "function" /* FUNCTION */,
27790
+ rag_ingestion: "task" /* TASK */,
27791
+ rag_embedding: "llm" /* LLM */,
27792
+ rag_vector_operation: "function" /* FUNCTION */,
27793
+ rag_action: "function" /* FUNCTION */,
27794
+ graph_action: "function" /* FUNCTION */,
27795
+ scorer_run: "score" /* SCORE */,
27796
+ scorer_step: "score" /* SCORE */,
27797
+ processor_run: "function" /* FUNCTION */,
27798
+ generic: "function" /* FUNCTION */
27799
+ };
27800
+ function spanTypeFor(mastraType) {
27801
+ return SPAN_TYPE_MAP[mastraType] ?? "function" /* FUNCTION */;
27802
+ }
27803
+ function epochSeconds(value) {
27804
+ if (value === void 0) return void 0;
27805
+ const ms = value instanceof Date ? value.getTime() : typeof value === "number" ? value : Date.parse(value);
27806
+ return Number.isFinite(ms) ? ms / 1e3 : void 0;
27807
+ }
27808
+ function modelMetrics(attributes) {
27809
+ if (!isObject(attributes)) return void 0;
27810
+ const usage = isObject(attributes.usage) ? attributes.usage : void 0;
27811
+ if (!usage) return void 0;
27812
+ const out = {};
27813
+ if (typeof usage.inputTokens === "number")
27814
+ out.prompt_tokens = usage.inputTokens;
27815
+ if (typeof usage.outputTokens === "number")
27816
+ out.completion_tokens = usage.outputTokens;
27817
+ if (typeof usage.inputTokens === "number" && typeof usage.outputTokens === "number") {
27818
+ out.tokens = usage.inputTokens + usage.outputTokens;
27819
+ }
27820
+ const inputDetails = isObject(usage.inputDetails) ? usage.inputDetails : void 0;
27821
+ const outputDetails = isObject(usage.outputDetails) ? usage.outputDetails : void 0;
27822
+ if (inputDetails && typeof inputDetails.cacheRead === "number") {
27823
+ out.prompt_cached_tokens = inputDetails.cacheRead;
27824
+ }
27825
+ if (inputDetails && typeof inputDetails.cacheWrite === "number") {
27826
+ out.prompt_cache_creation_tokens = inputDetails.cacheWrite;
27827
+ }
27828
+ if (outputDetails && typeof outputDetails.reasoning === "number") {
27829
+ out.completion_reasoning_tokens = outputDetails.reasoning;
27830
+ }
27831
+ return Object.keys(out).length > 0 ? out : void 0;
27832
+ }
27833
+ function buildMetadata(exported) {
27834
+ const out = {};
27835
+ if (exported.entityId !== void 0) out.entity_id = exported.entityId;
27836
+ if (exported.entityName !== void 0) out.entity_name = exported.entityName;
27837
+ if (exported.entityType !== void 0) out.entity_type = exported.entityType;
27838
+ if (exported.metadata && isObject(exported.metadata)) {
27839
+ Object.assign(out, exported.metadata);
27840
+ }
27841
+ if (exported.attributes && isObject(exported.attributes)) {
27842
+ for (const [key, value] of Object.entries(exported.attributes)) {
27843
+ if (key === "usage") continue;
27844
+ if (value !== void 0) out[key] = value;
27845
+ }
27846
+ }
27847
+ if (exported.tags && exported.tags.length > 0) {
27848
+ out.tags = exported.tags;
27849
+ }
27850
+ if (exported.requestContext && isObject(exported.requestContext)) {
27851
+ out.request_context = exported.requestContext;
27852
+ }
27853
+ return out;
27854
+ }
27855
+ var BraintrustObservabilityExporter = class {
27856
+ name = MASTRA_BRAINTRUST_EXPORTER_NAME;
27857
+ spans = /* @__PURE__ */ new Map();
27858
+ // Captured at the first SPAN_STARTED event. Mastra's observability bus may
27859
+ // dispatch later events outside the user's AsyncLocalStorage context, where
27860
+ // `currentSpan()` returns NOOP_SPAN — which would make our `startSpan()`
27861
+ // calls go to a no-op logger and silently drop. Anchoring on the parent
27862
+ // we observe while still in-context keeps the whole Mastra subtree under
27863
+ // the user's traced scenario.
27864
+ capturedParent;
27865
+ constructor() {
27866
+ _internalSetInitialState();
27867
+ }
27868
+ async exportTracingEvent(event) {
27869
+ const exported = event.exportedSpan;
27870
+ if (exported.isInternal === true) return;
27871
+ try {
27872
+ switch (event.type) {
27873
+ case "span_started":
27874
+ this.onStart(exported);
27875
+ break;
27876
+ case "span_updated":
27877
+ this.onUpdate(exported);
27878
+ break;
27879
+ case "span_ended":
27880
+ this.onEnd(exported);
27881
+ break;
27882
+ }
27883
+ } catch (err) {
27884
+ logExporterError(err);
27885
+ }
27886
+ }
27887
+ async flush() {
27888
+ const state = _internalGetGlobalState();
27889
+ if (state) {
27890
+ await state.bgLogger().flush();
27891
+ }
27892
+ }
27893
+ async shutdown() {
27894
+ await this.flush();
27895
+ this.spans.clear();
27896
+ }
27897
+ onStart(exported) {
27898
+ if (this.spans.has(exported.id)) return;
27899
+ const args = {
27900
+ name: exported.name,
27901
+ spanAttributes: { type: spanTypeFor(exported.type) },
27902
+ startTime: epochSeconds(exported.startTime)
27903
+ };
27904
+ const parentRecord = exported.parentSpanId ? this.spans.get(exported.parentSpanId) : void 0;
27905
+ if (!this.capturedParent) {
27906
+ const probe = currentSpan();
27907
+ if (probe && probe.spanId) {
27908
+ this.capturedParent = probe;
27909
+ }
27910
+ }
27911
+ const span = parentRecord ? parentRecord.span.startSpan(args) : this.capturedParent ? this.capturedParent.startSpan(args) : startSpan(args);
27912
+ const record = { span, hasLoggedInput: false };
27913
+ this.logPayload(record, exported);
27914
+ this.spans.set(exported.id, record);
27915
+ if (exported.isEvent === true) {
27916
+ span.end({ endTime: args.startTime });
27917
+ this.spans.delete(exported.id);
27918
+ }
27919
+ }
27920
+ onUpdate(exported) {
27921
+ const record = this.spans.get(exported.id);
27922
+ if (!record) return;
27923
+ this.logPayload(record, exported);
27924
+ }
27925
+ onEnd(exported) {
27926
+ const record = this.spans.get(exported.id);
27927
+ if (!record) return;
27928
+ this.logPayload(record, exported);
27929
+ if (exported.errorInfo) {
27930
+ record.span.log({
27931
+ error: exported.errorInfo.message || exported.errorInfo.name || "Unknown Mastra error"
27932
+ });
27933
+ }
27934
+ record.span.end({ endTime: epochSeconds(exported.endTime) });
27935
+ this.spans.delete(exported.id);
27936
+ }
27937
+ logPayload(record, exported) {
27938
+ const event = {};
27939
+ if (exported.input !== void 0) {
27940
+ event.input = exported.input;
27941
+ record.hasLoggedInput = true;
27942
+ }
27943
+ if (exported.output !== void 0) {
27944
+ event.output = exported.output;
27945
+ }
27946
+ const metadata = buildMetadata(exported);
27947
+ if (Object.keys(metadata).length > 0) {
27948
+ event.metadata = metadata;
27949
+ }
27950
+ const metrics = modelMetrics(exported.attributes);
27951
+ if (metrics) {
27952
+ event.metrics = metrics;
27953
+ }
27954
+ if (Object.keys(event).length > 0) {
27955
+ record.span.log(event);
27956
+ }
27957
+ }
27958
+ };
27959
+ function logExporterError(err) {
27960
+ debugLogger.warn("Mastra exporter failure:", err);
27961
+ }
27694
27962
  function wrapMastraAgent(agent, _options) {
27695
27963
  return agent;
27696
27964
  }
@@ -33189,6 +33457,7 @@ export {
33189
33457
  BaseExperiment,
33190
33458
  BraintrustLangChainCallbackHandler,
33191
33459
  BraintrustMiddleware,
33460
+ BraintrustObservabilityExporter,
33192
33461
  BraintrustState,
33193
33462
  BraintrustStream,
33194
33463
  CachedSpanFetcher,
@@ -685,6 +685,7 @@ var envIntegrationAliases = {
685
685
  cursorsdk: "cursorSDK",
686
686
  flue: "flue",
687
687
  "flue-runtime": "flue",
688
+ mastra: "mastra",
688
689
  "openai-agents": "openAIAgents",
689
690
  openaiagents: "openAIAgents",
690
691
  "openai-agents-core": "openAIAgents",
@@ -727,6 +728,7 @@ function getDefaultInstrumentationIntegrations() {
727
728
  cursor: true,
728
729
  cursorSDK: true,
729
730
  flue: true,
731
+ mastra: true,
730
732
  openAIAgents: true,
731
733
  openrouter: true,
732
734
  openrouterAgent: true,
@@ -755,6 +757,179 @@ function isInstrumentationIntegrationDisabled(integrations, ...names) {
755
757
  return names.some((name) => _optionalChain([integrations, 'optionalAccess', _34 => _34[name]]) === false);
756
758
  }
757
759
 
760
+ // src/auto-instrumentations/loader/mastra-observability-patch.ts
761
+ var MASTRA_EXPORTER_FACTORY_GLOBAL = "__braintrustMastraExporterFactory";
762
+ function installMastraExporterFactory(factory) {
763
+ const globals = globalThis;
764
+ globals[MASTRA_EXPORTER_FACTORY_GLOBAL] ??= factory;
765
+ }
766
+ var MASTRA_CORE_PACKAGE = "@mastra/core";
767
+ var MASTRA_OBSERVABILITY_PACKAGE = "@mastra/observability";
768
+ var MASTRA_CORE_ENTRY_PATHS = /* @__PURE__ */ new Set([
769
+ "dist/index.js",
770
+ "dist/index.cjs",
771
+ "dist/mastra/index.js",
772
+ "dist/mastra/index.cjs"
773
+ ]);
774
+ var MASTRA_OBSERVABILITY_ENTRY_PATHS = /* @__PURE__ */ new Set([
775
+ "dist/index.js",
776
+ "dist/index.cjs"
777
+ ]);
778
+ function classifyMastraTarget(packageName, modulePath) {
779
+ if (packageName === MASTRA_CORE_PACKAGE && MASTRA_CORE_ENTRY_PATHS.has(modulePath)) {
780
+ return "core";
781
+ }
782
+ if (packageName === MASTRA_OBSERVABILITY_PACKAGE && MASTRA_OBSERVABILITY_ENTRY_PATHS.has(modulePath)) {
783
+ return "observability";
784
+ }
785
+ return null;
786
+ }
787
+ function extractChunkPath(source) {
788
+ const esmMatch = source.match(
789
+ /export\s*\{\s*Mastra(?:\s+as\s+\w+)?\s*\}\s*from\s*['"]([^'"]+)['"]/
790
+ );
791
+ if (esmMatch) return esmMatch[1];
792
+ const cjsMatch = source.match(
793
+ /require\s*\(\s*['"]([^'"]+chunk-[^'"]+)['"]\s*\)/
794
+ );
795
+ if (cjsMatch) return cjsMatch[1];
796
+ return null;
797
+ }
798
+ var EXPORTER_FACTORY_KEY = JSON.stringify(MASTRA_EXPORTER_FACTORY_GLOBAL);
799
+ var MASTRA_PROXY_HANDLER_BODY = `
800
+ {
801
+ construct(target, args, newTarget) {
802
+ var firstArg = args[0];
803
+ if (
804
+ (!firstArg || typeof firstArg !== "object" || !firstArg.observability) &&
805
+ __braintrustObservabilityClass
806
+ ) {
807
+ try {
808
+ // serviceName is required by Mastra's Observability validator; pass
809
+ // something sensible by default. Users who want a different name
810
+ // should construct Observability themselves.
811
+ var observability = new __braintrustObservabilityClass({
812
+ configs: { default: { serviceName: "mastra" } },
813
+ });
814
+ args = args.slice();
815
+ args[0] = Object.assign({}, firstArg, { observability: observability });
816
+ } catch (e) {
817
+ // Fall through. Mastra will use its own NoOp; user code still works,
818
+ // just without auto-instrumentation.
819
+ }
820
+ }
821
+ return Reflect.construct(target, args, newTarget);
822
+ },
823
+ }`;
824
+ function buildMastraEsmWrapper(chunkPath) {
825
+ const chunk = JSON.stringify(chunkPath);
826
+ return `import { Mastra as __braintrustOrigMastra } from ${chunk};
827
+ import { createRequire as __braintrustCreateRequire } from "node:module";
828
+
829
+ let __braintrustObservabilityClass = null;
830
+ try {
831
+ // Resolve @mastra/observability relative to this module (the Mastra entry),
832
+ // so it's looked up from the user's node_modules tree.
833
+ const __braintrustRequire = __braintrustCreateRequire(import.meta.url);
834
+ __braintrustObservabilityClass =
835
+ __braintrustRequire("@mastra/observability").Observability;
836
+ } catch (e) {
837
+ // @mastra/observability isn't installed; the construct trap will skip the
838
+ // auto-construct branch and Mastra falls back to its own NoOp.
839
+ }
840
+ const Mastra = new Proxy(__braintrustOrigMastra, ${MASTRA_PROXY_HANDLER_BODY});
841
+ export { Mastra };
842
+ `;
843
+ }
844
+ function buildMastraCjsWrapper(chunkPath) {
845
+ const chunk = JSON.stringify(chunkPath);
846
+ return `'use strict';
847
+ const __braintrustChunk = require(${chunk});
848
+
849
+ let __braintrustObservabilityClass = null;
850
+ try {
851
+ __braintrustObservabilityClass = require("@mastra/observability").Observability;
852
+ } catch (e) {
853
+ // @mastra/observability isn't installed; same fallback as the ESM wrapper.
854
+ }
855
+
856
+ const __braintrustWrappedMastra = new Proxy(
857
+ __braintrustChunk.Mastra,
858
+ ${MASTRA_PROXY_HANDLER_BODY},
859
+ );
860
+ Object.defineProperty(exports, "Mastra", {
861
+ enumerable: true,
862
+ configurable: true,
863
+ get: function () { return __braintrustWrappedMastra; }
864
+ });
865
+ `;
866
+ }
867
+ var OBSERVABILITY_APPEND_BODY = `
868
+ ;(function __braintrustWrapObservability() {
869
+ // Top-level so we can both read and reassign the var binding the original
870
+ // entry declared.
871
+ if (typeof Observability === "undefined") return;
872
+ if (Observability.__braintrustWrapped) return;
873
+ function __braintrustEnsureExporter(rawConfig) {
874
+ try {
875
+ var factory = globalThis[${EXPORTER_FACTORY_KEY}];
876
+ if (typeof factory !== "function") return rawConfig;
877
+ var config = rawConfig && typeof rawConfig === "object" ? rawConfig : {};
878
+ var configsIn = config.configs && typeof config.configs === "object" ? config.configs : null;
879
+ var configsOut = {};
880
+ var hadEntries = false;
881
+ if (configsIn) {
882
+ for (var name in configsIn) {
883
+ if (!Object.prototype.hasOwnProperty.call(configsIn, name)) continue;
884
+ hadEntries = true;
885
+ var inst = configsIn[name] || {};
886
+ var existing = Array.isArray(inst.exporters) ? inst.exporters : [];
887
+ var hasOurs = existing.some(function (e) { return e && e.name === "braintrust"; });
888
+ configsOut[name] = Object.assign({}, inst, {
889
+ exporters: hasOurs ? existing : existing.concat([factory()]),
890
+ });
891
+ }
892
+ }
893
+ if (!hadEntries) {
894
+ configsOut.default = {
895
+ serviceName: "mastra",
896
+ exporters: [factory()],
897
+ };
898
+ }
899
+ return Object.assign({}, config, { configs: configsOut });
900
+ } catch (e) {
901
+ return rawConfig;
902
+ }
903
+ }
904
+ var __OriginalObservability = Observability;
905
+ Observability = new Proxy(__OriginalObservability, {
906
+ construct: function (target, args, newTarget) {
907
+ var nextArgs = args.slice();
908
+ nextArgs[0] = __braintrustEnsureExporter(nextArgs[0]);
909
+ return Reflect.construct(target, nextArgs, newTarget);
910
+ },
911
+ });
912
+ Observability.__braintrustWrapped = true;
913
+ if (typeof exports !== "undefined" && exports && typeof exports === "object") {
914
+ try {
915
+ Object.defineProperty(exports, "Observability", {
916
+ enumerable: true,
917
+ configurable: true,
918
+ get: function () { return Observability; },
919
+ });
920
+ } catch (e) {}
921
+ }
922
+ })();
923
+ `;
924
+ function patchMastraSource(source, target, format) {
925
+ if (target === "core") {
926
+ const chunkPath = extractChunkPath(source);
927
+ if (!chunkPath) return source;
928
+ return format === "esm" ? buildMastraEsmWrapper(chunkPath) : buildMastraCjsWrapper(chunkPath);
929
+ }
930
+ return source + OBSERVABILITY_APPEND_BODY;
931
+ }
932
+
758
933
  // src/instrumentation/plugins/openai-agents-channels.ts
759
934
  var openAIAgentsCoreChannels = defineChannels("@openai/agents-core", {
760
935
  onTraceStart: channel({
@@ -814,4 +989,7 @@ var langChainChannels = defineChannels("@langchain/core", {
814
989
 
815
990
 
816
991
 
817
- exports.__export = __export; exports.patchTracingChannel = patchTracingChannel; exports.isomorph_default = isomorph_default; exports.openAIChannels = openAIChannels; exports.openAICodexChannels = openAICodexChannels; exports.anthropicChannels = anthropicChannels; exports.aiSDKChannels = aiSDKChannels; exports.claudeAgentSDKChannels = claudeAgentSDKChannels; exports.cursorSDKChannels = cursorSDKChannels; exports.openAIAgentsCoreChannels = openAIAgentsCoreChannels; exports.googleGenAIChannels = googleGenAIChannels; exports.huggingFaceChannels = huggingFaceChannels; exports.openRouterAgentChannels = openRouterAgentChannels; exports.openRouterChannels = openRouterChannels; exports.mistralChannels = mistralChannels; exports.googleADKChannels = googleADKChannels; exports.cohereChannels = cohereChannels; exports.groqChannels = groqChannels; exports.genkitChannels = genkitChannels; exports.genkitCoreChannels = genkitCoreChannels; exports.gitHubCopilotChannels = gitHubCopilotChannels; exports.flueChannels = flueChannels; exports.langChainChannels = langChainChannels; exports.getDefaultInstrumentationIntegrations = getDefaultInstrumentationIntegrations; exports.readDisabledInstrumentationEnvConfig = readDisabledInstrumentationEnvConfig; exports.isInstrumentationIntegrationDisabled = isInstrumentationIntegrationDisabled;
992
+
993
+
994
+
995
+ exports.__export = __export; exports.patchTracingChannel = patchTracingChannel; exports.isomorph_default = isomorph_default; exports.openAIChannels = openAIChannels; exports.openAICodexChannels = openAICodexChannels; exports.anthropicChannels = anthropicChannels; exports.aiSDKChannels = aiSDKChannels; exports.claudeAgentSDKChannels = claudeAgentSDKChannels; exports.cursorSDKChannels = cursorSDKChannels; exports.openAIAgentsCoreChannels = openAIAgentsCoreChannels; exports.googleGenAIChannels = googleGenAIChannels; exports.huggingFaceChannels = huggingFaceChannels; exports.openRouterAgentChannels = openRouterAgentChannels; exports.openRouterChannels = openRouterChannels; exports.mistralChannels = mistralChannels; exports.googleADKChannels = googleADKChannels; exports.cohereChannels = cohereChannels; exports.groqChannels = groqChannels; exports.genkitChannels = genkitChannels; exports.genkitCoreChannels = genkitCoreChannels; exports.gitHubCopilotChannels = gitHubCopilotChannels; exports.flueChannels = flueChannels; exports.langChainChannels = langChainChannels; exports.getDefaultInstrumentationIntegrations = getDefaultInstrumentationIntegrations; exports.readDisabledInstrumentationEnvConfig = readDisabledInstrumentationEnvConfig; exports.isInstrumentationIntegrationDisabled = isInstrumentationIntegrationDisabled; exports.installMastraExporterFactory = installMastraExporterFactory; exports.classifyMastraTarget = classifyMastraTarget; exports.patchMastraSource = patchMastraSource;