"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;var __defProp = Object.defineProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};

// src/auto-instrumentations/patch-tracing-channel.ts
function patchTracingChannel(tracingChannelFn) {
  const dummyChannel = tracingChannelFn("__braintrust_probe__");
  const TracingChannel = _optionalChain([dummyChannel, 'optionalAccess', _2 => _2.constructor]);
  if (!_optionalChain([TracingChannel, 'optionalAccess', _3 => _3.prototype])) {
    return;
  }
  if (!Object.getOwnPropertyDescriptor(TracingChannel.prototype, "hasSubscribers")) {
    Object.defineProperty(TracingChannel.prototype, "hasSubscribers", {
      configurable: true,
      enumerable: false,
      get() {
        return Boolean(
          _optionalChain([this, 'access', _4 => _4.start, 'optionalAccess', _5 => _5.hasSubscribers]) || _optionalChain([this, 'access', _6 => _6.end, 'optionalAccess', _7 => _7.hasSubscribers]) || _optionalChain([this, 'access', _8 => _8.asyncStart, 'optionalAccess', _9 => _9.hasSubscribers]) || _optionalChain([this, 'access', _10 => _10.asyncEnd, 'optionalAccess', _11 => _11.hasSubscribers]) || _optionalChain([this, 'access', _12 => _12.error, 'optionalAccess', _13 => _13.hasSubscribers])
        );
      }
    });
  }
  if (TracingChannel.prototype.tracePromise) {
    TracingChannel.prototype.tracePromise = function(fn, context = {}, thisArg, ...args) {
      const start = this.start;
      const end = this.end;
      const asyncStart = this.asyncStart;
      const asyncEnd = this.asyncEnd;
      const error = this.error;
      function publishRejected(err) {
        context.error = err;
        _optionalChain([error, 'optionalAccess', _14 => _14.publish, 'call', _15 => _15(context)]);
        _optionalChain([asyncStart, 'optionalAccess', _16 => _16.publish, 'call', _17 => _17(context)]);
        _optionalChain([asyncEnd, 'optionalAccess', _18 => _18.publish, 'call', _19 => _19(context)]);
      }
      function publishResolved(result) {
        context.result = result;
        _optionalChain([asyncStart, 'optionalAccess', _20 => _20.publish, 'call', _21 => _21(context)]);
        _optionalChain([asyncEnd, 'optionalAccess', _22 => _22.publish, 'call', _23 => _23(context)]);
      }
      return start.runStores(context, () => {
        try {
          const result = Reflect.apply(fn, thisArg, args);
          _optionalChain([end, 'optionalAccess', _24 => _24.publish, 'call', _25 => _25(context)]);
          if (result && (typeof result === "object" || typeof result === "function") && typeof result.then === "function") {
            if (result.constructor === Promise) {
              return result.then(
                (res) => {
                  publishResolved(res);
                  return res;
                },
                (err) => {
                  publishRejected(err);
                  return Promise.reject(err);
                }
              );
            }
            void result.then(
              // eslint-disable-next-line @typescript-eslint/no-explicit-any
              (resolved) => {
                try {
                  publishResolved(resolved);
                } catch (e) {
                }
              },
              // eslint-disable-next-line @typescript-eslint/no-explicit-any
              (err) => {
                try {
                  publishRejected(err);
                } catch (e2) {
                }
              }
            );
            return result;
          }
          context.result = result;
          _optionalChain([asyncStart, 'optionalAccess', _26 => _26.publish, 'call', _27 => _27(context)]);
          _optionalChain([asyncEnd, 'optionalAccess', _28 => _28.publish, 'call', _29 => _29(context)]);
          return result;
        } catch (err) {
          context.error = err;
          _optionalChain([error, 'optionalAccess', _30 => _30.publish, 'call', _31 => _31(context)]);
          _optionalChain([end, 'optionalAccess', _32 => _32.publish, 'call', _33 => _33(context)]);
          throw err;
        }
      });
    };
  }
}

