braintrust 3.31.0 → 3.33.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 (62) hide show
  1. package/README.md +0 -43
  2. package/dev/dist/index.d.mts +767 -0
  3. package/dev/dist/index.d.ts +767 -0
  4. package/dev/dist/index.js +3115 -908
  5. package/dev/dist/index.mjs +2466 -259
  6. package/dist/apply-auto-instrumentation.js +325 -221
  7. package/dist/apply-auto-instrumentation.mjs +110 -6
  8. package/dist/auto-instrumentations/bundler/esbuild.cjs +182 -7
  9. package/dist/auto-instrumentations/bundler/esbuild.mjs +2 -2
  10. package/dist/auto-instrumentations/bundler/next.cjs +182 -7
  11. package/dist/auto-instrumentations/bundler/next.mjs +3 -3
  12. package/dist/auto-instrumentations/bundler/rollup.cjs +182 -7
  13. package/dist/auto-instrumentations/bundler/rollup.mjs +2 -2
  14. package/dist/auto-instrumentations/bundler/vite.cjs +182 -7
  15. package/dist/auto-instrumentations/bundler/vite.mjs +2 -2
  16. package/dist/auto-instrumentations/bundler/webpack-loader.cjs +182 -7
  17. package/dist/auto-instrumentations/bundler/webpack.cjs +182 -7
  18. package/dist/auto-instrumentations/bundler/webpack.mjs +3 -3
  19. package/dist/auto-instrumentations/{chunk-U64OYU4Q.mjs → chunk-T2DMPWFI.mjs} +113 -6
  20. package/dist/auto-instrumentations/{chunk-LW4HDHXT.mjs → chunk-UHJ2DNYJ.mjs} +74 -2
  21. package/dist/auto-instrumentations/{chunk-OXINGIEZ.mjs → chunk-W5QNG3PV.mjs} +1 -1
  22. package/dist/auto-instrumentations/hook.mjs +209 -9
  23. package/dist/auto-instrumentations/index.cjs +115 -6
  24. package/dist/auto-instrumentations/index.d.mts +5 -1
  25. package/dist/auto-instrumentations/index.d.ts +5 -1
  26. package/dist/auto-instrumentations/index.mjs +5 -1
  27. package/dist/browser.d.mts +2324 -342
  28. package/dist/browser.d.ts +2324 -342
  29. package/dist/browser.js +3573 -626
  30. package/dist/browser.mjs +3573 -626
  31. package/dist/chunk-7P6ASYW6.mjs +9 -0
  32. package/dist/{chunk-V32LW47Z.js → chunk-AXJTOUOC.js} +3022 -1131
  33. package/dist/{chunk-4AQGZS6X.js → chunk-G3VHOHRC.js} +85 -11
  34. package/dist/chunk-MLKGABMK.js +9 -0
  35. package/dist/{chunk-AJT4FR25.mjs → chunk-MZLBAFVJ.mjs} +2051 -160
  36. package/dist/{chunk-CE3BLB2L.mjs → chunk-TZVZN2JJ.mjs} +84 -10
  37. package/dist/cli.js +2614 -297
  38. package/dist/custom-views.d.mts +112 -0
  39. package/dist/custom-views.d.ts +112 -0
  40. package/dist/custom-views.js +13 -0
  41. package/dist/custom-views.mjs +13 -0
  42. package/dist/edge-light.d.mts +1 -1
  43. package/dist/edge-light.d.ts +1 -1
  44. package/dist/edge-light.js +3573 -626
  45. package/dist/edge-light.mjs +3573 -626
  46. package/dist/index.d.mts +2324 -342
  47. package/dist/index.d.ts +2324 -342
  48. package/dist/index.js +1959 -969
  49. package/dist/index.mjs +1450 -460
  50. package/dist/instrumentation/index.d.mts +439 -245
  51. package/dist/instrumentation/index.d.ts +439 -245
  52. package/dist/instrumentation/index.js +2550 -258
  53. package/dist/instrumentation/index.mjs +2550 -258
  54. package/dist/vitest-evals-reporter.js +17 -16
  55. package/dist/vitest-evals-reporter.mjs +3 -2
  56. package/dist/workerd.d.mts +1 -1
  57. package/dist/workerd.d.ts +1 -1
  58. package/dist/workerd.js +3573 -626
  59. package/dist/workerd.mjs +3573 -626
  60. package/package.json +10 -2
  61. package/util/dist/index.d.mts +326 -0
  62. package/util/dist/index.d.ts +326 -0
@@ -2960,6 +2960,14 @@ var ChatCompletionContentPartImageWithTitle = import_v36.z.object({
2960
2960
  ttl: import_v36.z.enum(["5m", "1h"]).optional()
2961
2961
  }).optional()
2962
2962
  });
2963
+ var ChatCompletionContentPartInputAudioWithTitle = import_v36.z.object({
2964
+ input_audio: import_v36.z.object({ data: import_v36.z.string(), format: import_v36.z.enum(["wav", "mp3"]) }),
2965
+ type: import_v36.z.literal("input_audio"),
2966
+ cache_control: import_v36.z.object({
2967
+ type: import_v36.z.literal("ephemeral"),
2968
+ ttl: import_v36.z.enum(["5m", "1h"]).optional()
2969
+ }).optional()
2970
+ });
2963
2971
  var ChatCompletionContentPartFileFile = import_v36.z.object({ file_data: import_v36.z.string(), filename: import_v36.z.string(), file_id: import_v36.z.string() }).partial();