// src/isomorph.ts
var DefaultAsyncLocalStorage = class {
  constructor() {
  }
  enterWith(_) {
  }
  run(_, callback) {
    return callback();
  }
  getStore() {
    return void 0;
  }
};
var DefaultChannel = (_class = class {
  constructor(name) {;_class.prototype.__init.call(this);
    this.name = name;
  }
  __init() {this.hasSubscribers = false}
  subscribe(_subscription) {
  }
  unsubscribe(_subscription) {
    return false;
  }
  bindStore(_store, _transform) {
  }
  unbindStore(_store) {
    return false;
  }
  publish(_message) {
  }
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  runStores(_message, fn, thisArg, ...args) {
    return fn.apply(thisArg, args);
  }
}, _class);
var DefaultTracingChannel = class {
  
  
  
  
  
  constructor(nameOrChannels) {
    if (typeof nameOrChannels === "string") {
      this.start = new DefaultChannel(`tracing:${nameOrChannels}:start`);
      this.end = new DefaultChannel(`tracing:${nameOrChannels}:end`);
      this.asyncStart = new DefaultChannel(
        `tracing:${nameOrChannels}:asyncStart`
      );
      this.asyncEnd = new DefaultChannel(`tracing:${nameOrChannels}:asyncEnd`);
      this.error = new DefaultChannel(`tracing:${nameOrChannels}:error`);
      return;
    }
    this.start = _nullishCoalesce(nameOrChannels.start, () => ( new DefaultChannel("tracing:start")));
    this.end = _nullishCoalesce(nameOrChannels.end, () => ( new DefaultChannel("tracing:end")));
    this.asyncStart = _nullishCoalesce(nameOrChannels.asyncStart, () => ( new DefaultChannel("tracing:asyncStart")));
    this.asyncEnd = _nullishCoalesce(nameOrChannels.asyncEnd, () => ( new DefaultChannel("tracing:asyncEnd")));
    this.error = _nullishCoalesce(nameOrChannels.error, () => ( new DefaultChannel("tracing:error")));
  }
  get hasSubscribers() {
    return this.start.hasSubscribers || this.end.hasSubscribers || this.asyncStart.hasSubscribers || this.asyncEnd.hasSubscribers || this.error.hasSubscribers;
  }
  subscribe(_handlers) {
  }
  unsubscribe(_handlers) {
    return false;
  }
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  traceSync(fn, _message, thisArg, ...args) {
    return fn.apply(thisArg, args);
  }
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  tracePromise(fn, _message, thisArg, ...args) {
    return fn.apply(thisArg, args);
  }
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  traceCallback(fn, _position, _message, thisArg, ...args) {
    return fn.apply(thisArg, args);
  }
};
var iso = {
  buildType: "unknown",
  // Will be set by configureBrowser() or configureNode()
  getRepoInfo: async (_settings) => void 0,
  getPastNAncestors: async () => [],
  getEnv: (_name) => void 0,
  getBraintrustApiKey: async () => void 0,
  getCallerLocation: () => void 0,
  newAsyncLocalStorage: () => new DefaultAsyncLocalStorage(),
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  newTracingChannel: (nameOrChannels) => new DefaultTracingChannel(nameOrChannels),
  processOn: (_0, _1) => {
  },
  basename: (filepath) => filepath.split(/[\\/]/).pop() || filepath,
  // eslint-disable-next-line no-restricted-properties -- preserving intentional console usage.
  writeln: (text) => console.log(text)
};
var isomorph_default = iso;

// src/instrumentation/core/channel-definitions.ts
function channel(spec) {
  return spec;
}
function defineChannels(pkg, channels) {
  return Object.fromEntries(
    Object.entries(channels).map(([key, spec]) => {
      const fullChannelName = `orchestrion:${pkg}:${spec.channelName}`;
      if (spec.kind === "async") {
        const asyncSpec = spec;
        const tracingChannel2 = () => isomorph_default.newTracingChannel(
          fullChannelName
        );
        return [
          key,
          {
            ...asyncSpec,
            tracingChannel: tracingChannel2,
            tracePromise: (fn, context) => tracingChannel2().tracePromise(
              fn,
              // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
              context
            )
          }
        ];
      }
      const syncSpec = spec;
      const tracingChannel = () => isomorph_default.newTracingChannel(
        fullChannelName
      );
      return [
        key,
        {
          ...syncSpec,
          tracingChannel,
          traceSync: (fn, context) => tracingChannel().traceSync(
            fn,
            // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
            context
          )
        }
      ];
    })
  );
}

// src/instrumentation/plugins/openai-channels.ts
var openAIChannels = defineChannels("openai", {
  chatCompletionsCreate: channel({
    channelName: "chat.completions.create",
    kind: "async"
  }),
  embeddingsCreate: channel({
    channelName: "embeddings.create",
    kind: "async"
  }),
  betaChatCompletionsParse: channel({
    channelName: "beta.chat.completions.parse",
    kind: "async"
  }),
  betaChatCompletionsStream: channel({
    channelName: "beta.chat.completions.stream",
    kind: "sync-stream"
  }),
  moderationsCreate: channel({
    channelName: "moderations.create",
    kind: "async"
  }),
  responsesCreate: channel({
    channelName: "responses.create",
    kind: "async"
  }),
  responsesStream: channel({
    channelName: "responses.stream",
    kind: "sync-stream"
  }),
  responsesParse: channel({
    channelName: "responses.parse",
    kind: "async"
  }),
  responsesCompact: channel({
    channelName: "responses.compact",
    kind: "async"
  })
});

// src/instrumentation/plugins/openai-codex-channels.ts
var openAICodexChannels = defineChannels("@openai/codex-sdk", {
  run: channel({
    channelName: "Thread.run",
    kind: "async"
  }),
  runStreamed: channel({
    channelName: "Thread.runStreamed",
    kind: "async"
  })
});

// src/instrumentation/plugins/anthropic-channels.ts
var anthropicChannels = defineChannels("@anthropic-ai/sdk", {
  messagesCreate: channel({
    channelName: "messages.create",
    kind: "async"
  }),
  betaMessagesCreate: channel({
    channelName: "beta.messages.create",
    kind: "async"
  }),
  betaMessagesToolRunner: channel({
    channelName: "beta.messages.toolRunner",
    kind: "sync-stream"
  })
});

// src/instrumentation/plugins/ai-sdk-channels.ts
var aiSDKChannels = defineChannels("ai", {
  generateText: channel({
    channelName: "generateText",
    kind: "async"
  }),
  streamText: channel({
    channelName: "streamText",
    kind: "async"
  }),
  streamTextSync: channel({
    channelName: "streamText.sync",
    kind: "sync-stream"
  }),
  generateObject: channel({
    channelName: "generateObject",
    kind: "async"
  }),
  streamObject: channel({
    channelName: "streamObject",
    kind: "async"
  }),
  streamObjectSync: channel({
    channelName: "streamObject.sync",
    kind: "sync-stream"
  }),
  embed: channel(
    {
      channelName: "embed",
      kind: "async"
    }
  ),
  embedMany: channel({
    channelName: "embedMany",
    kind: "async"
  }),
  rerank: channel({
    channelName: "rerank",
    kind: "async"
  }),
  agentGenerate: channel({
    channelName: "Agent.generate",
    kind: "async"
  }),
  agentStream: channel({
    channelName: "Agent.stream",
    kind: "async"
  }),
  agentStreamSync: channel({
    channelName: "Agent.stream.sync",
    kind: "sync-stream"
  }),
  toolLoopAgentGenerate: channel({
    channelName: "ToolLoopAgent.generate",
    kind: "async"
  }),
  toolLoopAgentStream: channel({
    channelName: "ToolLoopAgent.stream",
    kind: "async"
  }),
  workflowAgentStream: channel({
    channelName: "WorkflowAgent.stream",
    kind: "async"
  }),
  v7CreateTelemetryDispatcher: channel({
    channelName: "createTelemetryDispatcher",
    kind: "sync-stream"
  })
});

// src/instrumentation/plugins/claude-agent-sdk-channels.ts
var claudeAgentSDKChannels = defineChannels(
  "@anthropic-ai/claude-agent-sdk",
  {
    query: channel({
      channelName: "query",
      kind: "sync-stream"
    })
  }
);