2964
2972
  var ChatCompletionContentPartFileWithTitle = import_v36.z.object({
2965
2973
  file: ChatCompletionContentPartFileFile,
@@ -2972,6 +2980,7 @@ var ChatCompletionContentPartFileWithTitle = import_v36.z.object({
2972
2980
  var ChatCompletionContentPart = import_v36.z.union([
2973
2981
  ChatCompletionContentPartTextWithTitle,
2974
2982
  ChatCompletionContentPartImageWithTitle,
2983
+ ChatCompletionContentPartInputAudioWithTitle,
2975
2984
  ChatCompletionContentPartFileWithTitle
2976
2985
  ]);
2977
2986
  var ChatCompletionContentPartText = import_v36.z.object({
@@ -5797,6 +5806,7 @@ var INSTRUMENTATION_NAMES = {
5797
5806
  GENKIT: "genkit",
5798
5807
  GITHUB_COPILOT: "github-copilot",
5799
5808
  GOOGLE_ADK: "google-adk",
5809
+ GOOGLE_GENERATIVE_AI: "google-generative-ai",
5800
5810
  GOOGLE_GENAI: "google-genai",
5801
5811
  GROQ: "groq",
5802
5812
  HUGGINGFACE: "huggingface",
@@ -5804,6 +5814,7 @@ var INSTRUMENTATION_NAMES = {
5804
5814
  LANGSMITH: "langsmith",
5805
5815
  MASTRA: "mastra",
5806
5816
  MISTRAL: "mistral",
5817
+ LANGGRAPH_SDK: "langgraph-sdk",
5807
5818
  OLLAMA: "ollama",
5808
5819
  OPENAI: "openai",
5809
5820
  OPENAI_AGENTS: "openai-agents",
@@ -5812,12 +5823,13 @@ var INSTRUMENTATION_NAMES = {
5812
5823
  OPENROUTER_AGENT: "openrouter-agent",
5813
5824
  PI_CODING_AGENT: "pi-coding-agent",
5814
5825
  STRANDS_AGENT_SDK: "strands-agent-sdk",
5815
- VOYAGEAI: "voyageai"
5826
+ VOYAGEAI: "voyageai",
5827
+ ELEVENLABS: "elevenlabs"
5816
5828
  };
5817
5829
  var INTERNAL_SPAN_INSTRUMENTATION_NAME = /* @__PURE__ */ Symbol.for(
5818
5830
  "braintrust.spanInstrumentationName"
5819
5831
  );
5820
- var SDK_VERSION = true ? "3.31.0" : "0.0.0";
5832
+ var SDK_VERSION = true ? "3.33.0" : "0.0.0";
5821
5833
  function withSpanInstrumentationName(args, instrumentationName) {
5822
5834
  return {
5823
5835
  ...args,
@@ -8536,6 +8548,38 @@ function getSpanParentObjectAndPropagatedState(options) {
8536
8548
  function getSpanParentObject(options) {
8537
8549
  return getSpanParentObjectAndPropagatedState(options).parentObject;
8538
8550
  }
8551
+ function _internalExportParentSynchronously(parent) {
8552
+ if ("toStr" in parent) {
8553
+ return parent.toStr();
8554
+ }
8555
+ if ("getParentInfo" in parent) {
8556
+ const parentInfo = parent.getParentInfo();
8557
+ if (!parentInfo) {
8558
+ return void 0;
8559
+ }
8560
+ const objectId = parentInfo.objectId.getSync().value;
8561
+ if (!objectId && !parentInfo.computeObjectMetadataArgs) {
8562
+ return void 0;
8563
+ }
8564
+ return new SpanComponentsV4({
8565
+ object_type: parentInfo.objectType,
8566
+ ...objectId ? { object_id: objectId } : {
8567
+ compute_object_metadata_args: parentInfo.computeObjectMetadataArgs ?? {}
8568
+ },
8569
+ row_id: parent.id,
8570
+ root_span_id: parent.rootSpanId,
8571
+ span_id: parent.spanId
8572
+ }).toStr();
8573
+ }
8574
+ const components = braintrustParentToComponents(parent._getOtelParent());
8575
+ if (!components) {
8576
+ return void 0;
8577
+ }
8578
+ return new SpanComponentsV4({
8579
+ object_type: components.objectType,
8580
+ ...components.objectId ? { object_id: components.objectId } : { compute_object_metadata_args: components.computeArgs ?? {} }
8581
+ }).toStr();
8582
+ }
8539
8583
  function currentBraintrustParent(state) {
8540
8584
  const resolvedState = state ?? _globalState;
8541
8585
  const experiment = currentExperiment({ state: resolvedState });
@@ -9842,10 +9886,16 @@ var SpanImpl = class _SpanImpl {
9842
9886
  inject(carrier) {
9843
9887
  const resolvedCarrier = carrier ?? {};
9844
9888
  try {
9889
+ const braintrustParent = this._getOtelParent() ?? this._propagatedState?.braintrustParent;
9890
+ if (!braintrustParent) {
9891
+ debugLogger.forState(this._state).warn(
9892
+ "Injecting trace context without braintrust.parent because the span's destination is not available yet. The receiver will start a new local trace instead of continuing this one."
9893
+ );
9894
+ }
9845
9895
  _injectIntoCarrier(resolvedCarrier, {
9846
9896
  traceId: this._rootSpanId,
9847
9897
  spanId: this._spanId,
9848
- braintrustParent: this._getOtelParent() ?? this._propagatedState?.braintrustParent,
9898
+ braintrustParent,
9849
9899
  propagatedState: this._propagatedState
9850
9900
  });
9851
9901
  } catch (e) {
@@ -10395,6 +10445,16 @@ function renderMessageImpl(render, message, variables) {
10395
10445
  }
10396
10446
  }
10397
10447
  ];
10448
+ case "input_audio":
10449
+ return [
10450
+ {
10451
+ ...c,
10452
+ input_audio: {
10453
+ ...c.input_audio,
10454
+ data: render(c.input_audio.data)
10455
+ }
10456
+ }
10457
+ ];
10398
10458
  case "file":
10399
10459
  return [
10400
10460
  {
@@ -11918,6 +11978,18 @@ function defineChannels(pkg, channels, options) {
11918
11978
  var openAIChannels = defineChannels(
11919
11979
  "openai",
11920
11980
  {
11981
+ agentsTraceStart: channel({
11982
+ channelName: "agents.trace.start",
11983
+ kind: "async"
11984
+ }),
11985
+ agentsTraceCapture: channel({
11986
+ channelName: "agents.trace.capture",
11987
+ kind: "async"
11988
+ }),
11989
+ agentsTraceFail: channel({
11990
+ channelName: "agents.trace.fail",
11991
+ kind: "async"
11992
+ }),
11921
11993
  filesCreateTraced: channel({
11922
11994
  channelName: "files.create-traced",
11923
11995
  kind: "async"
@@ -12286,6 +12358,23 @@ function getCachedMetricFromHeaders(headers) {
12286
12358
  return parseCachedHeader(headers.get(LEGACY_CACHED_HEADER));
12287
12359
  }
12288
12360
 
12361
+ // src/instrumentation/plugins/openai-manual-instrumentation-utils.ts
12362
+ async function deterministicDigest(namespace, ...parts) {
12363
+ const encoded = new TextEncoder().encode(
12364
+ [namespace, ...parts].map((part) => `${part.length}:${part}`).join("\0")
12365
+ );
12366
+ return new Uint8Array(
12367
+ await globalThis.crypto.subtle.digest("SHA-256", encoded)
12368
+ );
12369
+ }
12370
+ function digestHex(bytes, length) {
12371
+ return Array.from(bytes.slice(0, length)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
12372
+ }
12373
+ function digestUuid(bytes) {
12374
+ const hex = digestHex(bytes, 16);
12375
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
12376
+ }
12377
+
12289
12378
  // src/instrumentation/plugins/openai-batch-instrumentation.ts
12290
12379
  var SUPPORTED_ENDPOINTS = /* @__PURE__ */ new Set(["/v1/chat/completions", "/v1/responses"]);
12291
12380
  var TERMINAL_STATUSES = /* @__PURE__ */ new Set([
@@ -12326,21 +12415,6 @@ async function exportParent(parent) {
12326
12415
  }
12327
12416
  return void 0;
12328
12417
  }
12329
- async function deterministicDigest(namespace, ...parts) {
12330
- const encoded = new TextEncoder().encode(
12331
- [namespace, ...parts].map((part) => `${part.length}:${part}`).join("\0")
12332
- );
12333
- return new Uint8Array(
12334
- await globalThis.crypto.subtle.digest("SHA-256", encoded)
12335
- );
12336
- }
12337
- function digestHex(bytes, length) {
12338
- return Array.from(bytes.slice(0, length)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
12339
- }
12340
- function digestUuid(bytes) {
12341
- const hex = digestHex(bytes, 16);
12342
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
12343
- }
12344
12418
  async function batchSpanIds(inputFileId) {
12345
12419
  const [row, span, root] = await Promise.all([
12346
12420
  deterministicDigest("openai:batch:row", inputFileId),
@@ -12831,6 +12905,628 @@ var interceptOpenAIBatchTraceComplete = (target, thisArg, args) => Promise.resol
12831
12905
  return result;
12832
12906
  });
12833
12907
 
12908
+ // src/instrumentation/plugins/openai-agents-api-instrumentation.ts
12909
+ var TERMINAL_TURN_EVENTS = /* @__PURE__ */ new Set([
12910
+ "agent.session.turn.completed",
12911
+ "agent.session.turn.failed",
12912
+ "agent.session.turn.cancelled"
12913
+ ]);
12914
+ var TURN_LIFECYCLE_EVENTS = /* @__PURE__ */ new Set([
12915
+ "agent.session.turn.created",
12916
+ "agent.session.turn.in_progress",
12917
+ ...TERMINAL_TURN_EVENTS
12918
+ ]);
12919
+ var SESSION_EVENTS = /* @__PURE__ */ new Set([
12920
+ "agent.session.created",
12921
+ "agent.session.failed",
12922
+ "agent.session.idle",
12923
+ "agent.session.in_progress",
12924
+ "agent.session.requires_action"
12925
+ ]);
12926
+ var SUBAGENT_EVENTS = /* @__PURE__ */ new Set([
12927
+ "agent.session.subagent.active",
12928
+ "agent.session.subagent.closed",
12929
+ "agent.session.subagent.created"
12930
+ ]);
12931
+ function read2(value, key) {
12932
+ if (!isObject(value)) {
12933
+ return void 0;
12934
+ }
12935
+ try {
12936
+ return Reflect.get(value, key);
12937
+ } catch {
12938
+ return void 0;
12939
+ }
12940
+ }
12941
+ function stringValue(value) {
12942
+ return typeof value === "string" && value.length > 0 ? value : void 0;
12943
+ }
12944
+ function recordValue(record, key) {
12945
+ return Object.hasOwn(record, key) ? record[key] : void 0;
12946
+ }
12947
+ function setRecordValue(record, key, value) {
12948
+ Object.defineProperty(record, key, {
12949
+ configurable: true,
12950
+ enumerable: true,
12951
+ value,
12952
+ writable: true
12953
+ });
12954
+ }
12955
+ function loggedError(value, fallback) {
12956
+ if (value instanceof Error) {
12957
+ return value;
12958
+ }
12959
+ const message = stringValue(read2(value, "message"));
12960
+ return new Error(message ?? (typeof value === "string" ? value : fallback));
12961
+ }
12962
+ function logInstrumentationError(context, error) {
12963
+ debugLogger.debug(`OpenAI Agents API instrumentation ${context}:`, error);
12964
+ }
12965
+ async function childSpanIds2(rootKey, kind, providerId) {
12966
+ const [row, span] = await Promise.all([
12967
+ deterministicDigest("openai:agents:row", rootKey, kind, providerId),
12968
+ deterministicDigest("openai:agents:span", rootKey, kind, providerId)
12969
+ ]);
12970
+ return { rowId: digestUuid(row), spanId: digestHex(span, 8) };
12971
+ }
12972
+ function traceMetadata(args) {
12973
+ const metadata = {};
12974
+ const suppliedMetadata = read2(args, "metadata");
12975
+ if (isObject(suppliedMetadata)) {
12976
+ try {
12977
+ for (const key of Object.keys(suppliedMetadata)) {
12978
+ metadata[key] = read2(suppliedMetadata, key);
12979
+ }
12980
+ } catch (error) {
12981
+ logInstrumentationError("could not read supplied metadata", error);
12982
+ }
12983
+ }
12984
+ const agent = read2(args, "agent");
12985
+ const agentId = stringValue(read2(agent, "id")) ?? stringValue(read2(args, "agent_id"));
12986
+ const agentName = stringValue(read2(agent, "name"));
12987
+ const model = stringValue(read2(agent, "model"));
12988
+ return {
12989
+ ...metadata,
12990
+ api: "agents",
12991
+ ...agentId ? { agent_id: agentId } : {},
12992
+ ...agentName ? { agent_name: agentName } : {},
12993
+ ...model ? { model } : {},
12994
+ provider: "openai"
12995
+ };
12996
+ }
12997
+ function copyState(state) {
12998
+ return {
12999
+ ...state,
13000
+ callItems: { ...state.callItems },
13001
+ eventIds: [...state.eventIds],
13002
+ openTools: { ...state.openTools },
13003
+ subagents: { ...state.subagents },
13004
+ turnSubagents: { ...state.turnSubagents }
13005
+ };
13006
+ }
13007
+ function startRootSpan(state) {
13008
+ const root = SpanComponentsV4.fromStr(state.root);
13009
+ const parent = SpanComponentsV4.fromStr(state.rootParent);
13010
+ const rowId = stringValue(root.data.row_id);
13011
+ const rootSpanId = stringValue(root.data.root_span_id);
13012
+ const spanId = stringValue(root.data.span_id);
13013
+ if (!rowId || !rootSpanId || !spanId) {
13014
+ throw new Error("OpenAI Agents trace root is invalid");
13015
+ }
13016
+ const hasParentSpan = Boolean(
13017
+ parent.data.row_id && parent.data.span_id && parent.data.root_span_id
13018
+ );
13019
+ return withCurrent(
13020
+ NOOP_SPAN,
13021
+ () => _internalStartSpanWithInitialMergeAndParentSpanIds(
13022
+ withSpanInstrumentationName(
13023
+ {
13024
+ name: "openai.agents.turn",
13025
+ type: "task" /* TASK */,
13026
+ parent: state.rootParent,
13027
+ ...!hasParentSpan ? {
13028
+ parentSpanIds: {
13029
+ parentSpanIds: [],
13030
+ rootSpanId
13031
+ }
13032
+ } : {},
13033
+ spanId,
13034
+ startTime: state.startTime,
13035
+ event: { id: rowId }
13036
+ },
13037
+ INSTRUMENTATION_NAMES.OPENAI
13038
+ )
13039
+ )
13040
+ );
13041
+ }
13042
+ async function startSubagentSpan(state, subagentId, input, metadata, visiting = /* @__PURE__ */ new Set()) {
13043
+ const subagent = recordValue(state.subagents, subagentId);
13044
+ let parent = state.root;
13045
+ if (subagent?.parentAgentId && subagent.parentAgentId !== subagentId && recordValue(state.subagents, subagent.parentAgentId) && !visiting.has(subagent.parentAgentId)) {
13046
+ visiting.add(subagentId);
13047
+ parent = await (await startSubagentSpan(
13048
+ state,
13049
+ subagent.parentAgentId,
13050
+ void 0,
13051
+ void 0,
13052
+ visiting
13053
+ )).export();
13054
+ }
13055
+ const ids = await childSpanIds2(state.rootKey, "subagent", subagentId);
13056
+ return withCurrent(
13057
+ NOOP_SPAN,
13058
+ () => _internalStartSpanWithInitialMerge(
13059
+ withSpanInstrumentationName(
13060
+ {
13061
+ name: "openai.agents.subagent",
13062
+ type: "task" /* TASK */,
13063
+ parent,
13064
+ spanId: ids.spanId,
13065
+ startTime: subagent?.openedAt,
13066
+ event: {
13067
+ id: ids.rowId,
13068
+ ...input !== void 0 ? { input } : {},
13069
+ metadata: {
13070
+ ...metadata,
13071
+ agent_id: subagentId,
13072
+ ...subagent?.parentAgentId ? { parent_agent_id: subagent.parentAgentId } : {},
13073
+ provider: "openai"
13074
+ }
13075
+ }
13076
+ },
13077
+ INSTRUMENTATION_NAMES.OPENAI
13078
+ )
13079
+ )
13080
+ );
13081
+ }
13082
+ async function parentForTurn(state, turnId) {
13083
+ const subagentId = turnId ? recordValue(state.turnSubagents, turnId) : void 0;
13084
+ if (!subagentId) {
13085
+ return state.root;
13086
+ }
13087
+ return await (await startSubagentSpan(state, subagentId)).export();
13088
+ }
13089
+ async function startToolSpan(state, tool, input) {
13090
+ const ids = await childSpanIds2(state.rootKey, "tool", tool.itemId);
13091
+ return withCurrent(
13092
+ NOOP_SPAN,
13093
+ async () => _internalStartSpanWithInitialMerge(
13094
+ withSpanInstrumentationName(
13095
+ {
13096
+ name: tool.name,
13097
+ type: "tool" /* TOOL */,
13098
+ parent: await parentForTurn(state, tool.turnId),
13099
+ spanId: ids.spanId,
13100
+ startTime: tool.startTime,
13101
+ event: {
13102
+ id: ids.rowId,
13103
+ ...input !== void 0 ? { input } : {},
13104
+ metadata: {
13105
+ item_id: tool.itemId,
13106
+ provider: "openai",
13107
+ tool_type: tool.toolType,
13108
+ ...tool.turnId ? { turn_id: tool.turnId } : {}
13109
+ }
13110
+ }
13111
+ },
13112
+ INSTRUMENTATION_NAMES.OPENAI
13113
+ )
13114
+ )
13115
+ );
13116
+ }
13117
+ function toolFromItem(item, observedAt) {
13118
+ const itemId = stringValue(read2(item, "id"));
13119
+ const toolType = stringValue(read2(item, "type"));
13120
+ if (!itemId || !toolType) {
13121
+ return void 0;
13122
+ }
13123
+ const turnId = stringValue(read2(item, "turn_id"));
13124
+ switch (toolType) {
13125
+ case "function_call":
13126
+ return {
13127
+ input: read2(item, "arguments"),
13128
+ tool: {
13129
+ itemId,
13130
+ name: stringValue(read2(item, "name")) ?? "Function call",
13131
+ startTime: observedAt,
13132
+ toolType,
13133
+ ...turnId ? { turnId } : {}
13134
+ }
13135
+ };
13136
+ case "mcp_call": {
13137
+ const name = stringValue(read2(item, "name")) ?? "MCP call";
13138
+ const server = stringValue(read2(item, "server_label"));
13139
+ return {
13140
+ input: read2(item, "arguments"),
13141
+ tool: {
13142
+ itemId,
13143
+ name: server ? `${server}.${name}` : name,
13144
+ startTime: observedAt,
13145
+ toolType,
13146
+ ...turnId ? { turnId } : {}
13147
+ }
13148
+ };
13149
+ }
13150
+ case "web_search_call":
13151
+ return {
13152
+ input: read2(item, "action"),
13153
+ tool: {
13154
+ itemId,
13155
+ name: "Web search",
13156
+ startTime: observedAt,
13157
+ toolType,
13158
+ ...turnId ? { turnId } : {}
13159
+ }
13160
+ };
13161
+ case "command_execution":
13162
+ return {
13163
+ input: {
13164
+ command: read2(item, "command"),
13165
+ cwd: read2(item, "cwd")
13166
+ },
13167
+ tool: {
13168
+ itemId,
13169
+ name: "Command execution",
13170
+ startTime: observedAt,
13171
+ toolType,
13172
+ ...turnId ? { turnId } : {}
13173
+ }
13174
+ };
13175
+ default:
13176
+ return void 0;
13177
+ }
13178
+ }
13179
+ function textFromContent(content) {
13180
+ if (!Array.isArray(content)) {
13181
+ return void 0;
13182
+ }
13183
+ const text = [];
13184
+ for (const part of content) {
13185
+ const partText = read2(part, "text");
13186
+ if (read2(part, "type") === "output_text" && typeof partText === "string") {
13187
+ text.push(partText);
13188
+ }
13189
+ }
13190
+ return text.length > 0 ? text.join("") : void 0;
13191
+ }
13192
+ function toolOutput(item, toolType) {
13193
+ switch (toolType) {
13194
+ case "function_call":
13195
+ return read2(item, "output");
13196
+ case "mcp_call":
13197
+ return read2(item, "output");
13198
+ case "web_search_call":
13199
+ return read2(item, "action");
13200
+ case "command_execution":
13201
+ return read2(item, "output");
13202
+ default:
13203
+ return void 0;
13204
+ }
13205
+ }
13206
+ function toolFailed(item, toolType) {
13207
+ const status = read2(item, "status");
13208
+ const explicitError = read2(item, "error");
13209
+ if (explicitError !== void 0 && explicitError !== null) {
13210
+ return loggedError(explicitError, `OpenAI ${toolType} failed`);
13211
+ }
13212
+ if (status === "failed" || status === "incomplete") {
13213
+ return new Error(`OpenAI ${toolType} ${status}`);
13214
+ }
13215
+ if (toolType === "command_execution" && typeof read2(item, "exit_code") === "number" && read2(item, "exit_code") !== 0) {
13216
+ return new Error(
13217
+ `OpenAI command exited with code ${read2(item, "exit_code")}`
13218
+ );
13219
+ }
13220
+ return void 0;
13221
+ }
13222
+ async function completeTool(state, tool, item, endTime) {
13223
+ const span = await startToolSpan(state, tool);
13224
+ const output = toolOutput(item, tool.toolType);
13225
+ const error = toolFailed(item, tool.toolType);
13226
+ span.log({
13227
+ ...output !== void 0 ? { output } : {},
13228
+ ...error ? { error } : {},
13229
+ metadata: {
13230
+ status: read2(item, "status"),
13231
+ ...tool.toolType === "command_execution" ? { exit_code: read2(item, "exit_code") } : {}
13232
+ }
13233
+ });
13234
+ span.end({ endTime });
13235
+ Reflect.deleteProperty(state.openTools, tool.itemId);
13236
+ }
13237
+ async function captureMessage(state, item) {
13238
+ if (read2(item, "type") !== "message" || read2(item, "role") !== "assistant" || read2(item, "phase") !== "final_answer") {
13239
+ return;
13240
+ }
13241
+ const output = textFromContent(read2(item, "content"));
13242
+ if (output === void 0) {
13243
+ return;
13244
+ }
13245
+ const turnId = stringValue(read2(item, "turn_id"));
13246
+ const subagentId = turnId ? recordValue(state.turnSubagents, turnId) : void 0;
13247
+ if (subagentId) {
13248
+ (await startSubagentSpan(state, subagentId)).log({ output });
13249
+ } else {
13250
+ startRootSpan(state).log({ output });
13251
+ }
13252
+ }
13253
+ async function captureItem(state, item, isDone, observedAt) {
13254
+ await captureMessage(state, item);
13255
+ const itemType = stringValue(read2(item, "type"));
13256
+ if (itemType === "function_call_output") {
13257
+ const callId = stringValue(read2(item, "call_id"));
13258
+ const itemId = callId ? recordValue(state.callItems, callId) : void 0;
13259
+ const tool2 = itemId ? recordValue(state.openTools, itemId) : void 0;
13260
+ if (tool2) {
13261
+ await completeTool(state, tool2, item, observedAt);
13262
+ }
13263
+ return;
13264
+ }
13265
+ const descriptor = toolFromItem(item, observedAt);
13266
+ if (!descriptor) {
13267
+ return;
13268
+ }
13269
+ const existing = recordValue(state.openTools, descriptor.tool.itemId);
13270
+ const tool = existing ?? descriptor.tool;
13271
+ setRecordValue(state.openTools, tool.itemId, tool);
13272
+ if (itemType === "function_call") {
13273
+ const callId = stringValue(read2(item, "call_id"));
13274
+ if (callId) {
13275
+ setRecordValue(state.callItems, callId, tool.itemId);
13276
+ }
13277
+ }
13278
+ await startToolSpan(state, tool, descriptor.input);
13279
+ const status = read2(item, "status");
13280
+ const terminalFunctionCall = itemType === "function_call" && (status === "failed" || status === "incomplete");
13281
+ if (itemType !== "function_call" && (isDone || status !== "in_progress") || terminalFunctionCall) {
13282
+ await completeTool(state, tool, item, observedAt);
13283
+ }
13284
+ }
13285
+ function updateSessionMetadata(state, session) {
13286
+ const sessionId = stringValue(read2(session, "id"));
13287
+ const agent = read2(session, "agent");
13288
+ startRootSpan(state).log({
13289
+ metadata: {
13290
+ ...sessionId ? { session_id: sessionId } : {},
13291
+ ...stringValue(read2(agent, "id")) ? { agent_id: read2(agent, "id") } : {},
13292
+ ...stringValue(read2(agent, "name")) ? { agent_name: read2(agent, "name") } : {},
13293
+ ...stringValue(read2(agent, "model")) ? { model: read2(agent, "model") } : {}
13294
+ }
13295
+ });
13296
+ }
13297
+ async function captureSubagent(state, eventType, subagent, observedAt) {
13298
+ const subagentId = stringValue(read2(subagent, "id"));
13299
+ if (!subagentId) {
13300
+ return;
13301
+ }
13302
+ const existing = recordValue(state.subagents, subagentId);
13303
+ const observedOpenedAt = read2(subagent, "opened_at");
13304
+ const openedAt = typeof observedOpenedAt === "number" && Number.isFinite(observedOpenedAt) && observedOpenedAt >= 0 ? observedOpenedAt : existing?.openedAt ?? observedAt;
13305
+ const observedClosedAt = read2(subagent, "closed_at");
13306
+ const closedAt = typeof observedClosedAt === "number" && Number.isFinite(observedClosedAt) && observedClosedAt >= 0 ? observedClosedAt : existing?.closedAt;
13307
+ const parentAgentId = stringValue(read2(subagent, "parent_agent_id")) ?? existing?.parentAgentId;
13308
+ setRecordValue(state.subagents, subagentId, {
13309
+ ...closedAt !== void 0 ? { closedAt } : {},
13310
+ openedAt,
13311
+ ...parentAgentId ? { parentAgentId } : {}
13312
+ });
13313
+ const span = await startSubagentSpan(
13314
+ state,
13315
+ subagentId,
13316
+ read2(subagent, "instructions"),
13317
+ {
13318
+ ...stringValue(read2(subagent, "name")) ? { agent_name: read2(subagent, "name") } : {},
13319
+ status: read2(subagent, "status")
13320
+ }
13321
+ );
13322
+ if (eventType === "agent.session.subagent.closed") {
13323
+ span.end({ endTime: closedAt ?? observedAt });
13324
+ }
13325
+ }
13326
+ async function closeTrace(state, endTime, error, usage) {
13327
+ if (state.ended) {
13328
+ return;
13329
+ }
13330
+ for (const tool of Object.values(state.openTools)) {
13331
+ const span = await startToolSpan(state, tool);
13332
+ span.log({
13333
+ error: error ?? new Error("OpenAI Agents turn ended before tool completion")
13334
+ });
13335
+ span.end({ endTime });
13336
+ }
13337
+ state.openTools = {};
13338
+ for (const subagentId of Object.keys(state.subagents)) {
13339
+ const subagent = state.subagents[subagentId];
13340
+ const span = await startSubagentSpan(state, subagentId);
13341
+ span.end({ endTime: subagent.closedAt ?? endTime });
13342
+ }
13343
+ const root = startRootSpan(state);
13344
+ root.log({
13345
+ ...error ? { error } : {},
13346
+ metrics: parseMetricsFromUsage(usage)
13347
+ });
13348
+ root.end({ endTime });
13349
+ state.ended = true;
13350
+ }
13351
+ async function captureTurnLifecycle(state, event, eventType, observedAt) {
13352
+ const turn = read2(event, "turn");
13353
+ const turnId = stringValue(read2(event, "turn_id")) ?? stringValue(read2(turn, "id"));
13354
+ const subagentId = stringValue(read2(turn, "subagent_id"));
13355
+ if (turnId && subagentId) {
13356
+ setRecordValue(state.turnSubagents, turnId, subagentId);
13357
+ if (!recordValue(state.subagents, subagentId)) {
13358
+ const createdAt = read2(turn, "created_at");
13359
+ setRecordValue(state.subagents, subagentId, {
13360
+ openedAt: typeof createdAt === "number" && Number.isFinite(createdAt) && createdAt >= 0 ? createdAt : observedAt
13361
+ });
13362
+ }
13363
+ await startSubagentSpan(state, subagentId);
13364
+ }
13365
+ const sessionId = stringValue(read2(event, "session_id"));
13366
+ if (sessionId) {
13367
+ startRootSpan(state).log({ metadata: { session_id: sessionId } });
13368
+ }
13369
+ if (!TERMINAL_TURN_EVENTS.has(eventType) || subagentId) {
13370
+ if (subagentId && eventType === "agent.session.turn.failed") {
13371
+ (await startSubagentSpan(state, subagentId)).log({
13372
+ error: loggedError(read2(turn, "error"), "OpenAI subagent turn failed")
13373
+ });
13374
+ }
13375
+ return;
13376
+ }
13377
+ const completedAt = read2(turn, "completed_at");
13378
+ const endTime = typeof completedAt === "number" && Number.isFinite(completedAt) && completedAt >= 0 ? completedAt : observedAt;
13379
+ const usage = read2(event, "usage") ?? read2(turn, "usage");
13380
+ const error = eventType === "agent.session.turn.completed" ? void 0 : loggedError(
13381
+ read2(turn, "error"),
13382
+ eventType === "agent.session.turn.cancelled" ? "OpenAI Agents turn cancelled" : "OpenAI Agents turn failed"
13383
+ );
13384
+ await closeTrace(state, endTime, error, usage);
13385
+ }
13386
+ async function captureEvent(state, event) {
13387
+ if (state.ended) {
13388
+ return state;
13389
+ }
13390
+ const eventType = stringValue(read2(event, "type"));
13391
+ const eventId = stringValue(read2(event, "event_id"));
13392
+ if (!eventType || eventId && state.eventIds.includes(eventId)) {
13393
+ return state;
13394
+ }
13395
+ const next = copyState(state);
13396
+ const observedAt = getCurrentUnixTimestamp();
13397
+ let handled = false;
13398
+ if (SESSION_EVENTS.has(eventType)) {
13399
+ const session = read2(event, "session");
13400
+ if (session) {
13401
+ updateSessionMetadata(next, session);
13402
+ }
13403
+ handled = true;
13404
+ }
13405
+ if (eventType === "agent.session.turn.item.added") {
13406
+ await captureItem(next, read2(event, "item"), false, observedAt);
13407
+ handled = true;
13408
+ } else if (eventType === "agent.session.turn.item.done") {
13409
+ await captureItem(next, read2(event, "item"), true, observedAt);
13410
+ handled = true;
13411
+ } else if (TURN_LIFECYCLE_EVENTS.has(eventType)) {
13412
+ await captureTurnLifecycle(next, event, eventType, observedAt);
13413
+ handled = true;
13414
+ } else if (SUBAGENT_EVENTS.has(eventType)) {
13415
+ await captureSubagent(next, eventType, read2(event, "subagent"), observedAt);
13416
+ handled = true;
13417
+ } else if (eventType === "agent.session.turn.output_text.delta" && next.firstTokenAt === void 0 && stringValue(read2(event, "delta"))) {
13418
+ next.firstTokenAt = observedAt;
13419
+ startRootSpan(next).log({
13420
+ metrics: { time_to_first_token: observedAt - next.startTime }
13421
+ });
13422
+ handled = true;
13423
+ } else if (eventType === "agent.session.failed") {
13424
+ const session = read2(event, "session");
13425
+ const lastActiveAt = read2(session, "last_active_at");
13426
+ const endTime = typeof lastActiveAt === "number" && Number.isFinite(lastActiveAt) && lastActiveAt >= 0 ? lastActiveAt : observedAt;
13427
+ await closeTrace(
13428
+ next,
13429
+ endTime,
13430
+ loggedError(read2(session, "error"), "OpenAI Agents session failed"),
13431
+ read2(session, "usage")
13432
+ );
13433
+ handled = true;
13434
+ } else if (eventType === "error") {
13435
+ await closeTrace(
13436
+ next,
13437
+ observedAt,
13438
+ loggedError(read2(event, "error"), "OpenAI Agents session failed")
13439
+ );
13440
+ handled = true;
13441
+ }
13442
+ if (!handled) {
13443
+ return state;
13444
+ }
13445
+ if (eventId) {
13446
+ next.eventIds.push(eventId);
13447
+ }
13448
+ return next;
13449
+ }
13450
+ var interceptOpenAIAgentsTraceStart = async (target, thisArg, args) => {
13451
+ const fallback = await Reflect.apply(target, thisArg, args);
13452
+ try {
13453
+ const state = args[0].state;
13454
+ const parent = state.rootParent;
13455
+ const traceArgs = args[0].args;
13456
+ const parentComponents = SpanComponentsV4.fromStr(parent);
13457
+ const hasParentSpan = Boolean(
13458
+ parentComponents.data.row_id && parentComponents.data.span_id && parentComponents.data.root_span_id
13459
+ );
13460
+ const rootComponents = SpanComponentsV4.fromStr(state.root);
13461
+ const rowId = stringValue(rootComponents.data.row_id);
13462
+ const rootSpanId = stringValue(rootComponents.data.root_span_id);
13463
+ const spanId = stringValue(rootComponents.data.span_id);
13464
+ if (!rowId || !rootSpanId || !spanId) {
13465
+ throw new Error("OpenAI Agents trace root is invalid");
13466
+ }
13467
+ withCurrent(
13468
+ NOOP_SPAN,
13469
+ () => _internalStartSpanWithInitialMergeAndParentSpanIds(
13470
+ withSpanInstrumentationName(
13471
+ {
13472
+ name: "openai.agents.turn",
13473
+ type: "task" /* TASK */,
13474
+ parent,
13475
+ ...!hasParentSpan ? {
13476
+ parentSpanIds: {
13477
+ parentSpanIds: [],
13478
+ rootSpanId
13479
+ }
13480
+ } : {},
13481
+ spanId,
13482
+ startTime: state.startTime,
13483
+ event: {
13484
+ id: rowId,
13485
+ input: read2(traceArgs, "input"),
13486
+ metadata: traceMetadata(traceArgs)
13487
+ }
13488
+ },
13489
+ INSTRUMENTATION_NAMES.OPENAI
13490
+ )
13491
+ )
13492
+ );
13493
+ return state;
13494
+ } catch (error) {
13495
+ logInstrumentationError("could not start trace", error);
13496
+ return fallback;
13497
+ }
13498
+ };
13499
+ var interceptOpenAIAgentsTraceCapture = async (target, thisArg, args) => {
13500
+ const fallback = await Reflect.apply(target, thisArg, args);
13501
+ if (!args[0].state) {
13502
+ return fallback;
13503
+ }
13504
+ try {
13505
+ return await captureEvent(args[0].state, args[0].event);
13506
+ } catch (error) {
13507
+ logInstrumentationError("could not capture event", error);
13508
+ return fallback;
13509
+ }
13510
+ };
13511
+ var interceptOpenAIAgentsTraceFail = async (target, thisArg, args) => {
13512
+ const fallback = await Reflect.apply(target, thisArg, args);
13513
+ if (!args[0].state) {
13514
+ return fallback;
13515
+ }
13516
+ try {
13517
+ const next = copyState(args[0].state);
13518
+ await closeTrace(
13519
+ next,
13520
+ getCurrentUnixTimestamp(),
13521
+ loggedError(args[0].error, "OpenAI Agents request failed")
13522
+ );
13523
+ return next;
13524
+ } catch (error) {
13525
+ logInstrumentationError("could not fail trace", error);
13526
+ return fallback;
13527
+ }
13528
+ };
13529
+
12834
13530
  // src/instrumentation/plugins/openai-plugin.ts
12835
13531
  var OpenAIPlugin = class extends BasePlugin {
12836
13532
  constructor() {
@@ -12838,6 +13534,13 @@ var OpenAIPlugin = class extends BasePlugin {
12838
13534
  }
12839
13535
  onEnable() {
12840
13536
  this.unsubscribers.push(
13537
+ openAIChannels.agentsTraceStart.intercept(
13538
+ interceptOpenAIAgentsTraceStart
13539
+ ),
13540
+ openAIChannels.agentsTraceCapture.intercept(
13541
+ interceptOpenAIAgentsTraceCapture
13542
+ ),
13543
+ openAIChannels.agentsTraceFail.intercept(interceptOpenAIAgentsTraceFail),
12841
13544
  openAIChannels.filesCreateTraced.intercept(
12842
13545
  interceptOpenAIFilesCreateTraced
12843
13546
  ),
@@ -13398,7 +14101,7 @@ async function* patchCodexEventStream(events, state) {
13398
14101
  try {
13399
14102
  await handleCodexEvent(state, event);
13400
14103
  } catch (error) {
13401
- logInstrumentationError("OpenAI Codex stream event", error);
14104
+ logInstrumentationError2("OpenAI Codex stream event", error);
13402
14105
  }
13403
14106
  yield event;
13404
14107
  }
@@ -13898,10 +14601,10 @@ function safeLog(span, event) {
13898
14601
  try {
13899
14602
  span.log(event);
13900
14603
  } catch (error) {
13901
- logInstrumentationError("OpenAI Codex span log", error);
14604
+ logInstrumentationError2("OpenAI Codex span log", error);
13902
14605
  }
13903
14606
  }
13904
- function logInstrumentationError(context, error) {
14607
+ function logInstrumentationError2(context, error) {
13905
14608
  debugLogger.error(`Error processing ${context}:`, error);
13906
14609
  }
13907
14610
 
@@ -15283,27 +15986,8 @@ function continuationParentFromCreateSessionParams(params) {
15283
15986
  }
15284
15987
  return context.parent;
15285
15988
  }
15286
- function exportSpanSynchronously(span) {
15287
- const parentInfo = span.getParentInfo();
15288
- if (!parentInfo) {
15289
- return void 0;
15290
- }
15291
- const objectId = parentInfo.objectId.getSync().value;
15292
- if (!objectId && !parentInfo.computeObjectMetadataArgs) {
15293
- return void 0;
15294
- }
15295
- return new SpanComponentsV4({
15296
- object_type: parentInfo.objectType,
15297
- ...objectId ? { object_id: objectId } : {
15298
- compute_object_metadata_args: parentInfo.computeObjectMetadataArgs ?? {}
15299
- },
15300
- row_id: span.id,
15301
- root_span_id: span.rootSpanId,
15302
- span_id: span.spanId
15303
- }).toStr();
15304
- }
15305
15989
  function exportedParent(parent) {
15306
- return typeof parent === "string" ? parent : exportSpanSynchronously(parent);
15990
+ return typeof parent === "string" ? parent : _internalExportParentSynchronously(parent);
15307
15991
  }
15308
15992
  function addSerializedContext(args) {
15309
15993
  if (!isObject(args.continuation) || args.sessionId === void 0) {
@@ -16060,16 +16744,16 @@ function braintrustAISDKTelemetry() {
16060
16744
  if (!toolCallId || !state) {
16061
16745
  return;
16062
16746
  }
16063
- const toolOutput = event.toolOutput;
16747
+ const toolOutput2 = event.toolOutput;
16064
16748
  const workflowToolError = event.success === false && "error" in event ? event.error : void 0;
16065
- if (toolOutput?.type === "tool-error" || workflowToolError !== void 0) {
16066
- const error = toolOutput?.error ?? workflowToolError;
16749
+ if (toolOutput2?.type === "tool-error" || workflowToolError !== void 0) {
16750
+ const error = toolOutput2?.error ?? workflowToolError;
16067
16751
  state.span.log({
16068
16752
  error: error instanceof Error ? error.message : String(error),
16069
16753
  metrics: typeof event.durationMs === "number" ? { duration_ms: event.durationMs } : {}
16070
16754
  });
16071
16755
  } else {
16072
- const output = toolOutput && "output" in toolOutput ? toolOutput.output : event.output;
16756
+ const output = toolOutput2 && "output" in toolOutput2 ? toolOutput2.output : event.output;
16073
16757
  state.span.log({
16074
16758
  ...shouldRecordOutputs(event) ? { output } : {},
16075
16759
  metrics: typeof event.durationMs === "number" ? { duration_ms: event.durationMs } : {}
@@ -18528,9 +19212,9 @@ function patchAISDKStreamingResult(args) {
18528
19212
  }
18529
19213
  finalize({ metrics, output });
18530
19214
  } catch (error) {
18531
- const loggedError = toLoggedError(error);
19215
+ const loggedError2 = toLoggedError(error);
18532
19216
  try {
18533
- span.log({ error: loggedError });
19217
+ span.log({ error: loggedError2 });
18534
19218
  } catch (loggingError) {
18535
19219
  debugLogger.error(
18536
19220
  "Error logging AI SDK streaming failure:",
@@ -18538,7 +19222,7 @@ function patchAISDKStreamingResult(args) {
18538
19222
  );
18539
19223
  }
18540
19224
  finalize({
18541
- error: error instanceof Error ? error : new Error(String(loggedError))
19225
+ error: error instanceof Error ? error : new Error(String(loggedError2))
18542
19226
  });
18543
19227
  }
18544
19228
  };
@@ -18651,9 +19335,9 @@ function patchAISDKStreamingResult(args) {
18651
19335
  }
18652
19336
  controller.enqueue(value);
18653
19337
  } catch (error) {
18654
- const loggedError = toLoggedError(error);
19338
+ const loggedError2 = toLoggedError(error);
18655
19339
  try {
18656
- span.log({ error: loggedError });
19340
+ span.log({ error: loggedError2 });
18657
19341
  } catch (loggingError) {
18658
19342
  debugLogger.error(
18659
19343
  "Error logging AI SDK base stream failure:",
@@ -18661,7 +19345,7 @@ function patchAISDKStreamingResult(args) {
18661
19345
  );
18662
19346
  }
18663
19347
  finalize({
18664
- error: error instanceof Error ? error : new Error(String(loggedError))
19348
+ error: error instanceof Error ? error : new Error(String(loggedError2))
18665
19349
  });
18666
19350
  controller.error(error);
18667
19351
  }
@@ -21555,7 +22239,7 @@ function wrapSendOptionsCallbacks(options, state) {
21555
22239
  try {
21556
22240
  await handleInteractionUpdate(state, args.update);
21557
22241
  } catch (error) {
21558
- logInstrumentationError2("Cursor SDK onDelta", error);
22242
+ logInstrumentationError3("Cursor SDK onDelta", error);
21559
22243
  }
21560
22244
  if (originalOnDelta) {
21561
22245
  return originalOnDelta(args);
@@ -21565,7 +22249,7 @@ function wrapSendOptionsCallbacks(options, state) {
21565
22249
  try {
21566
22250
  handleStepUpdate(state, args.step);
21567
22251
  } catch (error) {
21568
- logInstrumentationError2("Cursor SDK onStep", error);
22252
+ logInstrumentationError3("Cursor SDK onStep", error);
21569
22253
  }
21570
22254
  if (originalOnStep) {
21571
22255
  return originalOnStep(args);
@@ -21647,7 +22331,7 @@ async function* patchCursorStream(stream, state) {
21647
22331
  try {
21648
22332
  await handleStreamMessage2(state, message);
21649
22333
  } catch (error) {
21650
- logInstrumentationError2("Cursor SDK stream", error);
22334
+ logInstrumentationError3("Cursor SDK stream", error);
21651
22335
  }
21652
22336
  yield message;
21653
22337
  }
@@ -21711,7 +22395,7 @@ async function handleToolUpdate(state, update) {
21711
22395
  if (!state.activeToolSpans.has(callId)) {
21712
22396
  state.activeToolSpans.set(
21713
22397
  callId,
21714
- await startToolSpan(state, {
22398
+ await startToolSpan2(state, {
21715
22399
  args,
21716
22400
  callId,
21717
22401
  name,
@@ -21722,7 +22406,7 @@ async function handleToolUpdate(state, update) {
21722
22406
  }
21723
22407
  return;
21724
22408
  }
21725
- const toolState = state.activeToolSpans.get(callId) ?? await startToolSpan(state, {
22409
+ const toolState = state.activeToolSpans.get(callId) ?? await startToolSpan2(state, {
21726
22410
  args,
21727
22411
  callId,
21728
22412
  name,
@@ -21759,7 +22443,7 @@ async function handleStreamMessage2(state, message) {
21759
22443
  } else if (block?.type === "tool_use" && block.id) {
21760
22444
  state.activeToolSpans.set(
21761
22445
  block.id,
21762
- await startToolSpan(state, {
22446
+ await startToolSpan2(state, {
21763
22447
  args: block.input,
21764
22448
  callId: block.id,
21765
22449
  name: block.name,
@@ -21794,7 +22478,7 @@ async function handleToolMessage(state, message) {
21794
22478
  if (!state.activeToolSpans.has(callId)) {
21795
22479
  state.activeToolSpans.set(
21796
22480
  callId,
21797
- await startToolSpan(state, {
22481
+ await startToolSpan2(state, {
21798
22482
  args: message.args,
21799
22483
  callId,
21800
22484
  name: message.name,
@@ -21805,7 +22489,7 @@ async function handleToolMessage(state, message) {
21805
22489
  }
21806
22490
  return;
21807
22491
  }
21808
- const toolState = state.activeToolSpans.get(callId) ?? await startToolSpan(state, {
22492
+ const toolState = state.activeToolSpans.get(callId) ?? await startToolSpan2(state, {
21809
22493
  args: message.args,
21810
22494
  callId,
21811
22495
  name: message.name,
@@ -21832,7 +22516,7 @@ async function handleConversation(state, turns) {
21832
22516
  const command = turn.turn?.shellCommand?.command;
21833
22517
  if (command) {
21834
22518
  const callId = `shell:${state.activeToolSpans.size}:${command}`;
21835
- const toolState = await startToolSpan(state, {
22519
+ const toolState = await startToolSpan2(state, {
21836
22520
  args: turn.turn?.shellCommand,
21837
22521
  callId,
21838
22522
  name: "shell",
@@ -21856,7 +22540,7 @@ async function handleConversationStep(state, step) {
21856
22540
  }
21857
22541
  const toolCall = step.message;
21858
22542
  const callId = typeof toolCall?.callId === "string" ? toolCall.callId : `conversation-tool:${state.activeToolSpans.size}`;
21859
- const toolState = await startToolSpan(state, {
22543
+ const toolState = await startToolSpan2(state, {
21860
22544
  args: extractToolArgs(toolCall),
21861
22545
  callId,
21862
22546
  name: extractToolName(toolCall),
@@ -21887,7 +22571,7 @@ function handleStepUpdate(state, step) {
21887
22571
  state.stepText.push(step.message.text);
21888
22572
  }
21889
22573
  }
21890
- async function startToolSpan(state, args) {
22574
+ async function startToolSpan2(state, args) {
21891
22575
  const name = args.name || "unknown";
21892
22576
  const metadata = {
21893
22577
  "cursor_sdk.tool.status": args.status,
@@ -22174,10 +22858,10 @@ function safeLog2(span, event) {
22174
22858
  try {
22175
22859
  span.log(event);
22176
22860
  } catch (error) {
22177
- logInstrumentationError2("Cursor SDK span log", error);
22861
+ logInstrumentationError3("Cursor SDK span log", error);
22178
22862
  }
22179
22863
  }
22180
- function logInstrumentationError2(context, error) {
22864
+ function logInstrumentationError3(context, error) {
22181
22865
  debugLogger.error(`Error processing ${context}:`, error);
22182
22866
  }
22183
22867
  function cleanMetrics2(metrics) {
@@ -22663,6 +23347,342 @@ var OpenAIAgentsPlugin = class extends BasePlugin {
22663
23347
  }
22664
23348
  };
22665
23349
 
23350
+ // src/instrumentation/plugins/google-generative-ai-channels.ts
23351
+ var googleGenerativeAIChannels = defineChannels(
23352
+ "@google/generative-ai",
23353
+ {
23354
+ generateContent: channel({ channelName: "GenerativeModel.generateContent", kind: "async" }),
23355
+ generateContentStream: channel({ channelName: "GenerativeModel.generateContentStream", kind: "async" }),
23356
+ embedContent: channel({ channelName: "GenerativeModel.embedContent", kind: "async" }),
23357
+ batchEmbedContents: channel({ channelName: "GenerativeModel.batchEmbedContents", kind: "async" }),
23358
+ sendMessage: channel({ channelName: "ChatSession.sendMessage", kind: "async" }),
23359
+ sendMessageStream: channel({ channelName: "ChatSession.sendMessageStream", kind: "async" })
23360
+ },
23361
+ { instrumentationName: INSTRUMENTATION_NAMES.GOOGLE_GENERATIVE_AI }
23362
+ );
23363
+
23364
+ // src/instrumentation/plugins/google-generative-ai-plugin.ts
23365
+ var GENERATION_CONFIG_KEYS = [
23366
+ "temperature",
23367
+ "topP",
23368
+ "topK",
23369
+ "candidateCount",
23370
+ "maxOutputTokens",
23371
+ "stopSequences",
23372
+ "responseMimeType",
23373
+ "responseSchema",
23374
+ "presencePenalty",
23375
+ "frequencyPenalty",
23376
+ "responseLogprobs",
23377
+ "logprobs",
23378
+ "thinkingConfig"
23379
+ ];
23380
+ var GoogleGenerativeAIPlugin = class extends BasePlugin {
23381
+ onEnable() {
23382
+ this.unsubscribers.push(
23383
+ interceptCall(
23384
+ googleGenerativeAIChannels.generateContent,
23385
+ "generateContent"
23386
+ ),
23387
+ interceptCall(
23388
+ googleGenerativeAIChannels.generateContentStream,
23389
+ "generateContentStream"
23390
+ ),
23391
+ interceptCall(googleGenerativeAIChannels.sendMessage, "sendMessage"),
23392
+ interceptCall(
23393
+ googleGenerativeAIChannels.sendMessageStream,
23394
+ "sendMessageStream"
23395
+ ),
23396
+ interceptCall(googleGenerativeAIChannels.embedContent, "embedContent"),
23397
+ interceptCall(
23398
+ googleGenerativeAIChannels.batchEmbedContents,
23399
+ "batchEmbedContents"
23400
+ )
23401
+ );
23402
+ }
23403
+ onDisable() {
23404
+ this.unsubscribers = unsubscribeAll(this.unsubscribers);
23405
+ }
23406
+ };
23407
+ function interceptCall(channel2, operation) {
23408
+ return channel2.intercept((target, thisArg, args) => {
23409
+ const invokeTarget = () => Reflect.apply(target, thisArg, args);
23410
+ if (isAutoInstrumentationSuppressed()) return invokeTarget();
23411
+ const self = thisArg;
23412
+ const chat = operation.startsWith("sendMessage");
23413
+ const embedding = operation === "embedContent" || operation === "batchEmbedContents";
23414
+ const start = getCurrentUnixTimestamp();
23415
+ let span;
23416
+ try {
23417
+ span = startSpan(
23418
+ withSpanInstrumentationName(
23419
+ {
23420
+ name: embedding ? operation === "embedContent" ? "embed_content" : "batch_embed_contents" : "generate_content",
23421
+ spanAttributes: { type: "llm" /* LLM */ },
23422
+ event: extractInput(self, args[0], operation)
23423
+ },
23424
+ INSTRUMENTATION_NAMES.GOOGLE_GENERATIVE_AI
23425
+ )
23426
+ );
23427
+ } catch (error) {
23428
+ debugLogger.error("Error starting Google Generative AI span:", error);
23429
+ return invokeTarget();
23430
+ }
23431
+ let ended = false;
23432
+ const finish = (log) => {
23433
+ if (ended) return;
23434
+ ended = true;
23435
+ try {
23436
+ log();
23437
+ } catch (error) {
23438
+ debugLogger.error("Error logging Google Generative AI span:", error);
23439
+ }
23440
+ try {
23441
+ span.end();
23442
+ } catch (error) {
23443
+ debugLogger.error("Error ending Google Generative AI span:", error);
23444
+ }
23445
+ };
23446
+ if (chat) {
23447
+ try {
23448
+ void self._sendPromise.then(
23449
+ () => {
23450
+ try {
23451
+ span.log(extractInput(self, args[0], operation));
23452
+ } catch (error) {
23453
+ debugLogger.error("Error capturing Google chat history:", error);
23454
+ }
23455
+ },
23456
+ () => {
23457
+ }
23458
+ );
23459
+ } catch (error) {
23460
+ debugLogger.error("Error observing Google chat history:", error);
23461
+ }
23462
+ }
23463
+ let result;
23464
+ try {
23465
+ result = withCurrent(
23466
+ span,
23467
+ () => runWithAutoInstrumentationSuppressed(invokeTarget)
23468
+ );
23469
+ } catch (error) {
23470
+ finish(() => span.log({ error }));
23471
+ throw error;
23472
+ }
23473
+ void Promise.resolve(result).then(
23474
+ (value) => {
23475
+ try {
23476
+ if ("stream" in value) {
23477
+ let firstToken = false;
23478
+ const partial = { candidates: [] };
23479
+ const candidates = /* @__PURE__ */ new Map();
23480
+ patchStreamIfNeeded(value.stream, {
23481
+ aroundNext: (callback) => withCurrent(span, callback),
23482
+ onChunk: (chunk) => {
23483
+ for (const candidate of chunk.candidates ?? []) {
23484
+ const index = candidate.index ?? 0;
23485
+ const previous = candidates.get(index);
23486
+ const parts = [...previous?.content?.parts ?? []];
23487
+ for (const part of candidate.content?.parts ?? []) {
23488
+ const last = parts[parts.length - 1];
23489
+ if (part.text !== void 0 && last?.text !== void 0) {
23490
+ parts[parts.length - 1] = {
23491
+ ...last,
23492
+ text: last.text + part.text
23493
+ };
23494
+ } else parts.push(part);
23495
+ }
23496
+ candidates.set(index, {
23497
+ ...previous,
23498
+ ...candidate,
23499
+ content: {
23500
+ role: candidate.content?.role ?? previous?.content?.role ?? "model",
23501
+ parts
23502
+ }
23503
+ });
23504
+ }
23505
+ partial.candidates = Array.from(candidates.values());
23506
+ if (chunk.usageMetadata)
23507
+ partial.usageMetadata = chunk.usageMetadata;
23508
+ if (!firstToken && chunk.candidates?.some(
23509
+ (candidate) => candidate.content?.parts.some(
23510
+ (part) => part.text !== void 0 ? part.text.length > 0 : Object.keys(part).length > 0
23511
+ )
23512
+ )) {
23513
+ firstToken = true;
23514
+ span.log({
23515
+ metrics: {
23516
+ time_to_first_token: getCurrentUnixTimestamp() - start
23517
+ }
23518
+ });
23519
+ }
23520
+ },
23521
+ onComplete: () => {
23522
+ },
23523
+ onError: (error) => finish(() => {
23524
+ logResponse(span, partial);
23525
+ span.log({ error });
23526
+ }),
23527
+ onCancel: () => finish(() => logResponse(span, partial))
23528
+ });
23529
+ void value.response.then(
23530
+ (response) => finish(() => logResponse(span, response)),
23531
+ (error) => finish(() => {
23532
+ logResponse(span, partial);
23533
+ span.log({ error });
23534
+ })
23535
+ );
23536
+ } else if ("response" in value) {
23537
+ finish(() => logResponse(span, value.response));
23538
+ } else {
23539
+ const metrics = {};
23540
+ const promptTokens = value.usageMetadata?.promptTokenCount;
23541
+ if (typeof promptTokens === "number" && Number.isFinite(promptTokens) && promptTokens >= 0) {
23542
+ metrics.prompt_tokens = promptTokens;
23543
+ metrics.tokens = promptTokens;
23544
+ }
23545
+ for (const detail of value.usageMetadata?.promptTokenDetails ?? []) {
23546
+ if (detail.modality === "AUDIO" && typeof detail.tokenCount === "number" && Number.isFinite(detail.tokenCount) && detail.tokenCount >= 0) {
23547
+ metrics.prompt_audio_tokens = (metrics.prompt_audio_tokens ?? 0) + detail.tokenCount;
23548
+ }
23549
+ }
23550
+ finish(
23551
+ () => span.log({
23552
+ metrics,
23553
+ output: {
23554
+ count: value.embeddings?.length ?? (value.embedding ? 1 : 0)
23555
+ }
23556
+ })
23557
+ );
23558
+ }
23559
+ } catch (error) {
23560
+ debugLogger.error(
23561
+ "Error observing Google Generative AI result:",
23562
+ error
23563
+ );
23564
+ finish(() => {
23565
+ });
23566
+ }
23567
+ },
23568
+ (error) => finish(() => span.log({ error }))
23569
+ );
23570
+ return result;
23571
+ });
23572
+ }
23573
+ function normalizeContent(message) {
23574
+ const parts = (typeof message === "string" ? [message] : message).map(
23575
+ (part) => typeof part === "string" ? { text: part } : part
23576
+ );
23577
+ return {
23578
+ role: parts.some((part) => part.functionResponse) ? "function" : "user",
23579
+ parts
23580
+ };
23581
+ }
23582
+ function extractInput(self, request, operation) {
23583
+ const model = self.model.replace(/^models\//, "");
23584
+ if (operation === "embedContent" || operation === "batchEmbedContents") {
23585
+ const requests = operation === "batchEmbedContents" ? request.requests : [
23586
+ typeof request === "string" || Array.isArray(request) ? { content: normalizeContent(request) } : request
23587
+ ];
23588
+ const dimensions = requests[0]?.outputDimensionality;
23589
+ return {
23590
+ input: {
23591
+ inputs: convertAttachments(requests).map((item) => ({
23592
+ content: item.content.parts.length === 1 && item.content.parts[0].text !== void 0 ? item.content.parts[0].text : item.content.parts.map((part) => {
23593
+ if (part.text !== void 0)
23594
+ return { type: "text", text: part.text };
23595
+ const mimeType = part.inlineData?.mimeType ?? part.fileData?.mimeType;
23596
+ const data = part.inlineData ? typeof part.inlineData.data === "string" ? `data:${mimeType};base64,${part.inlineData.data}` : part.inlineData.data : part.fileData?.fileUri;
23597
+ return mimeType?.startsWith("image/") ? { type: "image_url", image_url: { url: data } } : { type: "file", file: { file_data: data } };
23598
+ })
23599
+ })),
23600
+ ...dimensions !== void 0 && requests.every((item) => item.outputDimensionality === dimensions) ? { output_dimensions: dimensions } : {}
23601
+ },
23602
+ metadata: { model, provider: "google" }
23603
+ };
23604
+ }
23605
+ const chat = operation.startsWith("sendMessage");
23606
+ const config = chat ? self.params ?? {} : self;
23607
+ const params = typeof request === "string" || Array.isArray(request) ? { contents: [normalizeContent(request)] } : request;
23608
+ const system = params.systemInstruction ?? config.systemInstruction;
23609
+ const systemContent = typeof system === "string" ? { role: "system", parts: [{ text: system }] } : system && "parts" in system ? { ...system, role: "system" } : system ? { role: "system", parts: [system] } : void 0;
23610
+ const contents = [
23611
+ ...systemContent ? [systemContent] : [],
23612
+ ...chat ? self._history : [],
23613
+ ...params.contents
23614
+ ];
23615
+ const metadata = { model, provider: "google" };
23616
+ const generation = params.generationConfig ?? config.generationConfig;
23617
+ for (const key of GENERATION_CONFIG_KEYS) {
23618
+ if (generation && Object.hasOwn(generation, key))
23619
+ metadata[key] = generation[key];
23620
+ }
23621
+ for (const key of ["tools", "toolConfig", "safetySettings"]) {
23622
+ const value = params[key] ?? config[key];
23623
+ if (value !== void 0) metadata[key] = value;
23624
+ }
23625
+ const cached = params.cachedContent ?? config.cachedContent;
23626
+ if (cached)
23627
+ metadata.cachedContent = typeof cached === "string" ? cached : cached.name;
23628
+ return { input: convertAttachments({ model, contents }), metadata };
23629
+ }
23630
+ function convertAttachments(value) {
23631
+ const convert = (node) => {
23632
+ if (Array.isArray(node)) return node.map(convert);
23633
+ if (!isObject(node)) return node;
23634
+ if (isObject(node.inlineData)) {
23635
+ const { data, mimeType } = node.inlineData;
23636
+ const processed = processInputAttachments({
23637
+ type: "file",
23638
+ file: { file_data: `data:${mimeType};base64,${data}` }
23639
+ });
23640
+ if (typeof processed.file.file_data === "string")
23641
+ throw new Error("Unable to convert Google inline data");
23642
+ return {
23643
+ ...node,
23644
+ inlineData: { ...node.inlineData, data: processed.file.file_data }
23645
+ };
23646
+ }
23647
+ return Object.fromEntries(
23648
+ Object.entries(node).map(([key, item]) => [key, convert(item)])
23649
+ );
23650
+ };
23651
+ try {
23652
+ return convert(value);
23653
+ } catch (error) {
23654
+ debugLogger.error(
23655
+ "Error converting Google Generative AI attachments:",
23656
+ error
23657
+ );
23658
+ return value;
23659
+ }
23660
+ }
23661
+ function logResponse(span, response) {
23662
+ const usage = response.usageMetadata;
23663
+ const metrics = {};
23664
+ if (usage) {
23665
+ if (usage.promptTokenCount !== void 0)
23666
+ metrics.prompt_tokens = usage.promptTokenCount;
23667
+ if (usage.candidatesTokenCount !== void 0 || usage.thoughtsTokenCount !== void 0)
23668
+ metrics.completion_tokens = (usage.candidatesTokenCount ?? 0) + (usage.thoughtsTokenCount ?? 0);
23669
+ if (usage.totalTokenCount !== void 0)
23670
+ metrics.tokens = usage.totalTokenCount;
23671
+ if (usage.cachedContentTokenCount !== void 0)
23672
+ metrics.prompt_cached_tokens = usage.cachedContentTokenCount;
23673
+ if (usage.thoughtsTokenCount !== void 0)
23674
+ metrics.completion_reasoning_tokens = usage.thoughtsTokenCount;
23675
+ }
23676
+ span.log({
23677
+ output: convertAttachments({
23678
+ candidates: response.candidates,
23679
+ promptFeedback: response.promptFeedback
23680
+ }),
23681
+ metrics,
23682
+ ...response.modelVersion ? { metadata: { model: response.modelVersion } } : {}
23683
+ });
23684
+ }
23685
+
22666
23686
  // src/instrumentation/plugins/google-genai-channels.ts
22667
23687
  var googleGenAIChannels = defineChannels(
22668
23688
  "@google/genai",
@@ -22679,6 +23699,10 @@ var googleGenAIChannels = defineChannels(
22679
23699
  channelName: "models.embedContent",
22680
23700
  kind: "async"
22681
23701
  }),
23702
+ httpResponseJson: channel({
23703
+ channelName: "httpResponse.json",
23704
+ kind: "async"
23705
+ }),
22682
23706
  interactionsCreate: channel({
22683
23707
  channelName: "interactions.create",
22684
23708
  kind: "async"
@@ -22827,13 +23851,45 @@ var GoogleGenAIPlugin = class extends BasePlugin {
22827
23851
  subscribeToEmbedContentChannel() {
22828
23852
  const tracingChannel = googleGenAIChannels.embedContent.tracingChannel();
22829
23853
  const states = /* @__PURE__ */ new WeakMap();
23854
+ const embeddingSpans = /* @__PURE__ */ new WeakSet();
23855
+ this.unsubscribers.push(
23856
+ googleGenAIChannels.httpResponseJson.intercept(
23857
+ (target, thisArg, args) => {
23858
+ const span = currentSpan();
23859
+ const result = Reflect.apply(target, thisArg, args);
23860
+ if (embeddingSpans.has(span)) {
23861
+ void Promise.resolve(result).then(
23862
+ (response) => {
23863
+ try {
23864
+ const metrics = cleanMetrics3(
23865
+ extractEmbedContentMetrics(response)
23866
+ );
23867
+ if (embeddingSpans.has(span) && Object.keys(metrics).length > 0) {
23868
+ span.log({ metrics });
23869
+ }
23870
+ } catch (error) {
23871
+ debugLogger.error(
23872
+ "Error reading Google GenAI embedding usage:",
23873
+ error
23874
+ );
23875
+ }
23876
+ },
23877
+ () => {
23878
+ }
23879
+ // The embedding channel handles the original rejection.
23880
+ );
23881
+ }
23882
+ return result;
23883
+ }
23884
+ )
23885
+ );
22830
23886
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart2(
22831
23887
  tracingChannel,
22832
23888
  states,
22833
23889
  (event) => {
22834
23890
  const params = event.arguments[0];
22835
23891
  const input = serializeEmbedContentInput(params);
22836
- const metadata = extractEmbedContentMetadata(params);
23892
+ const metadata = { provider: "google", model: params.model };
22837
23893
  const span = startSpan(
22838
23894
  withSpanInstrumentationName(
22839
23895
  {
@@ -22846,6 +23902,7 @@ var GoogleGenAIPlugin = class extends BasePlugin {
22846
23902
  INSTRUMENTATION_NAMES.GOOGLE_GENAI
22847
23903
  )
22848
23904
  );
23905
+ embeddingSpans.add(span);
22849
23906
  return {
22850
23907
  span,
22851
23908
  startTime: getCurrentUnixTimestamp()
@@ -22857,7 +23914,7 @@ var GoogleGenAIPlugin = class extends BasePlugin {
22857
23914
  ensureSpanState(states, event, () => {
22858
23915
  const params = event.arguments[0];
22859
23916
  const input = serializeEmbedContentInput(params);
22860
- const metadata = extractEmbedContentMetadata(params);
23917
+ const metadata = { provider: "google", model: params.model };
22861
23918
  const span = startSpan(
22862
23919
  withSpanInstrumentationName(
22863
23920
  {
@@ -22870,6 +23927,7 @@ var GoogleGenAIPlugin = class extends BasePlugin {
22870
23927
  INSTRUMENTATION_NAMES.GOOGLE_GENAI
22871
23928
  )
22872
23929
  );
23930
+ embeddingSpans.add(span);
22873
23931
  return {
22874
23932
  span,
22875
23933
  startTime: getCurrentUnixTimestamp()
@@ -22882,20 +23940,28 @@ var GoogleGenAIPlugin = class extends BasePlugin {
22882
23940
  return;
22883
23941
  }
22884
23942
  try {
22885
- const output = summarizeEmbedContentOutput(event.result);
22886
23943
  spanState.span.log({
22887
- ...output ? { output } : {},
23944
+ output: summarizeEmbedContentOutput(event.result),
22888
23945
  metrics: cleanMetrics3(
22889
23946
  extractEmbedContentMetrics(event.result, spanState.startTime)
22890
23947
  )
22891
23948
  });
22892
23949
  } finally {
23950
+ embeddingSpans.delete(spanState.span);
22893
23951
  spanState.span.end();
22894
23952
  states.delete(event);
22895
23953
  }
22896
23954
  },
22897
23955
  error: (event) => {
22898
- logErrorAndEndSpan(states, event);
23956
+ const spanState = states.get(event);
23957
+ if (!spanState) return;
23958
+ try {
23959
+ spanState.span.log({ error: event.error, output: { count: 0 } });
23960
+ } finally {
23961
+ embeddingSpans.delete(spanState.span);
23962
+ spanState.span.end();
23963
+ states.delete(event);
23964
+ }
22899
23965
  }
22900
23966
  };
22901
23967
  tracingChannel.subscribe(handlers);
@@ -23130,15 +24196,53 @@ function serializeGenerateContentInput(params) {
23130
24196
  return input;
23131
24197
  }
23132
24198
  function serializeEmbedContentInput(params) {
24199
+ let contents = Array.isArray(params.contents) ? params.contents : [params.contents];
24200
+ if (params.model.includes("gemini-embedding-2") && contents.length > 0 && contents.every(
24201
+ (content) => typeof content === "string" || !Array.isArray(content) && !("parts" in content)
24202
+ )) {
24203
+ contents = [contents];
24204
+ }
23133
24205
  const input = {
23134
- model: params.model,
23135
- contents: serializeContentCollection(params.contents)
24206
+ inputs: contents.map((content) => {
24207
+ const parts = typeof content === "string" ? [content] : Array.isArray(content) ? content : "parts" in content ? content.parts : [content];
24208
+ const normalized = parts.flatMap((part) => {
24209
+ if (typeof part === "string") return [{ type: "text", text: part }];
24210
+ if (part.text !== void 0) return [{ type: "text", text: part.text }];
24211
+ const media = part.inlineData ?? part.fileData;
24212
+ if (!media) return [];
24213
+ const data = "data" in media ? `data:${media.mimeType};base64,${typeof media.data === "string" ? media.data : uint8ArrayToBase64(media.data)}` : media.fileUri;
24214
+ return media.mimeType?.startsWith("image/") ? [{ type: "image_url", image_url: { url: data } }] : [
24215
+ {
24216
+ type: "file",
24217
+ file: {
24218
+ file_data: data,
24219
+ ..."displayName" in media && media.displayName ? { filename: media.displayName } : {}
24220
+ }
24221
+ }
24222
+ ];
24223
+ });
24224
+ return {
24225
+ content: normalized.length === 1 && normalized[0].type === "text" ? normalized[0].text : normalized
24226
+ };
24227
+ }),
24228
+ ...params.config?.outputDimensionality !== void 0 ? { output_dimensions: params.config.outputDimensionality } : {}
23136
24229
  };
23137
- const config = params.config ? tryToDict(params.config) : null;
23138
- if (config) {
23139
- input.config = config;
24230
+ try {
24231
+ const processed = processInputAttachments(input);
24232
+ const hasInlineMedia = processed.inputs.some(
24233
+ ({ content }) => Array.isArray(content) && content.some((part) => {
24234
+ const data = part.type === "image_url" ? part.image_url.url : part.type === "file" ? part.file.file_data : void 0;
24235
+ return typeof data === "string" && data.startsWith("data:");
24236
+ })
24237
+ );
24238
+ return hasInlineMedia ? input : processed;
24239
+ } catch (error) {
24240
+ debugLogger.error(
24241
+ "Error processing Google GenAI embedding attachments:",
24242
+ error
24243
+ );
24244
+ return input;
23140
24245
  }
23141
- return input;
23142
24246
  }
23143
24247
  function serializeInteractionInput(params) {
23144
24248
  const input = {
@@ -23326,19 +24430,6 @@ function extractGenerateContentMetadata(params) {
23326
24430
  }
23327
24431
  return metadata;
23328
24432
  }
23329
- function extractEmbedContentMetadata(params) {
23330
- const metadata = {};
23331
- if (params.model) {
23332
- metadata.model = params.model;
23333
- }
23334
- const config = params.config ? tryToDict(params.config) : null;
23335
- if (config) {
23336
- Object.keys(config).forEach((key) => {
23337
- metadata[key] = config[key];
23338
- });
23339
- }
23340
- return metadata;
23341
- }
23342
24433
  function extractGenerateContentMetrics(response, startTime) {
23343
24434
  const metrics = {};
23344
24435
  if (startTime !== void 0) {
@@ -23358,15 +24449,23 @@ function extractEmbedContentMetrics(response, startTime) {
23358
24449
  const end = getCurrentUnixTimestamp();
23359
24450
  metrics.start = startTime;
23360
24451
  metrics.end = end;
23361
- metrics.duration = end - startTime;
23362
- }
23363
- if (response?.usageMetadata) {
23364
- populateUsageMetrics(metrics, response.usageMetadata);
23365
24452
  }
23366
24453
  const embeddingTokenCount = extractEmbedPromptTokenCount(response);
23367
24454
  if (embeddingTokenCount !== void 0) {
23368
24455
  metrics.prompt_tokens = embeddingTokenCount;
23369
- metrics.tokens = embeddingTokenCount;
24456
+ }
24457
+ const totalTokens = response?.usageMetadata?.totalTokenCount ?? embeddingTokenCount;
24458
+ if (totalTokens !== void 0) {
24459
+ metrics.tokens = totalTokens;
24460
+ }
24461
+ const audioTokens = (response?.usageMetadata?.promptTokenDetails ?? response?.usageMetadata?.promptTokensDetails)?.filter(
24462
+ (detail) => detail.modality === "AUDIO" && detail.tokenCount !== void 0
24463
+ );
24464
+ if (audioTokens?.length) {
24465
+ metrics.prompt_audio_tokens = audioTokens.reduce(
24466
+ (sum, detail) => sum + (detail.tokenCount ?? 0),
24467
+ 0
24468
+ );
23370
24469
  }
23371
24470
  return metrics;
23372
24471
  }
@@ -23405,41 +24504,25 @@ function extractEmbedPromptTokenCount(response) {
23405
24504
  if (typeof usagePromptTokens === "number" && Number.isFinite(usagePromptTokens)) {
23406
24505
  return usagePromptTokens;
23407
24506
  }
23408
- const usageTotalTokens = response.usageMetadata?.totalTokenCount;
23409
- if (typeof usageTotalTokens === "number" && Number.isFinite(usageTotalTokens)) {
23410
- return usageTotalTokens;
23411
- }
23412
24507
  const embeddings = Array.isArray(response.embeddings) ? response.embeddings : response.embedding ? [response.embedding] : [];
23413
24508
  if (embeddings.length === 0) {
23414
24509
  return void 0;
23415
24510
  }
23416
24511
  let total = 0;
23417
- let sawAny = false;
23418
24512
  for (const embedding of embeddings) {
23419
24513
  const embeddingStats = tryToDict(tryToDict(embedding)?.statistics);
23420
24514
  const tokenCount2 = embeddingStats?.tokenCount;
23421
24515
  if (typeof tokenCount2 === "number" && Number.isFinite(tokenCount2)) {
23422
24516
  total += tokenCount2;
23423
- sawAny = true;
24517
+ } else {
24518
+ return void 0;
23424
24519
  }
23425
24520
  }
23426
- return sawAny ? total : void 0;
24521
+ return total;
23427
24522
  }
23428
24523
  function summarizeEmbedContentOutput(response) {
23429
- if (!response) {
23430
- return void 0;
23431
- }
23432
- const embeddings = Array.isArray(response.embeddings) ? response.embeddings : response.embedding ? [response.embedding] : [];
23433
- if (embeddings.length === 0) {
23434
- return void 0;
23435
- }
23436
- const firstValues = embeddings[0]?.values;
23437
- if (!Array.isArray(firstValues)) {
23438
- return void 0;
23439
- }
23440
24524
  return {
23441
- embedding_count: embeddings.length,
23442
- embedding_length: firstValues.length
24525
+ count: Array.isArray(response?.embeddings) ? response.embeddings.length : response?.embedding ? 1 : 0
23443
24526
  };
23444
24527
  }
23445
24528
  function populateUsageMetrics(metrics, usage) {
@@ -24306,7 +25389,7 @@ var HuggingFaceTransformersPlugin = class extends BasePlugin {
24306
25389
  getTask(event)
24307
25390
  ),
24308
25391
  extractInput: (args, event) => ({
24309
- input: extractInput(
25392
+ input: extractInput2(
24310
25393
  getTask(event),
24311
25394
  args
24312
25395
  ),
@@ -24396,7 +25479,7 @@ function modelIdentifier(pipeline) {
24396
25479
  }
24397
25480
  return void 0;
24398
25481
  }
24399
- function extractInput(task, args) {
25482
+ function extractInput2(task, args) {
24400
25483
  switch (task) {
24401
25484
  case "feature-extraction":
24402
25485
  return args[0];
@@ -27066,6 +28149,379 @@ function aggregateMistralStreamChunks(chunks) {
27066
28149
  };
27067
28150
  }
27068
28151
 
28152
+ // src/instrumentation/plugins/langgraph-sdk-channels.ts
28153
+ var langGraphSDKChannels = defineChannels(
28154
+ "@langchain/langgraph-sdk",
28155
+ {
28156
+ wait: channel({
28157
+ channelName: "runs.wait",
28158
+ kind: "async"
28159
+ }),
28160
+ stream: channel({
28161
+ channelName: "runs.stream",
28162
+ kind: "sync-stream"
28163
+ })
28164
+ },
28165
+ { instrumentationName: INSTRUMENTATION_NAMES.LANGGRAPH_SDK }
28166
+ );
28167
+
28168
+ // src/instrumentation/plugins/langgraph-sdk-plugin.ts
28169
+ var LangGraphSDKPlugin = class extends BasePlugin {
28170
+ onEnable() {
28171
+ this.unsubscribers.push(
28172
+ langGraphSDKChannels.wait.intercept(
28173
+ (target, self, args) => instrumentRun("wait", args, () => Reflect.apply(target, self, args))
28174
+ ),
28175
+ langGraphSDKChannels.stream.intercept(
28176
+ (target, self, args) => instrumentRun("stream", args, () => Reflect.apply(target, self, args))
28177
+ )
28178
+ );
28179
+ }
28180
+ onDisable() {
28181
+ this.unsubscribers = unsubscribeAll(this.unsubscribers);
28182
+ }
28183
+ };
28184
+ function normalizeMessage(value) {
28185
+ if (!isObject(value)) return value;
28186
+ const role = value.role ?? (value.type === "human" ? "user" : value.type === "ai" || value.type === "AIMessageChunk" ? "assistant" : value.type === "system" || value.type === "tool" || value.type === "function" ? value.type : void 0);
28187
+ if (typeof role !== "string") return value;
28188
+ const message = {
28189
+ role,
28190
+ content: value.content ?? ""
28191
+ };
28192
+ for (const key of ["name", "tool_call_id", "refusal"]) {
28193
+ if (value[key] !== void 0) message[key] = value[key];
28194
+ }
28195
+ const additional = isObject(value.additional_kwargs) ? value.additional_kwargs : {};
28196
+ const toolCalls = Array.isArray(value.tool_calls) && value.tool_calls.length ? value.tool_calls : additional.tool_calls;
28197
+ if (Array.isArray(toolCalls) && toolCalls.length > 0) {
28198
+ message.tool_calls = toolCalls.map((call) => {
28199
+ if (!isObject(call)) return call;
28200
+ if (isObject(call.function)) return call;
28201
+ return {
28202
+ id: call.id,
28203
+ type: "function",
28204
+ function: {
28205
+ name: call.name,
28206
+ arguments: typeof call.args === "string" ? call.args : JSON.stringify(call.args ?? {})
28207
+ }
28208
+ };
28209
+ });
28210
+ }
28211
+ if (Array.isArray(value.invalid_tool_calls) && value.invalid_tool_calls.length > 0)
28212
+ message.invalid_tool_calls = value.invalid_tool_calls;
28213
+ if (message.refusal === void 0 && additional.refusal !== void 0)
28214
+ message.refusal = additional.refusal;
28215
+ return message;
28216
+ }
28217
+ function normalizeRunError(value) {
28218
+ let name;
28219
+ let message;
28220
+ if (value instanceof Error) {
28221
+ name = value.name;
28222
+ message = value.message;
28223
+ } else if (isObject(value) && typeof value.error === "string" && typeof value.message === "string") {
28224
+ name = value.error;
28225
+ message = value.message;
28226
+ } else {
28227
+ return value;
28228
+ }
28229
+ for (let depth = 0; depth < 3; depth++) {
28230
+ try {
28231
+ const nested = JSON.parse(
28232
+ message.startsWith(`${name}: `) ? message.slice(name.length + 2) : message
28233
+ );
28234
+ if (!isObject(nested) || typeof nested.error !== "string" || typeof nested.message !== "string")
28235
+ break;
28236
+ name = nested.error;
28237
+ message = nested.message;
28238
+ } catch {
28239
+ break;
28240
+ }
28241
+ }
28242
+ if (value instanceof Error && name === value.name && message === value.message)
28243
+ return value;
28244
+ return Object.assign(new Error(message), { name });
28245
+ }
28246
+ function normalizeState(value) {
28247
+ if (!isObject(value)) return value;
28248
+ return Object.fromEntries(
28249
+ Object.entries(value).map(([key, field]) => {
28250
+ if (key === "messages" && Array.isArray(field))
28251
+ return [key, field.map(normalizeMessage)];
28252
+ if (key === "__error__") {
28253
+ const error = normalizeRunError(field);
28254
+ if (error instanceof Error)
28255
+ return [key, { error: error.name, message: error.message }];
28256
+ }
28257
+ return [key, field];
28258
+ })
28259
+ );
28260
+ }
28261
+ function normalizeRunOutput(value, input) {
28262
+ if (!isObject(value)) return value;
28263
+ if (Array.isArray(value.messages)) {
28264
+ if (value.__interrupt__ !== void 0 || value.__error__ !== void 0)
28265
+ return void 0;
28266
+ const inputMessages = isObject(input) && Array.isArray(input.messages) ? input.messages : [];
28267
+ let inputPrefixLength = 0;
28268
+ while (inputPrefixLength < inputMessages.length) {
28269
+ const previous = inputMessages[inputPrefixLength];
28270
+ const message = value.messages[inputPrefixLength];
28271
+ if (isObject(previous) && isObject(message) && previous.id !== void 0 && message.id !== void 0 && previous.id !== message.id || JSON.stringify(normalizeMessage(previous)) !== JSON.stringify(normalizeMessage(message)))
28272
+ break;
28273
+ inputPrefixLength++;
28274
+ }
28275
+ for (let index = value.messages.length - 1; index >= inputPrefixLength; index--) {
28276
+ const message = value.messages[index];
28277
+ const normalized = normalizeMessage(message);
28278
+ if (!isObject(normalized)) continue;
28279
+ if (normalized.role === "user") return void 0;
28280
+ if (normalized.role !== "assistant") continue;
28281
+ if (inputMessages.some((previous) => {
28282
+ if (!isObject(previous) || !isObject(message)) return false;
28283
+ return previous.id !== void 0 && previous.id === message.id && JSON.stringify(normalizeMessage(previous)) === JSON.stringify(normalized);
28284
+ }))
28285
+ continue;
28286
+ return normalized;
28287
+ }
28288
+ return void 0;
28289
+ }
28290
+ const result = Object.fromEntries(
28291
+ Object.entries(value).filter(
28292
+ ([key]) => key !== "__interrupt__" && key !== "__error__"
28293
+ )
28294
+ );
28295
+ return !Object.keys(result).length && (value.__interrupt__ !== void 0 || value.__error__ !== void 0) ? void 0 : result;
28296
+ }
28297
+ function instrumentRun(operation, [threadId, assistantId, options], invoke) {
28298
+ if (isAutoInstrumentationSuppressed()) return invoke();
28299
+ const start = getCurrentUnixTimestamp();
28300
+ let span;
28301
+ try {
28302
+ const metadata = {
28303
+ "langgraph.thread_id": threadId,
28304
+ "langgraph.assistant_id": assistantId
28305
+ };
28306
+ for (const key of [
28307
+ "streamMode",
28308
+ "streamSubgraphs",
28309
+ "interruptBefore",
28310
+ "interruptAfter",
28311
+ "multitaskStrategy",
28312
+ "durability"
28313
+ ]) {
28314
+ if (options?.[key] !== void 0) metadata[key] = options[key];
28315
+ }
28316
+ span = startSpan(
28317
+ withSpanInstrumentationName(
28318
+ {
28319
+ name: `langgraph.runs.${operation}`,
28320
+ spanAttributes: { type: "task" /* TASK */ },
28321
+ event: {
28322
+ input: options?.command === void 0 ? normalizeState(options?.input) : {
28323
+ input: normalizeState(options.input),
28324
+ command: options.command
28325
+ },
28326
+ metadata
28327
+ }
28328
+ },
28329
+ INSTRUMENTATION_NAMES.LANGGRAPH_SDK
28330
+ )
28331
+ );
28332
+ } catch (error) {
28333
+ debugLogger.error("Error starting LangGraph SDK span:", error);
28334
+ return invoke();
28335
+ }
28336
+ let ended = false;
28337
+ let output;
28338
+ let streamError;
28339
+ let firstToken;
28340
+ const updates = [];
28341
+ const usageByMessage = /* @__PURE__ */ new Map();
28342
+ const captureUsage = (id, usage) => {
28343
+ if (!isObject(usage)) return;
28344
+ const metrics = {};
28345
+ for (const [source, destination] of [
28346
+ ["input_tokens", "prompt_tokens"],
28347
+ ["output_tokens", "completion_tokens"],
28348
+ ["total_tokens", "tokens"]
28349
+ ]) {
28350
+ const value = usage[source];
28351
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0)
28352
+ metrics[destination] = value;
28353
+ }
28354
+ if (metrics.tokens === void 0 && metrics.prompt_tokens !== void 0 && metrics.completion_tokens !== void 0)
28355
+ metrics.tokens = metrics.prompt_tokens + metrics.completion_tokens;
28356
+ usageByMessage.set(id, { ...usageByMessage.get(id), ...metrics });
28357
+ };
28358
+ const messages = /* @__PURE__ */ new Map();
28359
+ const messageSnapshots = /* @__PURE__ */ new Map();
28360
+ const finish = (error) => {
28361
+ if (ended) return;
28362
+ ended = true;
28363
+ try {
28364
+ const metrics = {};
28365
+ for (const usage of usageByMessage.values()) {
28366
+ for (const [key, value] of Object.entries(usage))
28367
+ metrics[key] = (metrics[key] ?? 0) + value;
28368
+ }
28369
+ if (firstToken !== void 0)
28370
+ metrics.time_to_first_token = firstToken - start;
28371
+ const finalMessages = [
28372
+ ...new Map([...messages, ...messageSnapshots]).values()
28373
+ ];
28374
+ let loggedOutput = normalizeRunOutput(output, options?.input);
28375
+ if (loggedOutput === void 0 && finalMessages.length)
28376
+ loggedOutput = normalizeRunOutput(
28377
+ { messages: finalMessages },
28378
+ void 0
28379
+ );
28380
+ if (output === void 0 && !finalMessages.length && updates.length) {
28381
+ const results = updates.map((update) => normalizeRunOutput(update, options?.input)).filter((update) => update !== void 0);
28382
+ if (results.length) loggedOutput = { updates: results };
28383
+ }
28384
+ const interrupted = [output, ...updates].find(
28385
+ (state) => isObject(state) && state.__interrupt__ !== void 0
28386
+ );
28387
+ span.log({
28388
+ ...loggedOutput !== void 0 ? { output: loggedOutput } : {},
28389
+ ...isObject(interrupted) ? { metadata: { "langgraph.interrupts": interrupted.__interrupt__ } } : {},
28390
+ ...error !== void 0 || streamError !== void 0 ? { error: normalizeRunError(error ?? streamError) } : {},
28391
+ metrics
28392
+ });
28393
+ } catch (error2) {
28394
+ debugLogger.error("Error logging LangGraph SDK span:", error2);
28395
+ }
28396
+ try {
28397
+ span.end();
28398
+ } catch (error2) {
28399
+ debugLogger.error("Error ending LangGraph SDK span:", error2);
28400
+ }
28401
+ };
28402
+ const observeMessages = (value, streaming) => {
28403
+ if (!isObject(value) || !Array.isArray(value.messages)) return;
28404
+ const inputMessages = isObject(options?.input) && Array.isArray(options.input.messages) ? options.input.messages : [];
28405
+ for (const message of value.messages) {
28406
+ if (!isObject(message) || message.type !== "ai" && message.role !== "assistant")
28407
+ continue;
28408
+ if (message.id !== void 0 && inputMessages.some(
28409
+ (input) => isObject(input) && input.id === message.id
28410
+ ))
28411
+ continue;
28412
+ captureUsage(
28413
+ typeof message.id === "string" ? message.id : "message",
28414
+ message.usage_metadata
28415
+ );
28416
+ if (streaming && (typeof message.content === "string" ? message.content.length > 0 : Array.isArray(message.content) && message.content.some(
28417
+ (part) => isObject(part) && typeof part.text === "string" && part.text.length > 0
28418
+ )))
28419
+ firstToken ??= getCurrentUnixTimestamp();
28420
+ }
28421
+ };
28422
+ const onChunk = ({ event, data }) => {
28423
+ if (ended) return;
28424
+ if (event === "metadata" && isObject(data)) {
28425
+ if (typeof data.run_id === "string")
28426
+ span.log({ metadata: { "langgraph.run_id": data.run_id } });
28427
+ } else if (event === "error") {
28428
+ streamError = normalizeRunError(data);
28429
+ } else if (event === "values") {
28430
+ output = data;
28431
+ observeMessages(data, true);
28432
+ } else if (event === "updates") {
28433
+ if (isObject(data)) {
28434
+ const stateUpdates = [];
28435
+ for (const [node, update] of Object.entries(data)) {
28436
+ observeMessages(update, true);
28437
+ if (isObject(update) && Array.isArray(update.messages)) {
28438
+ for (const message of update.messages) {
28439
+ if (isObject(message))
28440
+ messageSnapshots.set(
28441
+ typeof message.id === "string" ? message.id : `update-${messageSnapshots.size}`,
28442
+ message
28443
+ );
28444
+ }
28445
+ const state = Object.fromEntries(
28446
+ Object.entries(update).filter(([key]) => key !== "messages")
28447
+ );
28448
+ if (Object.keys(state).length) stateUpdates.push([node, state]);
28449
+ } else {
28450
+ stateUpdates.push([node, update]);
28451
+ }
28452
+ }
28453
+ if (stateUpdates.length) updates.push(Object.fromEntries(stateUpdates));
28454
+ } else {
28455
+ updates.push(data);
28456
+ }
28457
+ } else if ((event === "messages" || event === "messages/partial" || event === "messages/complete") && Array.isArray(data)) {
28458
+ const parts = event === "messages" ? [data[0]] : data;
28459
+ for (const part of parts) {
28460
+ if (!isObject(part)) continue;
28461
+ const id = typeof part.id === "string" ? part.id : "message";
28462
+ captureUsage(id, part.usage_metadata);
28463
+ const previous = messages.get(id);
28464
+ messages.set(
28465
+ id,
28466
+ event === "messages" && previous && typeof part.content === "string" && typeof previous.content === "string" ? { ...part, content: previous.content + part.content } : part
28467
+ );
28468
+ if (typeof part.content === "string" && part.content.length > 0)
28469
+ firstToken ??= getCurrentUnixTimestamp();
28470
+ }
28471
+ }
28472
+ };
28473
+ let result;
28474
+ try {
28475
+ result = withCurrent(
28476
+ span,
28477
+ () => runWithAutoInstrumentationSuppressed(invoke)
28478
+ );
28479
+ } catch (error) {
28480
+ finish(error);
28481
+ throw error;
28482
+ }
28483
+ if (operation === "stream") {
28484
+ try {
28485
+ patchStreamIfNeeded(result, {
28486
+ shouldCollect: (chunk) => {
28487
+ try {
28488
+ onChunk(chunk);
28489
+ } catch (error) {
28490
+ debugLogger.error(
28491
+ "Error processing LangGraph stream event:",
28492
+ error
28493
+ );
28494
+ }
28495
+ return false;
28496
+ },
28497
+ aroundNext: (next) => withCurrent(span, () => runWithAutoInstrumentationSuppressed(next)),
28498
+ onComplete: () => finish(),
28499
+ onCancel: () => finish(),
28500
+ onError: (error) => finish(error)
28501
+ });
28502
+ } catch (error) {
28503
+ debugLogger.error("Error observing LangGraph stream:", error);
28504
+ finish();
28505
+ }
28506
+ } else {
28507
+ void Promise.resolve(result).then(
28508
+ (value) => {
28509
+ try {
28510
+ output = value;
28511
+ observeMessages(value, false);
28512
+ if (isObject(value) && isObject(value.__error__))
28513
+ streamError = normalizeRunError(value.__error__);
28514
+ finish();
28515
+ } catch (error) {
28516
+ finish(error);
28517
+ }
28518
+ },
28519
+ (error) => finish(error)
28520
+ );
28521
+ }
28522
+ return result;
28523
+ }
28524
+
27069
28525
  // src/instrumentation/plugins/ollama-channels.ts
27070
28526
  var ollamaChannels = defineChannels(
27071
28527
  "ollama",
@@ -27275,7 +28731,7 @@ function normalizeTextAndImages(content, images) {
27275
28731
  ...unrecognizedImages.length > 0 ? { unrecognizedImages } : {}
27276
28732
  };
27277
28733
  }
27278
- function normalizeMessage(message, toolCallId, syntheticToolCallIdOffset = 0) {
28734
+ function normalizeMessage2(message, toolCallId, syntheticToolCallIdOffset = 0) {
27279
28735
  if (typeof message.role !== "string") {
27280
28736
  return void 0;
27281
28737
  }
@@ -27321,7 +28777,7 @@ function normalizeMessages(messages) {
27321
28777
  toolCallId = pendingToolCallIds.get(toolName)?.shift();
27322
28778
  }
27323
28779
  }
27324
- const normalized = normalizeMessage(
28780
+ const normalized = normalizeMessage2(
27325
28781
  ollamaMessage,
27326
28782
  toolCallId,
27327
28783
  syntheticToolCallIdOffset
@@ -27440,7 +28896,7 @@ function extractOllamaChatOutput(result, syntheticToolCallIdOffset = 0) {
27440
28896
  if (!isObject(result) || !isObject(result.message)) {
27441
28897
  return void 0;
27442
28898
  }
27443
- const message = normalizeMessage(
28899
+ const message = normalizeMessage2(
27444
28900
  result.message,
27445
28901
  void 0,
27446
28902
  syntheticToolCallIdOffset
@@ -30160,14 +31616,14 @@ function extractActionSpanMetadata(args) {
30160
31616
  const options = extractRunInNewSpanOptions(args);
30161
31617
  const labels = isObject(options?.labels) ? options.labels : void 0;
30162
31618
  const metadata = isObject(options?.metadata) ? options.metadata : void 0;
30163
- const actionType = stringValue(labels?.["genkit:metadata:subtype"]);
30164
- const name = stringValue(metadata?.name);
31619
+ const actionType = stringValue2(labels?.["genkit:metadata:subtype"]);
31620
+ const name = stringValue2(metadata?.name);
30165
31621
  if (!actionType || !name) {
30166
31622
  return void 0;
30167
31623
  }
30168
31624
  return {
30169
31625
  actionType,
30170
- key: stringValue(labels?.["genkit:key"]),
31626
+ key: stringValue2(labels?.["genkit:key"]),
30171
31627
  name
30172
31628
  };
30173
31629
  }
@@ -30277,7 +31733,7 @@ function pickNumberMetrics(values) {
30277
31733
  })
30278
31734
  );
30279
31735
  }
30280
- function stringValue(value) {
31736
+ function stringValue2(value) {
30281
31737
  return typeof value === "string" ? value : void 0;
30282
31738
  }
30283
31739
 
@@ -30962,7 +32418,7 @@ function subscribeToFlueContext(value, state) {
30962
32418
  try {
30963
32419
  unsubscribe?.();
30964
32420
  } catch (error) {
30965
- logInstrumentationError3("Flue context unsubscribe", error);
32421
+ logInstrumentationError4("Flue context unsubscribe", error);
30966
32422
  }
30967
32423
  };
30968
32424
  try {
@@ -30978,7 +32434,7 @@ function subscribeToFlueContext(value, state) {
30978
32434
  });
30979
32435
  state.contexts.add(value);
30980
32436
  } catch (error) {
30981
- logInstrumentationError3("Flue context subscription", error);
32437
+ logInstrumentationError4("Flue context subscription", error);
30982
32438
  }
30983
32439
  }
30984
32440
  function isAutoContextTerminalEvent(event, ctx) {
@@ -31034,7 +32490,7 @@ var FlueObserveBridge = class {
31034
32490
  try {
31035
32491
  this.handleEvent(event, flueContextFromUnknown(ctx));
31036
32492
  } catch (error) {
31037
- logInstrumentationError3("Flue observe", error);
32493
+ logInstrumentationError4("Flue observe", error);
31038
32494
  }
31039
32495
  }
31040
32496
  reset() {
@@ -31051,7 +32507,7 @@ var FlueObserveBridge = class {
31051
32507
  try {
31052
32508
  span = this.spanForExecutionOperation(operation, executionContext);
31053
32509
  } catch (error) {
31054
- logInstrumentationError3("Flue execution interceptor", error);
32510
+ logInstrumentationError4("Flue execution interceptor", error);
31055
32511
  }
31056
32512
  return span ? runWithCurrentSpanStore(span, next) : next();
31057
32513
  }
@@ -31257,7 +32713,7 @@ var FlueObserveBridge = class {
31257
32713
  this.runsById.delete(event.runId);
31258
32714
  }
31259
32715
  void flush().catch((error) => {
31260
- logInstrumentationError3("Flue flush", error);
32716
+ logInstrumentationError4("Flue flush", error);
31261
32717
  });
31262
32718
  }
31263
32719
  handleOperationStart(event) {
@@ -32032,17 +33488,17 @@ function safeLog3(span, event) {
32032
33488
  try {
32033
33489
  span.log(event);
32034
33490
  } catch (error) {
32035
- logInstrumentationError3("Flue span log", error);
33491
+ logInstrumentationError4("Flue span log", error);
32036
33492
  }
32037
33493
  }
32038
33494
  function safeEnd(span, endTime) {
32039
33495
  try {
32040
33496
  span.end(endTime === void 0 ? void 0 : { endTime });
32041
33497
  } catch (error) {
32042
- logInstrumentationError3("Flue span end", error);
33498
+ logInstrumentationError4("Flue span end", error);
32043
33499
  }
32044
33500
  }
32045
- function logInstrumentationError3(label, error) {
33501
+ function logInstrumentationError4(label, error) {
32046
33502
  debugLogger.debug(`Error in ${label} instrumentation:`, error);
32047
33503
  }
32048
33504
 
@@ -32610,10 +34066,10 @@ var LangSmithPlugin = class extends BasePlugin {
32610
34066
  const creates = ownValue(batch, "runCreates");
32611
34067
  if (Array.isArray(creates)) {
32612
34068
  const parentFirst = [...creates].sort((left, right) => {
32613
- const leftId = stringValue2(ownValue(left, "id"));
32614
- const rightId = stringValue2(ownValue(right, "id"));
32615
- const leftParent = stringValue2(ownValue(left, "parent_run_id"));
32616
- const rightParent = stringValue2(ownValue(right, "parent_run_id"));
34069
+ const leftId = stringValue3(ownValue(left, "id"));
34070
+ const rightId = stringValue3(ownValue(right, "id"));
34071
+ const leftParent = stringValue3(ownValue(left, "parent_run_id"));
34072
+ const rightParent = stringValue3(ownValue(right, "parent_run_id"));
32617
34073
  if (leftParent && leftParent === rightId) {
32618
34074
  return 1;
32619
34075
  }
@@ -32632,13 +34088,13 @@ var LangSmithPlugin = class extends BasePlugin {
32632
34088
  if (Array.isArray(updates)) {
32633
34089
  for (const run of updates) {
32634
34090
  this.containLifecycleFailure("batchIngestRuns update", () => {
32635
- this.processUpdate(stringValue2(ownValue(run, "id")) ?? "", run);
34091
+ this.processUpdate(stringValue3(ownValue(run, "id")) ?? "", run);
32636
34092
  });
32637
34093
  }
32638
34094
  }
32639
34095
  }
32640
34096
  processCreate(run) {
32641
- const id = stringValue2(ownValue(run, "id"));
34097
+ const id = stringValue3(ownValue(run, "id"));
32642
34098
  if (!id || this.completedRuns.get(id)) {
32643
34099
  return;
32644
34100
  }
@@ -32671,7 +34127,7 @@ var LangSmithPlugin = class extends BasePlugin {
32671
34127
  this.endIfComplete(id, activeRun, run);
32672
34128
  }
32673
34129
  processUpdate(explicitId, run) {
32674
- const id = stringValue2(explicitId) ?? stringValue2(ownValue(run, "id"));
34130
+ const id = stringValue3(explicitId) ?? stringValue3(ownValue(run, "id"));
32675
34131
  if (!id || this.completedRuns.get(id)) {
32676
34132
  return;
32677
34133
  }
@@ -32694,13 +34150,13 @@ var LangSmithPlugin = class extends BasePlugin {
32694
34150
  this.endIfComplete(id, active, active.run);
32695
34151
  }
32696
34152
  startRunSpan(id, run) {
32697
- const traceId = stringValue2(ownValue(run, "trace_id")) ?? id;
32698
- const parentId = stringValue2(ownValue(run, "parent_run_id")) ?? stringValue2(ownValue(ownValue(run, "parent_run"), "id"));
34153
+ const traceId = stringValue3(ownValue(run, "trace_id")) ?? id;
34154
+ const parentId = stringValue3(ownValue(run, "parent_run_id")) ?? stringValue3(ownValue(ownValue(run, "parent_run"), "id"));
32699
34155
  const startTime = timestampSeconds(ownValue(run, "start_time"));
32700
34156
  return startSpan(
32701
34157
  withSpanInstrumentationName(
32702
34158
  {
32703
- name: stringValue2(ownValue(run, "name")) ?? "LangSmith run",
34159
+ name: stringValue3(ownValue(run, "name")) ?? "LangSmith run",
32704
34160
  spanId: id,
32705
34161
  parentSpanIds: {
32706
34162
  parentSpanIds: parentId ? [parentId] : [],
@@ -32792,7 +34248,7 @@ function mergeRuns(previous, current) {
32792
34248
  function isRecord2(value) {
32793
34249
  return typeof value === "object" && value !== null && !Array.isArray(value);
32794
34250
  }
32795
- function stringValue2(value) {
34251
+ function stringValue3(value) {
32796
34252
  return typeof value === "string" && value.length > 0 ? value : void 0;
32797
34253
  }
32798
34254
  function timestampSeconds(value) {
@@ -32810,7 +34266,7 @@ function timestampSeconds(value) {
32810
34266
  return void 0;
32811
34267
  }
32812
34268
  function dottedOrderDepth(run) {
32813
- const dottedOrder = stringValue2(ownValue(run, "dotted_order"));
34269
+ const dottedOrder = stringValue3(ownValue(run, "dotted_order"));
32814
34270
  return dottedOrder ? dottedOrder.split(".").length : Number.MAX_SAFE_INTEGER;
32815
34271
  }
32816
34272
  function mapRunType(runType) {
@@ -33015,7 +34471,7 @@ var PiCodingAgentPlugin = class extends BasePlugin {
33015
34471
  }
33016
34472
  );
33017
34473
  } catch (error) {
33018
- logInstrumentationError4("Pi Coding Agent prompt start", error);
34474
+ logInstrumentationError5("Pi Coding Agent prompt start", error);
33019
34475
  }
33020
34476
  if (!state) {
33021
34477
  return runWithAutoInstrumentationSuppressed(invokeTarget);
@@ -33148,12 +34604,12 @@ function installPiAgentInstrumentation(agent) {
33148
34604
  () => handlePiAgentEvent(state, event)
33149
34605
  );
33150
34606
  } catch (error) {
33151
- logInstrumentationError4("Pi Coding Agent event", error);
34607
+ logInstrumentationError5("Pi Coding Agent event", error);
33152
34608
  }
33153
34609
  });
33154
34610
  piAgentEventSubscriptions.add(agent);
33155
34611
  } catch (error) {
33156
- logInstrumentationError4("Pi Coding Agent event subscription", error);
34612
+ logInstrumentationError5("Pi Coding Agent event subscription", error);
33157
34613
  }
33158
34614
  }
33159
34615
  function makeInstrumentedStreamFunction(agent, originalStreamFunction, property) {
@@ -33203,7 +34659,7 @@ function wrapPiToolExecutors(tools) {
33203
34659
  });
33204
34660
  tool.execute = wrappedExecute;
33205
34661
  } catch (error) {
33206
- logInstrumentationError4("Pi Coding Agent tool wrapping", error);
34662
+ logInstrumentationError5("Pi Coding Agent tool wrapping", error);
33207
34663
  }
33208
34664
  }
33209
34665
  }
@@ -33282,7 +34738,7 @@ function patchAssistantMessageStream(stream, promptState, llmState) {
33282
34738
  try {
33283
34739
  await iterator.return();
33284
34740
  } catch (cleanupError) {
33285
- logInstrumentationError4(
34741
+ logInstrumentationError5(
33286
34742
  "Pi Coding Agent stream cleanup",
33287
34743
  cleanupError
33288
34744
  );
@@ -33447,7 +34903,7 @@ function finishPiPromptRun(state, error) {
33447
34903
  try {
33448
34904
  state.span.end();
33449
34905
  } catch (endError) {
33450
- logInstrumentationError4("Pi Coding Agent prompt end", endError);
34906
+ logInstrumentationError5("Pi Coding Agent prompt end", endError);
33451
34907
  }
33452
34908
  }
33453
34909
  }
@@ -33779,10 +35235,10 @@ function safeLog4(span, event) {
33779
35235
  try {
33780
35236
  span.log(event);
33781
35237
  } catch (error) {
33782
- logInstrumentationError4("Pi Coding Agent span log", error);
35238
+ logInstrumentationError5("Pi Coding Agent span log", error);
33783
35239
  }
33784
35240
  }
33785
- function logInstrumentationError4(context, error) {
35241
+ function logInstrumentationError5(context, error) {
33786
35242
  debugLogger.debug(`${context}:`, error);
33787
35243
  }
33788
35244
 
@@ -34020,7 +35476,7 @@ function handleAgentStreamEvent(state, event) {
34020
35476
  finalizeModelSpan(state, event);
34021
35477
  break;
34022
35478
  case "beforeToolCallEvent":
34023
- startToolSpan2(state, event);
35479
+ startToolSpan3(state, event);
34024
35480
  break;
34025
35481
  case "afterToolCallEvent":
34026
35482
  finalizeToolSpan(state, event);
@@ -34045,7 +35501,7 @@ function handleAgentStreamEvent(state, event) {
34045
35501
  break;
34046
35502
  }
34047
35503
  } catch (error) {
34048
- logInstrumentationError5("Strands Agent SDK event", error);
35504
+ logInstrumentationError6("Strands Agent SDK event", error);
34049
35505
  }
34050
35506
  }
34051
35507
  function handleMultiAgentStreamEvent(state, event, activeChildParents) {
@@ -34081,7 +35537,7 @@ function handleMultiAgentStreamEvent(state, event, activeChildParents) {
34081
35537
  break;
34082
35538
  }
34083
35539
  } catch (error) {
34084
- logInstrumentationError5("Strands Agent SDK multi-agent event", error);
35540
+ logInstrumentationError6("Strands Agent SDK multi-agent event", error);
34085
35541
  }
34086
35542
  }
34087
35543
  function buildModelSpanInput(event, attachmentCache) {
@@ -34160,7 +35616,7 @@ function finalizeModelSpan(state, event) {
34160
35616
  });
34161
35617
  modelState.span.end();
34162
35618
  }
34163
- function startToolSpan2(state, event) {
35619
+ function startToolSpan3(state, event) {
34164
35620
  const toolUse = event.toolUse;
34165
35621
  const key = toolKey2(toolUse);
34166
35622
  if (state.activeTools.has(key)) {
@@ -34440,7 +35896,7 @@ function getModelConfig(model) {
34440
35896
  try {
34441
35897
  return model.getConfig();
34442
35898
  } catch (error) {
34443
- logInstrumentationError5("Strands Agent SDK model config", error);
35899
+ logInstrumentationError6("Strands Agent SDK model config", error);
34444
35900
  return void 0;
34445
35901
  }
34446
35902
  }
@@ -34523,7 +35979,7 @@ function processStrandsInputAttachments(input, cache = createStrandsAttachmentCa
34523
35979
  try {
34524
35980
  return processStrandsInputNode(input, cache);
34525
35981
  } catch (error) {
34526
- logInstrumentationError5("Strands Agent SDK input attachments", error);
35982
+ logInstrumentationError6("Strands Agent SDK input attachments", error);
34527
35983
  return input;
34528
35984
  }
34529
35985
  }
@@ -34743,13 +36199,484 @@ function safeLog5(span, event) {
34743
36199
  try {
34744
36200
  span.log(event);
34745
36201
  } catch (error) {
34746
- logInstrumentationError5("Strands Agent SDK span log", error);
36202
+ logInstrumentationError6("Strands Agent SDK span log", error);
34747
36203
  }
34748
36204
  }
34749
- function logInstrumentationError5(context, error) {
36205
+ function logInstrumentationError6(context, error) {
34750
36206
  debugLogger.debug(`${context}:`, error);
34751
36207
  }
34752
36208
 
36209
+ // src/instrumentation/plugins/elevenlabs-channels.ts
36210
+ var elevenLabsChannels = defineChannels(
36211
+ "@elevenlabs/elevenlabs-js",
36212
+ {
36213
+ convert: channel({
36214
+ channelName: "textToSpeech.convert",
36215
+ kind: "async"
36216
+ }),
36217
+ stream: channel({
36218
+ channelName: "textToSpeech.stream",
36219
+ kind: "async"
36220
+ }),
36221
+ convertWithTimestamps: channel({ channelName: "textToSpeech.convertWithTimestamps", kind: "async" }),
36222
+ streamWithTimestamps: channel({ channelName: "textToSpeech.streamWithTimestamps", kind: "async" }),
36223
+ transcribe: channel({ channelName: "speechToText.convert", kind: "async" })
36224
+ },
36225
+ { instrumentationName: INSTRUMENTATION_NAMES.ELEVENLABS }
36226
+ );
36227
+
36228
+ // src/instrumentation/plugins/elevenlabs-plugin.ts
36229
+ var ElevenLabsPlugin = class extends BasePlugin {
36230
+ onEnable() {
36231
+ for (const method of [
36232
+ "convert",
36233
+ "stream",
36234
+ "convertWithTimestamps",
36235
+ "streamWithTimestamps"
36236
+ ]) {
36237
+ this.unsubscribers.push(
36238
+ interceptCall2(
36239
+ elevenLabsChannels[method],
36240
+ `elevenlabs.textToSpeech.${method}`,
36241
+ ([voice, request]) => ({
36242
+ input: {
36243
+ operation: "speech",
36244
+ prompt: request.text,
36245
+ parameters: {
36246
+ voice,
36247
+ format: request.outputFormat,
36248
+ language: request.languageCode,
36249
+ speed: request.voiceSettings?.speed
36250
+ }
36251
+ },
36252
+ metadata: {
36253
+ provider: "elevenlabs",
36254
+ model: request.modelId ?? "eleven_multilingual_v2"
36255
+ }
36256
+ }),
36257
+ (value, args, span, finish, headers, started) => captureSpeech(
36258
+ value,
36259
+ args[1],
36260
+ method,
36261
+ span,
36262
+ finish,
36263
+ started,
36264
+ headers
36265
+ )
36266
+ )
36267
+ );
36268
+ }
36269
+ this.unsubscribers.push(
36270
+ interceptCall2(
36271
+ elevenLabsChannels.transcribe,
36272
+ "elevenlabs.speechToText.convert",
36273
+ ([request]) => {
36274
+ if (request.webhook) return void 0;
36275
+ const file = request.file;
36276
+ const filename = typeof File !== "undefined" && file instanceof File ? file.name : "audio";
36277
+ const contentType = file instanceof Blob ? file.type || "application/octet-stream" : "application/octet-stream";
36278
+ const blob = file instanceof Blob ? file : file instanceof Uint8Array ? new Blob([new Uint8Array(file)], { type: contentType }) : file instanceof ArrayBuffer ? new Blob([file.slice(0)], { type: contentType }) : void 0;
36279
+ const fileData = blob ? new Attachment({ data: blob, filename, contentType }) : request.cloudStorageUrl;
36280
+ return {
36281
+ input: {
36282
+ operation: "transcribe",
36283
+ content: fileData ? [{ type: "file", file: { filename, file_data: fileData } }] : [],
36284
+ parameters: {
36285
+ language: request.languageCode,
36286
+ timestamp_granularities: request.timestampsGranularity
36287
+ }
36288
+ },
36289
+ metadata: { provider: "elevenlabs", model: request.modelId }
36290
+ };
36291
+ },
36292
+ (value, _args, span, finish) => {
36293
+ const result = value;
36294
+ const transcripts = result.transcripts ?? [result];
36295
+ span.log({
36296
+ output: {
36297
+ content: transcripts.flatMap(
36298
+ (transcript) => typeof transcript.text === "string" ? [{ type: "text", text: transcript.text }] : []
36299
+ ),
36300
+ annotations: {
36301
+ language: result.languageCode,
36302
+ words: result.words ?? (result.transcripts ? result.transcripts.flatMap(
36303
+ (transcript) => transcript.words ?? []
36304
+ ) : void 0)
36305
+ }
36306
+ }
36307
+ });
36308
+ finish();
36309
+ },
36310
+ ([request], span) => {
36311
+ const file = request.file;
36312
+ if (!isAsyncIterable(file)) return;
36313
+ const chunks = [];
36314
+ const filename = isObject(file) && typeof file.path === "string" ? file.path.split(/[\\/]/).pop() || "audio" : "audio";
36315
+ observeAudioStream(
36316
+ file,
36317
+ (chunk) => chunks.push(new Uint8Array(chunk)),
36318
+ () => {
36319
+ const contentType = "application/octet-stream";
36320
+ const data = new Blob(chunks, {
36321
+ type: contentType
36322
+ });
36323
+ chunks.length = 0;
36324
+ span.log({
36325
+ input: {
36326
+ content: [
36327
+ {
36328
+ type: "file",
36329
+ file: {
36330
+ filename,
36331
+ file_data: new Attachment({
36332
+ data,
36333
+ filename,
36334
+ contentType
36335
+ })
36336
+ }
36337
+ }
36338
+ ]
36339
+ }
36340
+ });
36341
+ },
36342
+ () => {
36343
+ chunks.length = 0;
36344
+ },
36345
+ span
36346
+ );
36347
+ }
36348
+ )
36349
+ );
36350
+ }
36351
+ onDisable() {
36352
+ this.unsubscribers = unsubscribeAll(this.unsubscribers);
36353
+ }
36354
+ };
36355
+ function interceptCall2(channel2, name, input, output, beforeInvoke) {
36356
+ return channel2.intercept((target, self, args) => {
36357
+ const invoke = () => Reflect.apply(target, self, args);
36358
+ if (isAutoInstrumentationSuppressed()) return invoke();
36359
+ const started = Date.now() / 1e3;
36360
+ let span;
36361
+ try {
36362
+ const event = input(args);
36363
+ if (event !== void 0)
36364
+ span = startSpan(
36365
+ withSpanInstrumentationName(
36366
+ {
36367
+ name,
36368
+ spanAttributes: { type: "llm" /* LLM */ },
36369
+ event
36370
+ },
36371
+ INSTRUMENTATION_NAMES.ELEVENLABS
36372
+ )
36373
+ );
36374
+ } catch (error) {
36375
+ debugLogger.error("Error starting ElevenLabs span", error);
36376
+ return invoke();
36377
+ }
36378
+ if (!span) return invoke();
36379
+ const activeSpan = span;
36380
+ let ended = false;
36381
+ const finish = (error) => {
36382
+ if (ended) return;
36383
+ ended = true;
36384
+ try {
36385
+ if (error !== void 0) activeSpan.log({ error });
36386
+ activeSpan.end();
36387
+ } catch (loggingError) {
36388
+ debugLogger.error("Error ending ElevenLabs span", loggingError);
36389
+ }
36390
+ };
36391
+ try {
36392
+ beforeInvoke?.(args, span);
36393
+ } catch (error) {
36394
+ debugLogger.error("Error observing ElevenLabs input", error);
36395
+ }
36396
+ let result;
36397
+ try {
36398
+ result = withCurrent(
36399
+ span,
36400
+ () => runWithAutoInstrumentationSuppressed(invoke)
36401
+ );
36402
+ } catch (error) {
36403
+ finish(error);
36404
+ throw error;
36405
+ }
36406
+ const capture = (value, headers) => {
36407
+ try {
36408
+ output(value, args, span, finish, headers, started);
36409
+ } catch (error) {
36410
+ debugLogger.error("Error capturing ElevenLabs output", error);
36411
+ finish();
36412
+ }
36413
+ };
36414
+ try {
36415
+ if (isObject(result) && typeof result.withRawResponse === "function") {
36416
+ void result.withRawResponse().then(
36417
+ ({
36418
+ data,
36419
+ rawResponse
36420
+ }) => capture(data, rawResponse?.headers),
36421
+ finish
36422
+ );
36423
+ } else {
36424
+ void Promise.resolve(result).then((value) => capture(value), finish);
36425
+ }
36426
+ } catch (error) {
36427
+ debugLogger.error("Error observing ElevenLabs result", error);
36428
+ finish();
36429
+ }
36430
+ return result;
36431
+ });
36432
+ }
36433
+ function captureSpeech(value, request, method, span, finish, started, headers) {
36434
+ const format = request.outputFormat ?? "mp3_44100_128";
36435
+ const formatType = format.startsWith("mp3_") ? "audio/mpeg" : format.startsWith("pcm_") ? "audio/pcm" : format.startsWith("opus_") ? "audio/ogg" : format.startsWith("ulaw_") ? "audio/basic" : format.startsWith("alaw_") ? "audio/x-alaw" : void 0;
36436
+ const headerType = headers?.get("content-type")?.split(";")[0];
36437
+ const contentType = headerType?.startsWith("audio/") ? headerType : formatType;
36438
+ const disposition = headers?.get("content-disposition");
36439
+ const headerFilename = disposition?.match(
36440
+ /filename="([^"]+)"|filename=([^;]+)/i
36441
+ );
36442
+ const filename = headerFilename?.[1] ?? headerFilename?.[2]?.trim() ?? `speech.${contentType ? getExtensionFromMediaType(contentType) : "bin"}`;
36443
+ const chunks = [];
36444
+ const alignments = [];
36445
+ let bytes = 0;
36446
+ let first = true;
36447
+ let stopped = false;
36448
+ const observe = (chunk) => {
36449
+ if (stopped || chunk.byteLength === 0) return;
36450
+ if (first && method.startsWith("stream")) {
36451
+ span.log({
36452
+ metrics: { time_to_first_token: Date.now() / 1e3 - started }
36453
+ });
36454
+ }
36455
+ first = false;
36456
+ chunks.push(new Uint8Array(chunk));
36457
+ bytes += chunk.byteLength;
36458
+ };
36459
+ const complete = () => {
36460
+ if (stopped) return;
36461
+ stopped = true;
36462
+ try {
36463
+ const content = [];
36464
+ if (contentType && bytes) {
36465
+ const data = new Uint8Array(bytes);
36466
+ let offset = 0;
36467
+ for (const chunk of chunks) {
36468
+ data.set(chunk, offset);
36469
+ offset += chunk.length;
36470
+ }
36471
+ content.push({
36472
+ type: "file",
36473
+ file: {
36474
+ filename,
36475
+ byte_size: bytes,
36476
+ file_data: new Attachment({
36477
+ data: new Blob([data], { type: contentType }),
36478
+ filename,
36479
+ contentType
36480
+ })
36481
+ }
36482
+ });
36483
+ }
36484
+ span.log({
36485
+ output: {
36486
+ content,
36487
+ ...alignments.length ? { annotations: alignments } : {}
36488
+ }
36489
+ });
36490
+ } finally {
36491
+ chunks.length = 0;
36492
+ finish();
36493
+ }
36494
+ };
36495
+ const cancel = (error) => {
36496
+ stopped = true;
36497
+ chunks.length = 0;
36498
+ finish(error);
36499
+ };
36500
+ const timestampChunk = (chunk) => {
36501
+ const binary = atob(chunk.audioBase64);
36502
+ observe(Uint8Array.from(binary, (character) => character.charCodeAt(0)));
36503
+ if (chunk.alignment || chunk.normalizedAlignment)
36504
+ alignments.push({
36505
+ alignment: chunk.alignment,
36506
+ normalized_alignment: chunk.normalizedAlignment
36507
+ });
36508
+ };
36509
+ if (method === "convertWithTimestamps") {
36510
+ timestampChunk(value);
36511
+ complete();
36512
+ } else if (method === "streamWithTimestamps") {
36513
+ patchStreamIfNeeded(value, {
36514
+ shouldCollect: (chunk) => {
36515
+ try {
36516
+ timestampChunk(chunk);
36517
+ } catch (error) {
36518
+ debugLogger.error("Error collecting ElevenLabs timestamps", error);
36519
+ cancel();
36520
+ }
36521
+ return false;
36522
+ },
36523
+ onComplete: complete,
36524
+ onCancel: () => cancel(),
36525
+ onError: cancel,
36526
+ aroundNext: (next) => withCurrent(span, next)
36527
+ });
36528
+ } else {
36529
+ observeAudioStream(value, observe, complete, cancel, span);
36530
+ }
36531
+ }
36532
+ function observeAudioStream(value, observe, complete, cancel, span) {
36533
+ let ended = false;
36534
+ const safeObserve = (chunk) => {
36535
+ if (ended) return;
36536
+ try {
36537
+ observe(chunk);
36538
+ } catch (error) {
36539
+ debugLogger.error("Error collecting ElevenLabs audio", error);
36540
+ end(false);
36541
+ }
36542
+ };
36543
+ const end = (success, error) => {
36544
+ if (ended) return;
36545
+ ended = true;
36546
+ try {
36547
+ if (success) complete();
36548
+ else cancel(error);
36549
+ } catch (loggingError) {
36550
+ debugLogger.error("Error logging ElevenLabs audio", loggingError);
36551
+ cancel();
36552
+ }
36553
+ };
36554
+ if (!isObject(value) || !Object.isExtensible(value)) {
36555
+ end(false);
36556
+ return;
36557
+ }
36558
+ if (typeof value.read === "function" && typeof value.on === "function") {
36559
+ value.on("end", () => end(true));
36560
+ value.on("close", () => end(false));
36561
+ const emit2 = value.emit;
36562
+ if (typeof emit2 === "function")
36563
+ value.emit = function(event, ...args) {
36564
+ if (event === "data" && args[0] instanceof Uint8Array)
36565
+ safeObserve(args[0]);
36566
+ if (event === "error") end(false, args[0]);
36567
+ return Reflect.apply(emit2, this, [event, ...args]);
36568
+ };
36569
+ return;
36570
+ }
36571
+ if (typeof value.getReader === "function") {
36572
+ const webStream = value;
36573
+ const pipeTo = webStream.pipeTo;
36574
+ const pipeThrough = webStream.pipeThrough;
36575
+ webStream.pipeTo = function(destination, options) {
36576
+ if (!isObject(destination) || this.locked || destination.locked)
36577
+ return pipeTo.call(this, destination, options);
36578
+ const tap = new TransformStream({
36579
+ transform(chunk, controller) {
36580
+ safeObserve(chunk);
36581
+ controller.enqueue(chunk);
36582
+ },
36583
+ flush() {
36584
+ end(true);
36585
+ }
36586
+ });
36587
+ const observed = pipeThrough.call(
36588
+ this,
36589
+ tap,
36590
+ options
36591
+ );
36592
+ return observed.pipeTo(destination, options).catch((error) => {
36593
+ end(false, error);
36594
+ throw error;
36595
+ });
36596
+ };
36597
+ webStream.pipeThrough = function(transform, options) {
36598
+ if (this.locked || transform.writable.locked || transform.readable.locked)
36599
+ return pipeThrough.call(this, transform, options);
36600
+ const result = webStream.pipeTo.call(this, transform.writable, options);
36601
+ void result.catch(() => {
36602
+ });
36603
+ return transform.readable;
36604
+ };
36605
+ const getReader = value.getReader;
36606
+ value.getReader = function(...args) {
36607
+ const reader = Reflect.apply(getReader, this, args);
36608
+ const read3 = reader.read;
36609
+ reader.read = function(...readArgs) {
36610
+ return Promise.resolve(
36611
+ withCurrent(span, () => Reflect.apply(read3, this, readArgs))
36612
+ ).then(
36613
+ (result) => {
36614
+ if (result.value) safeObserve(result.value);
36615
+ if (result.done) end(true);
36616
+ return result;
36617
+ },
36618
+ (error) => {
36619
+ end(false, error);
36620
+ throw error;
36621
+ }
36622
+ );
36623
+ };
36624
+ const readerCancel = reader.cancel;
36625
+ reader.cancel = function(...cancelArgs) {
36626
+ const result = Reflect.apply(readerCancel, this, cancelArgs);
36627
+ end(false);
36628
+ return result;
36629
+ };
36630
+ return reader;
36631
+ };
36632
+ const streamCancel = value.cancel;
36633
+ if (typeof streamCancel === "function")
36634
+ value.cancel = function(...args) {
36635
+ const result = Reflect.apply(streamCancel, this, args);
36636
+ void Promise.resolve(result).then(
36637
+ () => end(false),
36638
+ () => {
36639
+ }
36640
+ );
36641
+ return result;
36642
+ };
36643
+ }
36644
+ if (typeof value.getReader === "function" && typeof value.values === "function") {
36645
+ const values = value.values;
36646
+ const iterate = function(...args) {
36647
+ const iterator = Reflect.apply(values, this, args);
36648
+ patchStreamIfNeeded(iterator, {
36649
+ shouldCollect(chunk) {
36650
+ safeObserve(chunk);
36651
+ return false;
36652
+ },
36653
+ onComplete: () => end(true),
36654
+ onCancel: () => end(false),
36655
+ onError: (error) => end(false, error),
36656
+ aroundNext: (next) => withCurrent(span, next)
36657
+ });
36658
+ return iterator;
36659
+ };
36660
+ value.values = iterate;
36661
+ Object.defineProperty(value, Symbol.asyncIterator, {
36662
+ configurable: true,
36663
+ writable: true,
36664
+ value: iterate
36665
+ });
36666
+ } else if (isAsyncIterable(value)) {
36667
+ patchStreamIfNeeded(value, {
36668
+ shouldCollect: (chunk) => {
36669
+ safeObserve(chunk);
36670
+ return false;
36671
+ },
36672
+ onComplete: () => end(true),
36673
+ onCancel: () => end(false),
36674
+ onError: (error) => end(false, error),
36675
+ aroundNext: (next) => withCurrent(span, next)
36676
+ });
36677
+ } else if (typeof value.getReader !== "function") end(false);
36678
+ }
36679
+
34753
36680
  // src/instrumentation/plugins/voyageai-channels.ts
34754
36681
  var voyageAIChannels = defineChannels(
34755
36682
  "voyageai",
@@ -34817,7 +36744,7 @@ var VoyageAIPlugin = class extends BasePlugin {
34817
36744
  this.unsubscribers = unsubscribeAll(this.unsubscribers);
34818
36745
  }
34819
36746
  };
34820
- function interceptVoyageAICall(channel2, name, extractInput2, extractOutput2, extractMetrics2 = extractUsageMetrics3) {
36747
+ function interceptVoyageAICall(channel2, name, extractInput3, extractOutput2, extractMetrics2 = extractUsageMetrics3) {
34821
36748
  return channel2.intercept((target, thisArg, args) => {
34822
36749
  const invokeTarget = () => Reflect.apply(target, thisArg, args);
34823
36750
  if (isAutoInstrumentationSuppressed()) {
@@ -34825,7 +36752,7 @@ function interceptVoyageAICall(channel2, name, extractInput2, extractOutput2, ex
34825
36752
  }
34826
36753
  let span;
34827
36754
  try {
34828
- const { input, metadata } = extractInput2(args);
36755
+ const { input, metadata } = extractInput3(args);
34829
36756
  span = startSpan(
34830
36757
  withSpanInstrumentationName(
34831
36758
  {
@@ -35175,14 +37102,14 @@ var CloudflareAIChatPlugin = class extends BasePlugin {
35175
37102
  const result = event.arguments[0];
35176
37103
  state = agent ? this.findResponseState(
35177
37104
  agent,
35178
- stringValue3(ownValue2(result, "requestId"))
37105
+ stringValue4(ownValue2(result, "requestId"))
35179
37106
  ) : void 0;
35180
37107
  if (!state) {
35181
37108
  return;
35182
37109
  }
35183
37110
  state.responseObserved = true;
35184
37111
  const output = serializeMessage(ownValue2(result, "message"));
35185
- const status = stringValue3(ownValue2(result, "status"));
37112
+ const status = stringValue4(ownValue2(result, "status"));
35186
37113
  const error = ownValue2(result, "error");
35187
37114
  const input = ownValue2(result, "continuation") === true ? state.input : serializeMessages(readProperty(agent, "messages"))?.filter(
35188
37115
  (message) => typeof output?.id !== "string" || message.id !== output.id
@@ -35229,7 +37156,7 @@ var CloudflareAIChatPlugin = class extends BasePlugin {
35229
37156
  }
35230
37157
  try {
35231
37158
  const agent = asObject(event.self);
35232
- const requestId = stringValue3(event.arguments[0]);
37159
+ const requestId = stringValue4(event.arguments[0]);
35233
37160
  const key = requestId ?? /* @__PURE__ */ Symbol("cloudflare-ai-chat-turn");
35234
37161
  const activeForAgent = agent ? this.getActiveTurns(agent) : void 0;
35235
37162
  const existing = activeForAgent?.get(key);
@@ -35398,7 +37325,7 @@ function ownValue2(value, key) {
35398
37325
  const descriptor = Object.getOwnPropertyDescriptor(object, key);
35399
37326
  return descriptor && "value" in descriptor ? descriptor.value : void 0;
35400
37327
  }
35401
- function stringValue3(value) {
37328
+ function stringValue4(value) {
35402
37329
  return typeof value === "string" ? value : void 0;
35403
37330
  }
35404
37331
  function serializeMessages(value) {
@@ -35516,7 +37443,7 @@ var CloudflareAgentsPlugin = class extends BasePlugin {
35516
37443
  );
35517
37444
  spans.set(event, span);
35518
37445
  } catch (error) {
35519
- logInstrumentationError6("start", error);
37446
+ logInstrumentationError7("start", error);
35520
37447
  }
35521
37448
  },
35522
37449
  asyncEnd: (event) => {
@@ -35536,7 +37463,7 @@ var CloudflareAgentsPlugin = class extends BasePlugin {
35536
37463
  }
35537
37464
  }
35538
37465
  } catch (error) {
35539
- logInstrumentationError6("completion", error);
37466
+ logInstrumentationError7("completion", error);
35540
37467
  } finally {
35541
37468
  safelyEndSpan(span);
35542
37469
  }
@@ -35550,7 +37477,7 @@ var CloudflareAgentsPlugin = class extends BasePlugin {
35550
37477
  try {
35551
37478
  span.log({ error: event.error });
35552
37479
  } catch (error) {
35553
- logInstrumentationError6("rejection", error);
37480
+ logInstrumentationError7("rejection", error);
35554
37481
  } finally {
35555
37482
  safelyEndSpan(span);
35556
37483
  }
@@ -35580,10 +37507,10 @@ function safelyEndSpan(span) {
35580
37507
  try {
35581
37508
  span.end();
35582
37509
  } catch (error) {
35583
- logInstrumentationError6("span end", error);
37510
+ logInstrumentationError7("span end", error);
35584
37511
  }
35585
37512
  }
35586
- function logInstrumentationError6(operation, error) {
37513
+ function logInstrumentationError7(operation, error) {
35587
37514
  debugLogger.error(
35588
37515
  `Failed to process Cloudflare Agents ${operation} instrumentation:`,
35589
37516
  error
@@ -35601,12 +37528,14 @@ var BraintrustPlugin = class extends BasePlugin {
35601
37528
  cloudflareThinkPlugin = null;
35602
37529
  cursorSDKPlugin = null;
35603
37530
  openAIAgentsPlugin = null;
37531
+ googleGenerativeAIPlugin = null;
35604
37532
  googleGenAIPlugin = null;
35605
37533
  huggingFacePlugin = null;
35606
37534
  huggingFaceTransformersPlugin = null;
35607
37535
  openRouterPlugin = null;
35608
37536
  openRouterAgentPlugin = null;
35609
37537
  mistralPlugin = null;
37538
+ langGraphSDKPlugin = null;
35610
37539
  ollamaPlugin = null;
35611
37540
  googleADKPlugin = null;
35612
37541
  coherePlugin = null;
@@ -35619,6 +37548,7 @@ var BraintrustPlugin = class extends BasePlugin {
35619
37548
  langSmithPlugin = null;
35620
37549
  piCodingAgentPlugin = null;
35621
37550
  strandsAgentSDKPlugin = null;
37551
+ elevenLabsPlugin = null;
35622
37552
  voyageAIPlugin = null;
35623
37553
  cloudflareAIChatPlugin = null;
35624
37554
  cloudflareAgentsPlugin = null;
@@ -35660,6 +37590,10 @@ var BraintrustPlugin = class extends BasePlugin {
35660
37590
  this.openAIAgentsPlugin = new OpenAIAgentsPlugin();
35661
37591
  this.openAIAgentsPlugin.enable();
35662
37592
  }
37593
+ if (integrations.googleGenerativeAI !== false) {
37594
+ this.googleGenerativeAIPlugin = new GoogleGenerativeAIPlugin();
37595
+ this.googleGenerativeAIPlugin.enable();
37596
+ }
35663
37597
  if (integrations.googleGenAI !== false && integrations.google !== false) {
35664
37598
  this.googleGenAIPlugin = new GoogleGenAIPlugin();
35665
37599
  this.googleGenAIPlugin.enable();
@@ -35682,6 +37616,10 @@ var BraintrustPlugin = class extends BasePlugin {
35682
37616
  this.mistralPlugin = new MistralPlugin();
35683
37617
  this.mistralPlugin.enable();
35684
37618
  }
37619
+ if (integrations.langgraphSDK !== false) {
37620
+ this.langGraphSDKPlugin = new LangGraphSDKPlugin();
37621
+ this.langGraphSDKPlugin.enable();
37622
+ }
35685
37623
  if (integrations.ollama !== false) {
35686
37624
  this.ollamaPlugin = new OllamaPlugin();
35687
37625
  this.ollamaPlugin.enable();
@@ -35694,6 +37632,10 @@ var BraintrustPlugin = class extends BasePlugin {
35694
37632
  this.coherePlugin = new CoherePlugin();
35695
37633
  this.coherePlugin.enable();
35696
37634
  }
37635
+ if (integrations.elevenlabs !== false) {
37636
+ this.elevenLabsPlugin = new ElevenLabsPlugin();
37637
+ this.elevenLabsPlugin.enable();
37638
+ }
35697
37639
  if (integrations.voyageai !== false) {
35698
37640
  this.voyageAIPlugin = new VoyageAIPlugin();
35699
37641
  this.voyageAIPlugin.enable();
@@ -35778,6 +37720,10 @@ var BraintrustPlugin = class extends BasePlugin {
35778
37720
  this.openAIAgentsPlugin.disable();
35779
37721
  this.openAIAgentsPlugin = null;
35780
37722
  }
37723
+ if (this.googleGenerativeAIPlugin) {
37724
+ this.googleGenerativeAIPlugin.disable();
37725
+ this.googleGenerativeAIPlugin = null;
37726
+ }
35781
37727
  if (this.googleGenAIPlugin) {
35782
37728
  this.googleGenAIPlugin.disable();
35783
37729
  this.googleGenAIPlugin = null;
@@ -35802,6 +37748,10 @@ var BraintrustPlugin = class extends BasePlugin {
35802
37748
  this.mistralPlugin.disable();
35803
37749
  this.mistralPlugin = null;
35804
37750
  }
37751
+ if (this.langGraphSDKPlugin) {
37752
+ this.langGraphSDKPlugin.disable();
37753
+ this.langGraphSDKPlugin = null;
37754
+ }
35805
37755
  if (this.ollamaPlugin) {
35806
37756
  this.ollamaPlugin.disable();
35807
37757
  this.ollamaPlugin = null;
@@ -35814,6 +37764,10 @@ var BraintrustPlugin = class extends BasePlugin {
35814
37764
  this.coherePlugin.disable();
35815
37765
  this.coherePlugin = null;
35816
37766
  }
37767
+ if (this.elevenLabsPlugin) {
37768
+ this.elevenLabsPlugin.disable();
37769
+ this.elevenLabsPlugin = null;
37770
+ }
35817
37771
  if (this.voyageAIPlugin) {
35818
37772
  this.voyageAIPlugin.disable();
35819
37773
  this.voyageAIPlugin = null;
@@ -35872,7 +37826,31 @@ var MAX_STORED_LLM_INPUTS = 100;
35872
37826
  var MAX_STORED_REASONING_BLOCKS = 100;
35873
37827
  var MAX_STORED_SPAN_REFERENCES = 1e4;
35874
37828
  var MAX_STORED_STEP_STARTS = 1e4;
37829
+ var EVE_HANDLED_EVENT_TYPES = /* @__PURE__ */ new Set([
37830
+ "action.result",
37831
+ "actions.requested",
37832
+ "message.completed",
37833
+ "message.received",
37834
+ "reasoning.completed",
37835
+ "result.completed",
37836
+ "session.completed",
37837
+ "session.failed",
37838
+ "session.started",
37839
+ "step.completed",
37840
+ "step.failed",
37841
+ "step.started",
37842
+ "subagent.called",
37843
+ "subagent.completed",
37844
+ "turn.completed",
37845
+ "turn.failed",
37846
+ "turn.started"
37847
+ ]);
35875
37848
  function braintrustEveHook(options) {
37849
+ if (!options || typeof options.defineState !== "function") {
37850
+ throw new TypeError(
37851
+ "braintrustEveHook requires Eve's defineState function"
37852
+ );
37853
+ }
35876
37854
  const state = options.defineState(EVE_TRACE_STATE_KEY, emptyEveTraceState);
35877
37855
  const bridge = new EveBridge(state);
35878
37856
  return {
@@ -35884,15 +37862,27 @@ function braintrustEveHook(options) {
35884
37862
  };
35885
37863
  }
35886
37864
  function createLegacyEveInstrumentation(options) {
37865
+ if (!options || typeof options.defineState !== "function") {
37866
+ throw new TypeError(
37867
+ "braintrustEveInstrumentation requires Eve's defineState function"
37868
+ );
37869
+ }
35887
37870
  const state = options.defineState(EVE_TRACE_STATE_KEY, emptyEveTraceState);
35888
37871
  return {
35889
37872
  events: {
35890
37873
  "step.started": (input) => {
35891
37874
  try {
37875
+ if (!isEveInstrumentationStepStartedEventInput(input)) {
37876
+ debugLogger.warn(
37877
+ "Ignoring malformed Eve instrumentation step.started event"
37878
+ );
37879
+ return void 0;
37880
+ }
35892
37881
  captureEveModelInput(state, input);
35893
37882
  } catch (error) {
35894
37883
  debugLogger.warn("Error in Eve LLM input capture:", error);
35895
37884
  }
37885
+ return void 0;
35896
37886
  }
35897
37887
  },
35898
37888
  recordInputs: false,
@@ -35901,7 +37891,77 @@ function createLegacyEveInstrumentation(options) {
35901
37891
  };
35902
37892
  }
35903
37893
  function isEveHandleMessageStreamEvent(event) {
35904
- return isObject(event) && typeof event["type"] === "string";
37894
+ if (!isObject(event) || typeof event["type"] !== "string") {
37895
+ return false;
37896
+ }
37897
+ const type = event["type"];
37898
+ if (type === "session.completed") {
37899
+ return true;
37900
+ }
37901
+ if (!isObject(event["data"])) {
37902
+ return false;
37903
+ }
37904
+ const data = event["data"];
37905
+ if (type === "session.started") {
37906
+ return true;
37907
+ }
37908
+ if (type === "session.failed") {
37909
+ return typeof data["sessionId"] === "string" && typeof data["code"] === "string" && typeof data["message"] === "string";
37910
+ }
37911
+ if (type === "session.waiting") {
37912
+ return data["wait"] === "next-user-message";
37913
+ }
37914
+ if (typeof data["turnId"] !== "string" || typeof data["sequence"] !== "number" || !Number.isFinite(data["sequence"])) {
37915
+ return false;
37916
+ }
37917
+ if (type === "turn.started" || type === "turn.completed" || type === "subagent.called" || type === "subagent.completed") {
37918
+ if (type === "subagent.called") {
37919
+ return typeof data["callId"] === "string" && typeof data["childSessionId"] === "string" && typeof data["name"] === "string";
37920
+ }
37921
+ if (type === "subagent.completed") {
37922
+ return typeof data["callId"] === "string" && typeof data["subagentName"] === "string";
37923
+ }
37924
+ return true;
37925
+ }
37926
+ if (type === "turn.failed") {
37927
+ return typeof data["code"] === "string" && typeof data["message"] === "string";
37928
+ }
37929
+ if (type === "message.received") {
37930
+ return typeof data["message"] === "string";
37931
+ }
37932
+ if (typeof data["stepIndex"] !== "number" || !Number.isFinite(data["stepIndex"]) || data["stepIndex"] < 0) {
37933
+ return false;
37934
+ }
37935
+ switch (type) {
37936
+ case "step.started":
37937
+ return true;
37938
+ case "message.completed":
37939
+ return typeof data["finishReason"] === "string" && (typeof data["message"] === "string" || data["message"] === null);
37940
+ case "reasoning.completed":
37941
+ return typeof data["reasoning"] === "string";
37942
+ case "result.completed":
37943
+ return true;
37944
+ case "step.completed":
37945
+ return typeof data["finishReason"] === "string";
37946
+ case "step.failed":
37947
+ return typeof data["code"] === "string" && typeof data["message"] === "string";
37948
+ case "actions.requested":
37949
+ return Array.isArray(data["actions"]);
37950
+ case "action.result":
37951
+ return isObject(data["result"]) && (data["status"] === "completed" || data["status"] === "failed" || data["status"] === "rejected");
37952
+ default:
37953
+ return false;
37954
+ }
37955
+ }
37956
+ function isEveInstrumentationStepStartedEventInput(input) {
37957
+ if (!isObject(input)) {
37958
+ return false;
37959
+ }
37960
+ const modelInput = input["modelInput"];
37961
+ const session = input["session"];
37962
+ const step = input["step"];
37963
+ const turn = input["turn"];
37964
+ return isObject(modelInput) && Array.isArray(modelInput["messages"]) && isObject(session) && typeof session["id"] === "string" && isObject(step) && typeof step["index"] === "number" && Number.isFinite(step["index"]) && step["index"] >= 0 && isObject(turn) && typeof turn["id"] === "string" && typeof turn["sequence"] === "number" && Number.isFinite(turn["sequence"]);
35905
37965
  }
35906
37966
  var ResumedEveSpan = class {
35907
37967
  constructor(reference) {
@@ -36070,7 +38130,17 @@ var EveBridge = class {
36070
38130
  });
36071
38131
  }
36072
38132
  async handle(event, ctx, hookMetadata) {
38133
+ try {
38134
+ await this.handleUnchecked(event, ctx, hookMetadata);
38135
+ } catch (error) {
38136
+ debugLogger.warn("Error in Eve hook instrumentation:", error);
38137
+ }
38138
+ }
38139
+ async handleUnchecked(event, ctx, hookMetadata) {
36073
38140
  if (!isEveHandleMessageStreamEvent(event)) {
38141
+ if (isObject(event) && typeof event["type"] === "string" && EVE_HANDLED_EVENT_TYPES.has(event["type"])) {
38142
+ debugLogger.warn(`Ignoring malformed Eve hook ${event["type"]} event`);
38143
+ }
36074
38144
  return;
36075
38145
  }
36076
38146
  const run = async () => {
@@ -36396,9 +38466,14 @@ var EveBridge = class {
36396
38466
  }
36397
38467
  for (const action of traceActions) {
36398
38468
  const name = action.kind === "tool-call" ? action.toolName : action.subagentName ?? action.name ?? "agent";
38469
+ let args = "null";
38470
+ try {
38471
+ args = JSON.stringify(action.input) ?? "null";
38472
+ } catch {
38473
+ }
36399
38474
  toolCallsById.set(action.callId, {
36400
38475
  function: {
36401
- arguments: JSON.stringify(action.input),
38476
+ arguments: args,
36402
38477
  name
36403
38478
  },
36404
38479
  id: action.callId,
@@ -37267,17 +39342,33 @@ function consumeCapturedEveModelInput(state, sessionId, turnId, stepIndex) {
37267
39342
  }
37268
39343
  }
37269
39344
  function capturedModelInput(modelInput) {
37270
- const { instructions, messages } = modelInput;
37271
- const value = [];
37272
- if (typeof instructions === "string") {
37273
- value.push({ content: instructions, role: "system" });
37274
- } else if (Array.isArray(instructions)) {
37275
- value.push(...instructions.map(capturedEveModelMessage));
37276
- } else if (instructions) {
37277
- value.push(capturedEveModelMessage(instructions));
37278
- }
37279
- value.push(...messages.map(capturedEveModelMessage));
37280
39345
  try {
39346
+ if (!isObject(modelInput) || !Array.isArray(modelInput["messages"])) {
39347
+ return void 0;
39348
+ }
39349
+ const value = [];
39350
+ const instructions = modelInput["instructions"];
39351
+ if (typeof instructions === "string") {
39352
+ value.push({ content: instructions, role: "system" });
39353
+ } else if (Array.isArray(instructions)) {
39354
+ for (const instruction of instructions) {
39355
+ const captured = capturedEveModelMessage(instruction);
39356
+ if (captured?.role === "system") {
39357
+ value.push(captured);
39358
+ }
39359
+ }
39360
+ } else {
39361
+ const captured = capturedEveModelMessage(instructions);
39362
+ if (captured?.role === "system") {
39363
+ value.push(captured);
39364
+ }
39365
+ }
39366
+ for (const message of modelInput["messages"]) {
39367
+ const captured = capturedEveModelMessage(message);
39368
+ if (captured) {
39369
+ value.push(captured);
39370
+ }
39371
+ }
37281
39372
  const cloned = JSON.parse(JSON.stringify(value));
37282
39373
  if (!Array.isArray(cloned)) {
37283
39374
  return void 0;
@@ -37288,116 +39379,202 @@ function capturedModelInput(modelInput) {
37288
39379
  }
37289
39380
  }
37290
39381
  function capturedEveModelMessage(message) {
37291
- const { content, role } = message;
39382
+ if (!isObject(message)) {
39383
+ return void 0;
39384
+ }
39385
+ const role = message["role"];
39386
+ if (role !== "system" && role !== "user" && role !== "assistant" && role !== "tool") {
39387
+ return void 0;
39388
+ }
39389
+ const content = message["content"];
37292
39390
  if (typeof content === "string") {
37293
39391
  return { content, role };
37294
39392
  }
37295
- return { content: content.map(capturedEveModelContentPart), role };
39393
+ if (!Array.isArray(content)) {
39394
+ return void 0;
39395
+ }
39396
+ const capturedContent = [];
39397
+ for (const part of content) {
39398
+ const captured = capturedEveModelContentPart(part);
39399
+ if (captured) {
39400
+ capturedContent.push(captured);
39401
+ }
39402
+ }
39403
+ return { content: capturedContent, role };
37296
39404
  }
37297
39405
  function capturedEveModelContentPart(part) {
37298
- switch (part.type) {
39406
+ if (!isObject(part) || typeof part["type"] !== "string") {
39407
+ return void 0;
39408
+ }
39409
+ switch (part["type"]) {
37299
39410
  case "text":
37300
- case "reasoning":
37301
- return { text: part.text, type: part.type };
39411
+ case "reasoning": {
39412
+ const text = part["text"];
39413
+ return typeof text === "string" ? { text, type: part["type"] } : void 0;
39414
+ }
37302
39415
  case "image":
39416
+ if (!Object.hasOwn(part, "image")) {
39417
+ return void 0;
39418
+ }
37303
39419
  return {
37304
- image: part.image,
37305
- ...part.mediaType !== void 0 ? { mediaType: part.mediaType } : {},
39420
+ image: part["image"],
39421
+ ...typeof part["mediaType"] === "string" ? { mediaType: part["mediaType"] } : {},
37306
39422
  type: "image"
37307
39423
  };
37308
39424
  case "file":
37309
- case "reasoning-file":
39425
+ case "reasoning-file": {
39426
+ if (!Object.hasOwn(part, "data") || typeof part["mediaType"] !== "string") {
39427
+ return void 0;
39428
+ }
37310
39429
  return {
37311
- data: part.data,
37312
- ...part.type === "file" && part.filename !== void 0 ? { filename: part.filename } : {},
37313
- mediaType: part.mediaType,
37314
- type: part.type
39430
+ data: part["data"],
39431
+ ...part["type"] === "file" && typeof part["filename"] === "string" ? { filename: part["filename"] } : {},
39432
+ mediaType: part["mediaType"],
39433
+ type: part["type"]
37315
39434
  };
39435
+ }
37316
39436
  case "custom":
37317
39437
  return {
37318
- ..."kind" in part ? { kind: part.kind } : {},
39438
+ ...typeof part["kind"] === "string" ? { kind: part["kind"] } : {},
37319
39439
  type: "custom"
37320
39440
  };
37321
- case "tool-call":
39441
+ case "tool-call": {
39442
+ if (typeof part["toolCallId"] !== "string" || typeof part["toolName"] !== "string") {
39443
+ return void 0;
39444
+ }
37322
39445
  return {
37323
- input: part.input,
37324
- ...part.providerExecuted !== void 0 ? { providerExecuted: part.providerExecuted } : {},
37325
- toolCallId: part.toolCallId,
37326
- toolName: part.toolName,
39446
+ input: part["input"],
39447
+ ...typeof part["providerExecuted"] === "boolean" ? { providerExecuted: part["providerExecuted"] } : {},
39448
+ toolCallId: part["toolCallId"],
39449
+ toolName: part["toolName"],
37327
39450
  type: "tool-call"
37328
39451
  };
39452
+ }
37329
39453
  case "tool-result": {
37330
- const output = part.output;
39454
+ const output = part["output"];
39455
+ if (typeof part["toolCallId"] !== "string" || typeof part["toolName"] !== "string" || !isObject(output) || typeof output["type"] !== "string") {
39456
+ return void 0;
39457
+ }
37331
39458
  let capturedOutput;
37332
- switch (output.type) {
39459
+ switch (output["type"]) {
37333
39460
  case "text":
37334
- case "error-text":
37335
- capturedOutput = { type: output.type, value: output.value };
39461
+ case "error-text": {
39462
+ if (typeof output["value"] !== "string") {
39463
+ return void 0;
39464
+ }
39465
+ capturedOutput = {
39466
+ type: output["type"],
39467
+ value: output["value"]
39468
+ };
37336
39469
  break;
39470
+ }
37337
39471
  case "json":
37338
39472
  case "error-json":
37339
- capturedOutput = { type: output.type, value: output.value };
39473
+ capturedOutput = {
39474
+ type: output["type"],
39475
+ value: output["value"]
39476
+ };
37340
39477
  break;
37341
39478
  case "execution-denied":
37342
39479
  capturedOutput = {
37343
- ...output.reason !== void 0 ? { reason: output.reason } : {},
39480
+ ...typeof output["reason"] === "string" ? { reason: output["reason"] } : {},
37344
39481
  type: "execution-denied"
37345
39482
  };
37346
39483
  break;
37347
- case "content":
39484
+ case "content": {
39485
+ if (!Array.isArray(output["value"])) {
39486
+ return void 0;
39487
+ }
39488
+ const value = [];
39489
+ for (const outputPart of output["value"]) {
39490
+ const captured = capturedEveModelContentPart(outputPart);
39491
+ if (captured) {
39492
+ value.push(captured);
39493
+ }
39494
+ }
37348
39495
  capturedOutput = {
37349
39496
  type: "content",
37350
- value: output.value.map(capturedEveModelContentPart)
39497
+ value
37351
39498
  };
37352
39499
  break;
39500
+ }
39501
+ default:
39502
+ return void 0;
37353
39503
  }
37354
39504
  return {
37355
39505
  output: capturedOutput,
37356
- toolCallId: part.toolCallId,
37357
- toolName: part.toolName,
39506
+ toolCallId: part["toolCallId"],
39507
+ toolName: part["toolName"],
37358
39508
  type: "tool-result"
37359
39509
  };
37360
39510
  }
37361
- case "tool-approval-request":
39511
+ case "tool-approval-request": {
39512
+ if (typeof part["approvalId"] !== "string" || typeof part["toolCallId"] !== "string") {
39513
+ return void 0;
39514
+ }
37362
39515
  return {
37363
- approvalId: part.approvalId,
37364
- ...part.isAutomatic !== void 0 ? { isAutomatic: part.isAutomatic } : {},
37365
- ...part.signature !== void 0 ? { signature: part.signature } : {},
37366
- toolCallId: part.toolCallId,
39516
+ approvalId: part["approvalId"],
39517
+ ...typeof part["isAutomatic"] === "boolean" ? { isAutomatic: part["isAutomatic"] } : {},
39518
+ ...typeof part["signature"] === "string" ? { signature: part["signature"] } : {},
39519
+ toolCallId: part["toolCallId"],
37367
39520
  type: "tool-approval-request"
37368
39521
  };
37369
- case "tool-approval-response":
39522
+ }
39523
+ case "tool-approval-response": {
39524
+ if (typeof part["approvalId"] !== "string" || typeof part["approved"] !== "boolean") {
39525
+ return void 0;
39526
+ }
37370
39527
  return {
37371
- approvalId: part.approvalId,
37372
- approved: part.approved,
37373
- ...part.providerExecuted !== void 0 ? { providerExecuted: part.providerExecuted } : {},
37374
- ...part.reason !== void 0 ? { reason: part.reason } : {},
39528
+ approvalId: part["approvalId"],
39529
+ approved: part["approved"],
39530
+ ...typeof part["providerExecuted"] === "boolean" ? { providerExecuted: part["providerExecuted"] } : {},
39531
+ ...typeof part["reason"] === "string" ? { reason: part["reason"] } : {},
37375
39532
  type: "tool-approval-response"
37376
39533
  };
39534
+ }
37377
39535
  case "file-data":
37378
- case "image-data":
39536
+ case "image-data": {
39537
+ if (typeof part["data"] !== "string" || typeof part["mediaType"] !== "string") {
39538
+ return void 0;
39539
+ }
37379
39540
  return {
37380
- data: part.data,
37381
- ...part.type === "file-data" && part.filename !== void 0 ? { filename: part.filename } : {},
37382
- mediaType: part.mediaType,
37383
- type: part.type
39541
+ data: part["data"],
39542
+ ...part["type"] === "file-data" && typeof part["filename"] === "string" ? { filename: part["filename"] } : {},
39543
+ mediaType: part["mediaType"],
39544
+ type: part["type"]
37384
39545
  };
39546
+ }
37385
39547
  case "file-url":
37386
- case "image-url":
39548
+ case "image-url": {
39549
+ if (typeof part["url"] !== "string") {
39550
+ return void 0;
39551
+ }
37387
39552
  return {
37388
- ...part.type === "file-url" && part.mediaType !== void 0 ? { mediaType: part.mediaType } : {},
37389
- type: part.type,
37390
- url: part.url
39553
+ ...part["type"] === "file-url" && typeof part["mediaType"] === "string" ? { mediaType: part["mediaType"] } : {},
39554
+ type: part["type"],
39555
+ url: part["url"]
37391
39556
  };
39557
+ }
37392
39558
  case "file-id":
37393
- case "image-file-id":
37394
- return { fileId: part.fileId, type: part.type };
39559
+ case "image-file-id": {
39560
+ const fileId = part["fileId"];
39561
+ if (typeof fileId !== "string" && !isObject(fileId)) {
39562
+ return void 0;
39563
+ }
39564
+ return { fileId, type: part["type"] };
39565
+ }
37395
39566
  case "file-reference":
37396
- case "image-file-reference":
39567
+ case "image-file-reference": {
39568
+ if (!isObject(part["providerReference"])) {
39569
+ return void 0;
39570
+ }
37397
39571
  return {
37398
- providerReference: part.providerReference,
37399
- type: part.type
39572
+ providerReference: part["providerReference"],
39573
+ type: part["type"]
37400
39574
  };
39575
+ }
39576
+ default:
39577
+ return void 0;
37401
39578
  }
37402
39579
  }
37403
39580
  function isCapturedModelInput(input) {
@@ -37533,18 +39710,54 @@ function createEveInstrumentationProvider(options = {}) {
37533
39710
  recordOutputs: true
37534
39711
  }),
37535
39712
  events: {
37536
- "action.completed": (event, context) => bridge.handleActionTerminal(event, context),
37537
- "action.failed": (event, context) => bridge.handleActionTerminal(event, context),
37538
- "action.started": (event, context) => bridge.handleActionStarted(event, context),
37539
- "model.call.completed": (event, context) => bridge.handleModelTerminal(event, context),
37540
- "model.call.failed": (event, context) => bridge.handleModelTerminal(event, context),
37541
- "model.call.started": (event, context) => bridge.handleModelStarted(event, context),
37542
- "step.attempt.completed": (event) => bridge.handleStepAttemptTerminal(event),
37543
- "step.attempt.failed": (event) => bridge.handleStepAttemptTerminal(event),
37544
- "turn.cancelled": (event, context) => bridge.handleTurnTerminal(event, context),
37545
- "turn.completed": (event, context) => bridge.handleTurnTerminal(event, context),
37546
- "turn.failed": (event, context) => bridge.handleTurnTerminal(event, context),
37547
- "turn.started": (event, context) => bridge.handleTurnStarted(event, context)
39713
+ "action.completed": providerHandler(
39714
+ "action.completed",
39715
+ bridge.handleActionTerminal.bind(bridge)
39716
+ ),
39717
+ "action.failed": providerHandler(
39718
+ "action.failed",
39719
+ bridge.handleActionTerminal.bind(bridge)
39720
+ ),
39721
+ "action.started": providerHandler(
39722
+ "action.started",
39723
+ bridge.handleActionStarted.bind(bridge)
39724
+ ),
39725
+ "model.call.completed": providerHandler(
39726
+ "model.call.completed",
39727
+ bridge.handleModelTerminal.bind(bridge)
39728
+ ),
39729
+ "model.call.failed": providerHandler(
39730
+ "model.call.failed",
39731
+ bridge.handleModelTerminal.bind(bridge)
39732
+ ),
39733
+ "model.call.started": providerHandler(
39734
+ "model.call.started",
39735
+ bridge.handleModelStarted.bind(bridge)
39736
+ ),
39737
+ "step.attempt.completed": providerHandler(
39738
+ "step.attempt.completed",
39739
+ (event) => bridge.handleStepAttemptTerminal(event)
39740
+ ),
39741
+ "step.attempt.failed": providerHandler(
39742
+ "step.attempt.failed",
39743
+ (event) => bridge.handleStepAttemptTerminal(event)
39744
+ ),
39745
+ "turn.cancelled": providerHandler(
39746
+ "turn.cancelled",
39747
+ bridge.handleTurnTerminal.bind(bridge)
39748
+ ),
39749
+ "turn.completed": providerHandler(
39750
+ "turn.completed",
39751
+ bridge.handleTurnTerminal.bind(bridge)
39752
+ ),
39753
+ "turn.failed": providerHandler(
39754
+ "turn.failed",
39755
+ bridge.handleTurnTerminal.bind(bridge)
39756
+ ),
39757
+ "turn.started": providerHandler(
39758
+ "turn.started",
39759
+ bridge.handleTurnStarted.bind(bridge)
39760
+ )
37548
39761
  },
37549
39762
  flush,
37550
39763
  setup: options.setup
@@ -37900,17 +40113,20 @@ function modelOutput(event) {
37900
40113
  const reasoning = [];
37901
40114
  const toolCalls = [];
37902
40115
  for (const part of content) {
37903
- if (part.type === "text") {
37904
- text += part.text;
37905
- } else if (part.type === "reasoning" && part.text.trim().length > 0) {
37906
- reasoning.push({ content: part.text });
37907
- } else if (part.type === "tool-call") {
40116
+ if (!isObject(part)) {
40117
+ continue;
40118
+ }
40119
+ if (part["type"] === "text" && typeof part["text"] === "string") {
40120
+ text += part["text"];
40121
+ } else if (part["type"] === "reasoning" && typeof part["text"] === "string" && part["text"].trim().length > 0) {
40122
+ reasoning.push({ content: part["text"] });
40123
+ } else if (part["type"] === "tool-call" && typeof part["toolName"] === "string" && typeof part["callId"] === "string") {
37908
40124
  toolCalls.push({
37909
40125
  function: {
37910
- arguments: safeJsonStringify(part.input),
37911
- name: part.toolName
40126
+ arguments: safeJsonStringify(part["input"]),
40127
+ name: part["toolName"]
37912
40128
  },
37913
- id: part.callId,
40129
+ id: part["callId"],
37914
40130
  type: "function"
37915
40131
  });
37916
40132
  }
@@ -37929,13 +40145,13 @@ function modelOutput(event) {
37929
40145
  ];
37930
40146
  }
37931
40147
  function usageMetrics(usage) {
37932
- const promptTokens = nonNegativeNumber(usage.inputTokens);
37933
- const completionTokens = nonNegativeNumber(usage.outputTokens);
40148
+ const promptTokens = nonNegativeNumber(usage?.inputTokens);
40149
+ const completionTokens = nonNegativeNumber(usage?.outputTokens);
37934
40150
  const cachedTokens = nonNegativeNumber(
37935
- usage.inputTokenDetails?.cacheReadTokens
40151
+ usage?.inputTokenDetails?.cacheReadTokens
37936
40152
  );
37937
40153
  const cacheCreationTokens = nonNegativeNumber(
37938
- usage.inputTokenDetails?.cacheWriteTokens
40154
+ usage?.inputTokenDetails?.cacheWriteTokens
37939
40155
  );
37940
40156
  return {
37941
40157
  ...promptTokens !== void 0 ? { prompt_tokens: promptTokens } : {},
@@ -37972,10 +40188,76 @@ function turnIdempotencyKey(sessionId, turnId) {
37972
40188
  function actionIdempotencyKey(sessionId, turnId, callId) {
37973
40189
  return `action:${sessionId}:${turnId}:${callId}`;
37974
40190
  }
40191
+ function providerHandler(type, handler) {
40192
+ return async (event, context) => {
40193
+ try {
40194
+ if (!isEveProviderEvent(event, type) || !isEveProviderContext(context)) {
40195
+ debugLogger.warn(`Ignoring malformed Eve provider ${type} event`);
40196
+ return;
40197
+ }
40198
+ await handler(event, context);
40199
+ } catch (error) {
40200
+ debugLogger.warn(`Error in Eve provider ${type}:`, error);
40201
+ }
40202
+ };
40203
+ }
40204
+ function isEveProviderEvent(event, type) {
40205
+ if (!isObject(event) || event["type"] !== type || typeof event["idempotencyKey"] !== "string" || event["idempotencyKey"].length === 0) {
40206
+ return false;
40207
+ }
40208
+ if (type === "turn.started") {
40209
+ const parentLineage = event["parentLineage"];
40210
+ return typeof event["rootSessionId"] === "string" && typeof event["sessionId"] === "string" && typeof event["turnId"] === "string" && typeof event["sequence"] === "number" && Number.isFinite(event["sequence"]) && (parentLineage === void 0 || isEveProviderParentLineage(parentLineage));
40211
+ }
40212
+ if (type === "turn.cancelled" || type === "turn.completed" || type === "turn.failed") {
40213
+ return typeof event["sessionId"] === "string" && typeof event["turnId"] === "string";
40214
+ }
40215
+ if (!isEveProviderScope(event["scope"])) {
40216
+ return false;
40217
+ }
40218
+ if (type === "model.call.started") {
40219
+ const model = event["model"];
40220
+ return isObject(model) && typeof model["modelId"] === "string" && typeof model["provider"] === "string";
40221
+ }
40222
+ if (type === "model.call.completed") {
40223
+ return typeof event["finishReason"] === "string" && isObject(event["usage"]) && (event["content"] === void 0 || Array.isArray(event["content"]));
40224
+ }
40225
+ if (type === "model.call.failed") {
40226
+ return true;
40227
+ }
40228
+ if (type === "action.started") {
40229
+ return typeof event["callId"] === "string" && typeof event["name"] === "string" && (event["kind"] === "load-skill" || event["kind"] === "remote-agent-call" || event["kind"] === "subagent-call" || event["kind"] === "tool-call");
40230
+ }
40231
+ if (type === "action.completed") {
40232
+ const output = event["output"];
40233
+ return event["outcome"] === "completed" && isObject(output) && (output["type"] === "result" || output["type"] === "error");
40234
+ }
40235
+ if (type === "action.failed") {
40236
+ return event["outcome"] === "abandoned" || event["outcome"] === "cancelled" || event["outcome"] === "failed" || event["outcome"] === "rejected";
40237
+ }
40238
+ return type === "step.attempt.completed" || type === "step.attempt.failed";
40239
+ }
40240
+ function isEveProviderContext(value) {
40241
+ if (!isObject(value) || !isObject(value["state"])) {
40242
+ return false;
40243
+ }
40244
+ return typeof value["state"]["get"] === "function" && typeof value["state"]["set"] === "function";
40245
+ }
40246
+ function isEveProviderScope(value) {
40247
+ return isObject(value) && typeof value["attemptId"] === "string" && typeof value["attemptIndex"] === "number" && Number.isFinite(value["attemptIndex"]) && typeof value["sessionId"] === "string" && typeof value["stepIndex"] === "number" && Number.isFinite(value["stepIndex"]) && typeof value["turnId"] === "string" && (value["rootSessionId"] === void 0 || typeof value["rootSessionId"] === "string");
40248
+ }
40249
+ function isEveProviderParentLineage(value) {
40250
+ return isObject(value) && typeof value["callId"] === "string" && typeof value["sessionId"] === "string" && typeof value["turnId"] === "string";
40251
+ }
37975
40252
 
37976
40253
  // src/instrumentation/plugins/eve-instrumentation.ts
37977
40254
  var EVE_INSTRUMENTATION_PROVIDER = /* @__PURE__ */ Symbol.for("eve.instrumentation.provider");
37978
40255
  function braintrustEveInstrumentation(options) {
40256
+ if (!options || typeof options !== "object") {
40257
+ throw new TypeError(
40258
+ "braintrustEveInstrumentation requires an options object"
40259
+ );
40260
+ }
37979
40261
  const definition = "defineState" in options ? createLegacyEveInstrumentation(options) : createEveInstrumentationProvider(options);
37980
40262
  const declaration = {
37981
40263
  ...definition,
@@ -38026,6 +40308,8 @@ var envIntegrationAliases = {
38026
40308
  "openai-agents-core": "openAIAgents",
38027
40309
  openaiagentscore: "openAIAgents",
38028
40310
  google: "google",
40311
+ "google-generative-ai": "googleGenerativeAI",
40312
+ googlegenerativeai: "googleGenerativeAI",
38029
40313
  "google-genai": "googleGenAI",
38030
40314
  googlegenai: "googleGenAI",
38031
40315
  huggingface: "huggingface",
@@ -38056,10 +40340,15 @@ var envIntegrationAliases = {
38056
40340
  "langchain-js": "langchain",
38057
40341
  "@langchain": "langchain",
38058
40342
  langgraph: "langgraph",
40343
+ langgraphsdk: "langgraphSDK",
40344
+ "langgraph-sdk": "langgraphSDK",
40345
+ "@langchain/langgraph-sdk": "langgraphSDK",
38059
40346
  langsmith: "langsmith",
38060
40347
  voyage: "voyageai",
38061
40348
  "voyage-ai": "voyageai",
38062
- voyageai: "voyageai"
40349
+ voyageai: "voyageai",
40350
+ elevenlabs: "elevenlabs",
40351
+ "@elevenlabs/elevenlabs-js": "elevenlabs"
38063
40352
  };
38064
40353
  function getDefaultInstrumentationIntegrations() {
38065
40354
  return {
@@ -38070,6 +40359,7 @@ function getDefaultInstrumentationIntegrations() {
38070
40359
  aisdk: true,
38071
40360
  google: true,
38072
40361
  googleGenAI: true,
40362
+ googleGenerativeAI: true,
38073
40363
  googleADK: true,
38074
40364
  huggingface: true,
38075
40365
  claudeAgentSDK: true,
@@ -38093,8 +40383,10 @@ function getDefaultInstrumentationIntegrations() {
38093
40383
  gitHubCopilot: true,
38094
40384
  langchain: true,
38095
40385
  langgraph: true,
40386
+ langgraphSDK: true,
38096
40387
  langsmith: true,
38097
40388
  voyageai: true,
40389
+ elevenlabs: true,
38098
40390
  piCodingAgent: true,
38099
40391
  strandsAgentSDK: true,
38100
40392
  cloudflareAgents: true