// src/instrumentation/plugins/cursor-sdk-channels.ts
var cursorSDKChannels = defineChannels("@cursor/sdk", {
  create: channel({
    channelName: "Agent.create",
    kind: "async"
  }),
  resume: channel({
    channelName: "Agent.resume",
    kind: "async"
  }),
  prompt: channel({
    channelName: "Agent.prompt",
    kind: "async"
  }),
  send: channel({
    channelName: "agent.send",
    kind: "async"
  })
});

// src/instrumentation/plugins/google-genai-channels.ts
var googleGenAIChannels = defineChannels("@google/genai", {
  generateContent: channel({
    channelName: "models.generateContent",
    kind: "async"
  }),
  generateContentStream: channel({
    channelName: "models.generateContentStream",
    kind: "async"
  }),
  embedContent: channel({
    channelName: "models.embedContent",
    kind: "async"
  }),
  interactionsCreate: channel({
    channelName: "interactions.create",
    kind: "async"
  })
});

// src/instrumentation/plugins/huggingface-channels.ts
var huggingFaceChannels = defineChannels("@huggingface/inference", {
  chatCompletion: channel({
    channelName: "chatCompletion",
    kind: "async"
  }),
  chatCompletionStream: channel({
    channelName: "chatCompletionStream",
    kind: "sync-stream"
  }),
  textGeneration: channel({
    channelName: "textGeneration",
    kind: "async"
  }),
  textGenerationStream: channel({
    channelName: "textGenerationStream",
    kind: "sync-stream"
  }),
  featureExtraction: channel({
    channelName: "featureExtraction",
    kind: "async"
  })
});

// src/instrumentation/plugins/openrouter-agent-channels.ts
var openRouterAgentChannels = defineChannels("@openrouter/agent", {
  callModel: channel({
    channelName: "callModel",
    kind: "sync-stream"
  }),
  callModelTurn: channel({
    channelName: "callModel.turn",
    kind: "async"
  }),
  toolExecute: channel({
    channelName: "tool.execute",
    kind: "async"
  })
});

// src/instrumentation/plugins/openrouter-channels.ts
var openRouterChannels = defineChannels("@openrouter/sdk", {
  chatSend: channel({
    channelName: "chat.send",
    kind: "async"
  }),
  embeddingsGenerate: channel({
    channelName: "embeddings.generate",
    kind: "async"
  }),
  rerankRerank: channel(
    {
      channelName: "rerank.rerank",
      kind: "async"
    }
  ),
  betaResponsesSend: channel({
    channelName: "beta.responses.send",
    kind: "async"
  }),
  callModel: channel({
    channelName: "callModel",
    kind: "sync-stream"
  }),
  callModelTurn: channel({
    channelName: "callModel.turn",
    kind: "async"
  }),
  toolExecute: channel({
    channelName: "tool.execute",
    kind: "async"
  })
});

// src/instrumentation/plugins/mistral-channels.ts
var mistralChannels = defineChannels("@mistralai/mistralai", {
  chatComplete: channel({
    channelName: "chat.complete",
    kind: "async"
  }),
  chatStream: channel({
    channelName: "chat.stream",
    kind: "async"
  }),
  embeddingsCreate: channel({
    channelName: "embeddings.create",
    kind: "async"
  }),
  classifiersModerate: channel({
    channelName: "classifiers.moderate",
    kind: "async"
  }),
  classifiersModerateChat: channel({
    channelName: "classifiers.moderateChat",
    kind: "async"
  }),
  classifiersClassify: channel({
    channelName: "classifiers.classify",
    kind: "async"
  }),
  classifiersClassifyChat: channel({
    channelName: "classifiers.classifyChat",
    kind: "async"
  }),
  fimComplete: channel({
    channelName: "fim.complete",
    kind: "async"
  }),
  fimStream: channel({
    channelName: "fim.stream",
    kind: "async"
  }),
  agentsComplete: channel({
    channelName: "agents.complete",
    kind: "async"
  }),
  agentsStream: channel({
    channelName: "agents.stream",
    kind: "async"
  })
});

// src/instrumentation/plugins/google-adk-channels.ts
var googleADKChannels = defineChannels("@google/adk", {
  runnerRunAsync: channel({
    channelName: "runner.runAsync",
    kind: "sync-stream"
  }),
  agentRunAsync: channel({
    channelName: "agent.runAsync",
    kind: "sync-stream"
  }),
  toolRunAsync: channel({
    channelName: "tool.runAsync",
    kind: "async"
  })
});

// src/instrumentation/plugins/cohere-channels.ts
var cohereChannels = defineChannels("cohere-ai", {
  chat: channel({
    channelName: "chat",
    kind: "async"
  }),
  chatStream: channel({
    channelName: "chatStream",
    kind: "async"
  }),
  embed: channel({
    channelName: "embed",
    kind: "async"
  }),
  rerank: channel({
    channelName: "rerank",
    kind: "async"
  })
});

// src/instrumentation/plugins/groq-channels.ts
var groqChannels = defineChannels("groq-sdk", {
  chatCompletionsCreate: channel({
    channelName: "chat.completions.create",
    kind: "async"
  }),
  embeddingsCreate: channel(
    {
      channelName: "embeddings.create",
      kind: "async"
    }
  )
});

// src/instrumentation/plugins/bedrock-runtime-channels.ts
var clientSendChannel = channel({
  channelName: "client.send",
  kind: "async"
});
var bedrockRuntimeChannels = defineChannels("aws-bedrock-runtime", {
  clientSend: clientSendChannel
});
var smithyCoreChannels = defineChannels("@smithy/core", {
  clientSend: clientSendChannel
});
var smithyClientChannels = defineChannels("@smithy/smithy-client", {
  clientSend: clientSendChannel
});

// src/instrumentation/plugins/genkit-channels.ts
var genkitChannels = defineChannels("@genkit-ai/ai", {
  generate: channel({
    channelName: "generate",
    kind: "async"
  }),
  generateStream: channel({
    channelName: "generateStream",
    kind: "sync-stream"
  }),
  embed: channel({
    channelName: "embed",
    kind: "async"
  }),
  embedMany: channel({
    channelName: "embedMany",
    kind: "async"
  }),
  actionRun: channel({
    channelName: "action.run",
    kind: "async"
  }),
  actionStream: channel({
    channelName: "action.stream",
    kind: "sync-stream"
  })
});
var genkitCoreChannels = defineChannels("@genkit-ai/core", {
  actionSpan: channel({
    channelName: "action.span",
    kind: "async"
  })
});

// src/instrumentation/plugins/github-copilot-channels.ts
var gitHubCopilotChannels = defineChannels("@github/copilot-sdk", {
  createSession: channel({
    channelName: "client.createSession",
    kind: "async"
  }),
  resumeSession: channel({
    channelName: "client.resumeSession",
    kind: "async"
  }),
  sendAndWait: channel({
    channelName: "session.sendAndWait",
    kind: "async"
  })
});

// src/instrumentation/plugins/flue-channels.ts
var flueChannels = defineChannels("@flue/runtime", {
  createContext: channel({
    channelName: "createFlueContext",
    kind: "sync-stream"
  })
});

// src/instrumentation/plugins/pi-coding-agent-channels.ts
var piCodingAgentChannels = defineChannels(
  "@earendil-works/pi-coding-agent",
  {
    prompt: channel({
      channelName: "AgentSession.prompt",
      kind: "async"
    })
  }
);

// src/instrumentation/plugins/strands-agent-sdk-channels.ts
var strandsAgentSDKChannels = defineChannels("@strands-agents/sdk", {
  agentStream: channel({
    channelName: "Agent.stream",
    kind: "sync-stream"
  }),
  graphStream: channel({
    channelName: "Graph.stream",
    kind: "sync-stream"
  }),
  swarmStream: channel({
    channelName: "Swarm.stream",
    kind: "sync-stream"
  })
});

// src/instrumentation/config.ts
var envIntegrationAliases = {
  openai: "openai",
  "openai-codex": "openaiCodexSDK",
  "openai-codex-sdk": "openaiCodexSDK",
  openaicodexsdk: "openaiCodexSDK",
  codex: "openaiCodexSDK",
  "codex-sdk": "openaiCodexSDK",
  "pi-coding-agent": "piCodingAgent",
  "pi-coding-agent-sdk": "piCodingAgent",
  picodingagent: "piCodingAgent",
  picodingagentsdk: "piCodingAgent",
  "@earendil-works/pi-coding-agent": "piCodingAgent",
  strandsAgentSDK: "strandsAgentSDK",
  strandsagentsdk: "strandsAgentSDK",
  "strands-agent-sdk": "strandsAgentSDK",
  "@strands-agents/sdk": "strandsAgentSDK",
  anthropic: "anthropic",
  aisdk: "aisdk",
  "ai-sdk": "aisdk",
  "vercel-ai": "aisdk",
  vercel: "vercel",
  claudeagentsdk: "claudeAgentSDK",
  "claude-agent-sdk": "claudeAgentSDK",
  cursor: "cursor",
  "cursor-sdk": "cursorSDK",
  cursorsdk: "cursorSDK",
  flue: "flue",
  "flue-runtime": "flue",
  mastra: "mastra",
  "openai-agents": "openAIAgents",
  openaiagents: "openAIAgents",
  "openai-agents-core": "openAIAgents",
  openaiagentscore: "openAIAgents",
  google: "google",
  "google-genai": "googleGenAI",
  googlegenai: "googleGenAI",
  huggingface: "huggingface",
  openrouter: "openrouter",
  openrouteragent: "openrouterAgent",
  "openrouter-agent": "openrouterAgent",
  mistral: "mistral",
  googleadk: "googleADK",
  "google-adk": "googleADK",
  cohere: "cohere",
  groq: "groq",
  "groq-sdk": "groq",
  bedrock: "bedrock",
  "aws-bedrock": "awsBedrock",
  awsbedrock: "awsBedrock",
  "aws-bedrock-runtime": "awsBedrockRuntime",
  awsbedrockruntime: "awsBedrockRuntime",
  "@aws-sdk/client-bedrock-runtime": "awsBedrockRuntime",
  genkit: "genkit",
  "firebase-genkit": "genkit",
  githubcopilot: "gitHubCopilot",
  "github-copilot": "gitHubCopilot",
  "copilot-sdk": "gitHubCopilot",
  langchain: "langchain",
  "langchain-js": "langchain",
  "@langchain": "langchain",
  langgraph: "langgraph"
};
function getDefaultInstrumentationIntegrations() {
  return {
    openai: true,
    openaiCodexSDK: true,
    anthropic: true,
    vercel: true,
    aisdk: true,
    google: true,
    googleGenAI: true,
    googleADK: true,
    huggingface: true,
    claudeAgentSDK: true,
    cursor: true,
    cursorSDK: true,
    flue: true,
    mastra: true,
    openAIAgents: true,
    openrouter: true,
    openrouterAgent: true,
    mistral: true,
    cohere: true,
    groq: true,
    bedrock: true,
    awsBedrock: true,
    awsBedrockRuntime: true,
    genkit: true,
    gitHubCopilot: true,
    langchain: true,
    langgraph: true,
    piCodingAgent: true,
    strandsAgentSDK: true
  };
}
function readDisabledInstrumentationEnvConfig(disabledList) {
  const integrations = {};
  if (disabledList) {
    for (const value of disabledList.split(",")) {
      const rawSdk = value.trim();
      const sdk = rawSdk.toLowerCase();
      if (sdk.length > 0) {
        integrations[_nullishCoalesce(_nullishCoalesce(envIntegrationAliases[rawSdk], () => ( envIntegrationAliases[sdk])), () => ( sdk))] = false;
      }
    }
  }
  return { integrations };
}
function isInstrumentationIntegrationDisabled(integrations, ...names) {
  return names.some((name) => _optionalChain([integrations, 'optionalAccess', _34 => _34[name]]) === false);
}

// src/auto-instrumentations/loader/mastra-observability-patch.ts
var MASTRA_EXPORTER_FACTORY_GLOBAL = "__braintrustMastraExporterFactory";
function installMastraExporterFactory(factory) {
  const globals = globalThis;
  globals[MASTRA_EXPORTER_FACTORY_GLOBAL] ??= factory;
}
var MASTRA_CORE_PACKAGE = "@mastra/core";
var MASTRA_OBSERVABILITY_PACKAGE = "@mastra/observability";
var MASTRA_CORE_ENTRY_PATHS = /* @__PURE__ */ new Set([
  "dist/index.js",
  "dist/index.cjs",
  "dist/mastra/index.js",
  "dist/mastra/index.cjs"
]);
var MASTRA_OBSERVABILITY_ENTRY_PATHS = /* @__PURE__ */ new Set([
  "dist/index.js",
  "dist/index.cjs"
]);
function classifyMastraTarget(packageName, modulePath) {
  if (packageName === MASTRA_CORE_PACKAGE && MASTRA_CORE_ENTRY_PATHS.has(modulePath)) {
    return "core";
  }
  if (packageName === MASTRA_OBSERVABILITY_PACKAGE && MASTRA_OBSERVABILITY_ENTRY_PATHS.has(modulePath)) {
    return "observability";
  }
  return null;
}
function extractChunkPath(source) {
  const esmMatch = source.match(
    /export\s*\{\s*Mastra(?:\s+as\s+\w+)?\s*\}\s*from\s*['"]([^'"]+)['"]/
  );
  if (esmMatch) return esmMatch[1];
  const cjsMatch = source.match(
    /require\s*\(\s*['"]([^'"]+chunk-[^'"]+)['"]\s*\)/
  );
  if (cjsMatch) return cjsMatch[1];
  return null;
}
var EXPORTER_FACTORY_KEY = JSON.stringify(MASTRA_EXPORTER_FACTORY_GLOBAL);
var MASTRA_PROXY_HANDLER_BODY = `
{
  construct(target, args, newTarget) {
    var firstArg = args[0];
    if (
      (!firstArg || typeof firstArg !== "object" || !firstArg.observability) &&
      __braintrustObservabilityClass
    ) {
      try {
        // serviceName is required by Mastra's Observability validator; pass
        // something sensible by default. Users who want a different name
        // should construct Observability themselves.
        var observability = new __braintrustObservabilityClass({
          configs: { default: { serviceName: "mastra" } },
        });
        args = args.slice();
        args[0] = Object.assign({}, firstArg, { observability: observability });
      } catch (e) {
        // Fall through. Mastra will use its own NoOp; user code still works,
        // just without auto-instrumentation.
      }
    }
    return Reflect.construct(target, args, newTarget);
  },
}`;
function buildMastraEsmWrapper(chunkPath) {
  const chunk = JSON.stringify(chunkPath);
  return `import { Mastra as __braintrustOrigMastra } from ${chunk};
import { createRequire as __braintrustCreateRequire } from "node:module";

let __braintrustObservabilityClass = null;
try {
  // Resolve @mastra/observability relative to this module (the Mastra entry),
  // so it's looked up from the user's node_modules tree.
  const __braintrustRequire = __braintrustCreateRequire(import.meta.url);
  __braintrustObservabilityClass =
    __braintrustRequire("@mastra/observability").Observability;
} catch (e) {
  // @mastra/observability isn't installed; the construct trap will skip the
  // auto-construct branch and Mastra falls back to its own NoOp.
}
const Mastra = new Proxy(__braintrustOrigMastra, ${MASTRA_PROXY_HANDLER_BODY});
export { Mastra };
`;
}
function buildMastraCjsWrapper(chunkPath) {
  const chunk = JSON.stringify(chunkPath);
  return `'use strict';
const __braintrustChunk = require(${chunk});

let __braintrustObservabilityClass = null;
try {
  __braintrustObservabilityClass = require("@mastra/observability").Observability;
} catch (e) {
  // @mastra/observability isn't installed; same fallback as the ESM wrapper.
}

const __braintrustWrappedMastra = new Proxy(
  __braintrustChunk.Mastra,
  ${MASTRA_PROXY_HANDLER_BODY},
);
Object.defineProperty(exports, "Mastra", {
  enumerable: true,
  configurable: true,
  get: function () { return __braintrustWrappedMastra; }
});
`;
}
var OBSERVABILITY_APPEND_BODY = `
;(function __braintrustWrapObservability() {
  // Top-level so we can both read and reassign the var binding the original
  // entry declared.
  if (typeof Observability === "undefined") return;
  if (Observability.__braintrustWrapped) return;
  function __braintrustEnsureExporter(rawConfig) {
    try {
      var factory = globalThis[${EXPORTER_FACTORY_KEY}];
      if (typeof factory !== "function") return rawConfig;
      var config = rawConfig && typeof rawConfig === "object" ? rawConfig : {};
      var configsIn = config.configs && typeof config.configs === "object" ? config.configs : null;
      var configsOut = {};
      var hadEntries = false;
      if (configsIn) {
        for (var name in configsIn) {
          if (!Object.prototype.hasOwnProperty.call(configsIn, name)) continue;
          hadEntries = true;
          var inst = configsIn[name] || {};
          var existing = Array.isArray(inst.exporters) ? inst.exporters : [];
          var hasOurs = existing.some(function (e) { return e && e.name === "braintrust"; });
          configsOut[name] = Object.assign({}, inst, {
            exporters: hasOurs ? existing : existing.concat([factory()]),
          });
        }
      }
      if (!hadEntries) {
        configsOut.default = {
          serviceName: "mastra",
          exporters: [factory()],
        };
      }
      return Object.assign({}, config, { configs: configsOut });
    } catch (e) {
      return rawConfig;
    }
  }
  var __OriginalObservability = Observability;
  Observability = new Proxy(__OriginalObservability, {
    construct: function (target, args, newTarget) {
      var nextArgs = args.slice();
      nextArgs[0] = __braintrustEnsureExporter(nextArgs[0]);
      return Reflect.construct(target, nextArgs, newTarget);
    },
  });
  Observability.__braintrustWrapped = true;
  if (typeof exports !== "undefined" && exports && typeof exports === "object") {
    try {
      Object.defineProperty(exports, "Observability", {
        enumerable: true,
        configurable: true,
        get: function () { return Observability; },
      });
    } catch (e) {}
  }
})();
`;
function patchMastraSource(source, target, format) {
  if (target === "core") {
    const chunkPath = extractChunkPath(source);
    if (!chunkPath) return source;
    return format === "esm" ? buildMastraEsmWrapper(chunkPath) : buildMastraCjsWrapper(chunkPath);
  }
  return source + OBSERVABILITY_APPEND_BODY;
}

// src/instrumentation/plugins/openai-agents-channels.ts
var openAIAgentsCoreChannels = defineChannels("@openai/agents-core", {
  onTraceStart: channel({
    channelName: "tracing.processor.onTraceStart",
    kind: "async"
  }),
  onTraceEnd: channel({
    channelName: "tracing.processor.onTraceEnd",
    kind: "async"
  }),
  onSpanStart: channel({
    channelName: "tracing.processor.onSpanStart",
    kind: "async"
  }),
  onSpanEnd: channel({
    channelName: "tracing.processor.onSpanEnd",
    kind: "async"
  })
});

// src/instrumentation/plugins/langchain-channels.ts
var langChainChannels = defineChannels("@langchain/core", {
  configure: channel({
    channelName: "CallbackManager.configure",
    kind: "sync-stream"
  }),
  configureSync: channel({
    channelName: "CallbackManager._configureSync",
    kind: "sync-stream"
  })
});




































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.bedrockRuntimeChannels = bedrockRuntimeChannels; exports.smithyCoreChannels = smithyCoreChannels; exports.smithyClientChannels = smithyClientChannels; exports.genkitChannels = genkitChannels; exports.genkitCoreChannels = genkitCoreChannels; exports.gitHubCopilotChannels = gitHubCopilotChannels; exports.flueChannels = flueChannels; exports.langChainChannels = langChainChannels; exports.piCodingAgentChannels = piCodingAgentChannels; exports.strandsAgentSDKChannels = strandsAgentSDKChannels; exports.getDefaultInstrumentationIntegrations = getDefaultInstrumentationIntegrations; exports.readDisabledInstrumentationEnvConfig = readDisabledInstrumentationEnvConfig; exports.isInstrumentationIntegrationDisabled = isInstrumentationIntegrationDisabled; exports.installMastraExporterFactory = installMastraExporterFactory; exports.classifyMastraTarget = classifyMastraTarget; exports.patchMastraSource = patchMastraSource;
