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
@@ -2914,6 +2914,14 @@ var ChatCompletionContentPartImageWithTitle = z6.object({
2914
2914
  ttl: z6.enum(["5m", "1h"]).optional()
2915
2915
  }).optional()
2916
2916
  });
2917
+ var ChatCompletionContentPartInputAudioWithTitle = z6.object({
2918
+ input_audio: z6.object({ data: z6.string(), format: z6.enum(["wav", "mp3"]) }),
2919
+ type: z6.literal("input_audio"),
2920
+ cache_control: z6.object({
2921
+ type: z6.literal("ephemeral"),
2922
+ ttl: z6.enum(["5m", "1h"]).optional()
2923
+ }).optional()
2924
+ });
2917
2925
  var ChatCompletionContentPartFileFile = z6.object({ file_data: z6.string(), filename: z6.string(), file_id: z6.string() }).partial();
2918
2926
  var ChatCompletionContentPartFileWithTitle = z6.object({
2919
2927
  file: ChatCompletionContentPartFileFile,
@@ -2926,6 +2934,7 @@ var ChatCompletionContentPartFileWithTitle = z6.object({
2926
2934
  var ChatCompletionContentPart = z6.union([
2927
2935
  ChatCompletionContentPartTextWithTitle,
2928
2936
  ChatCompletionContentPartImageWithTitle,
2937
+ ChatCompletionContentPartInputAudioWithTitle,
2929
2938
  ChatCompletionContentPartFileWithTitle
2930
2939
  ]);
2931
2940
  var ChatCompletionContentPartText = z6.object({
@@ -5753,6 +5762,7 @@ var INSTRUMENTATION_NAMES = {
5753
5762
  GENKIT: "genkit",
5754
5763
  GITHUB_COPILOT: "github-copilot",
5755
5764
  GOOGLE_ADK: "google-adk",
5765
+ GOOGLE_GENERATIVE_AI: "google-generative-ai",
5756
5766
  GOOGLE_GENAI: "google-genai",
5757
5767
  GROQ: "groq",
5758
5768
  HUGGINGFACE: "huggingface",
@@ -5760,6 +5770,7 @@ var INSTRUMENTATION_NAMES = {
5760
5770
  LANGSMITH: "langsmith",
5761
5771
  MASTRA: "mastra",
5762
5772
  MISTRAL: "mistral",
5773
+ LANGGRAPH_SDK: "langgraph-sdk",
5763
5774
  OLLAMA: "ollama",
5764
5775
  OPENAI: "openai",
5765
5776
  OPENAI_AGENTS: "openai-agents",
@@ -5768,12 +5779,13 @@ var INSTRUMENTATION_NAMES = {
5768
5779
  OPENROUTER_AGENT: "openrouter-agent",
5769
5780
  PI_CODING_AGENT: "pi-coding-agent",
5770
5781
  STRANDS_AGENT_SDK: "strands-agent-sdk",
5771
- VOYAGEAI: "voyageai"
5782
+ VOYAGEAI: "voyageai",
5783
+ ELEVENLABS: "elevenlabs"
5772
5784
  };
5773
5785
  var INTERNAL_SPAN_INSTRUMENTATION_NAME = /* @__PURE__ */ Symbol.for(
5774
5786
  "braintrust.spanInstrumentationName"
5775
5787
  );
5776
- var SDK_VERSION = true ? "3.31.0" : "0.0.0";
5788
+ var SDK_VERSION = true ? "3.33.0" : "0.0.0";
5777
5789
  function withSpanInstrumentationName(args, instrumentationName) {
5778
5790
  return {
5779
5791
  ...args,
@@ -8492,6 +8504,38 @@ function getSpanParentObjectAndPropagatedState(options) {
8492
8504
  function getSpanParentObject(options) {
8493
8505
  return getSpanParentObjectAndPropagatedState(options).parentObject;
8494
8506
  }
8507
+ function _internalExportParentSynchronously(parent) {
8508
+ if ("toStr" in parent) {
8509
+ return parent.toStr();
8510
+ }
8511
+ if ("getParentInfo" in parent) {
8512
+ const parentInfo = parent.getParentInfo();
8513
+ if (!parentInfo) {
8514
+ return void 0;
8515
+ }
8516
+ const objectId = parentInfo.objectId.getSync().value;
8517
+ if (!objectId && !parentInfo.computeObjectMetadataArgs) {
8518
+ return void 0;
8519
+ }
8520
+ return new SpanComponentsV4({
8521
+ object_type: parentInfo.objectType,
8522
+ ...objectId ? { object_id: objectId } : {
8523
+ compute_object_metadata_args: parentInfo.computeObjectMetadataArgs ?? {}
8524
+ },
8525
+ row_id: parent.id,
8526
+ root_span_id: parent.rootSpanId,
8527
+ span_id: parent.spanId
8528
+ }).toStr();
8529
+ }
8530
+ const components = braintrustParentToComponents(parent._getOtelParent());
8531
+ if (!components) {
8532
+ return void 0;
8533
+ }
8534
+ return new SpanComponentsV4({
8535
+ object_type: components.objectType,
8536
+ ...components.objectId ? { object_id: components.objectId } : { compute_object_metadata_args: components.computeArgs ?? {} }
8537
+ }).toStr();
8538
+ }
8495
8539
  function currentBraintrustParent(state) {
8496
8540
  const resolvedState = state ?? _globalState;
8497
8541
  const experiment = currentExperiment({ state: resolvedState });
@@ -9798,10 +9842,16 @@ var SpanImpl = class _SpanImpl {
9798
9842
  inject(carrier) {
9799
9843
  const resolvedCarrier = carrier ?? {};
9800
9844
  try {
9845
+ const braintrustParent = this._getOtelParent() ?? this._propagatedState?.braintrustParent;
9846
+ if (!braintrustParent) {
9847
+ debugLogger.forState(this._state).warn(
9848
+ "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."
9849
+ );
9850
+ }
9801
9851
  _injectIntoCarrier(resolvedCarrier, {
9802
9852
  traceId: this._rootSpanId,
9803
9853
  spanId: this._spanId,
9804
- braintrustParent: this._getOtelParent() ?? this._propagatedState?.braintrustParent,
9854
+ braintrustParent,
9805
9855
  propagatedState: this._propagatedState
9806
9856
  });
9807
9857
  } catch (e) {
@@ -10351,6 +10401,16 @@ function renderMessageImpl(render, message, variables) {
10351
10401
  }
10352
10402
  }
10353
10403
  ];
10404
+ case "input_audio":
10405
+ return [
10406
+ {
10407
+ ...c,
10408
+ input_audio: {
10409
+ ...c.input_audio,
10410
+ data: render(c.input_audio.data)
10411
+ }
10412
+ }
10413
+ ];
10354
10414
  case "file":
10355
10415
  return [
10356
10416
  {
@@ -11874,6 +11934,18 @@ function defineChannels(pkg, channels, options) {
11874
11934
  var openAIChannels = defineChannels(
11875
11935
  "openai",
11876
11936
  {
11937
+ agentsTraceStart: channel({
11938
+ channelName: "agents.trace.start",
11939
+ kind: "async"
11940
+ }),
11941
+ agentsTraceCapture: channel({
11942
+ channelName: "agents.trace.capture",
11943
+ kind: "async"
11944
+ }),
11945
+ agentsTraceFail: channel({
11946
+ channelName: "agents.trace.fail",
11947
+ kind: "async"
11948
+ }),
11877
11949
  filesCreateTraced: channel({
11878
11950
  channelName: "files.create-traced",
11879
11951
  kind: "async"
@@ -12242,6 +12314,23 @@ function getCachedMetricFromHeaders(headers) {
12242
12314
  return parseCachedHeader(headers.get(LEGACY_CACHED_HEADER));
12243
12315
  }
12244
12316
 
12317
+ // src/instrumentation/plugins/openai-manual-instrumentation-utils.ts
12318
+ async function deterministicDigest(namespace, ...parts) {
12319
+ const encoded = new TextEncoder().encode(
12320
+ [namespace, ...parts].map((part) => `${part.length}:${part}`).join("\0")
12321
+ );
12322
+ return new Uint8Array(
12323
+ await globalThis.crypto.subtle.digest("SHA-256", encoded)
12324
+ );
12325
+ }
12326
+ function digestHex(bytes, length) {
12327
+ return Array.from(bytes.slice(0, length)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
12328
+ }
12329
+ function digestUuid(bytes) {
12330
+ const hex = digestHex(bytes, 16);
12331
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
12332
+ }
12333
+
12245
12334
  // src/instrumentation/plugins/openai-batch-instrumentation.ts
12246
12335
  var SUPPORTED_ENDPOINTS = /* @__PURE__ */ new Set(["/v1/chat/completions", "/v1/responses"]);
12247
12336
  var TERMINAL_STATUSES = /* @__PURE__ */ new Set([
@@ -12282,21 +12371,6 @@ async function exportParent(parent) {
12282
12371
  }
12283
12372
  return void 0;
12284
12373
  }
12285
- async function deterministicDigest(namespace, ...parts) {
12286
- const encoded = new TextEncoder().encode(
12287
- [namespace, ...parts].map((part) => `${part.length}:${part}`).join("\0")
12288
- );
12289
- return new Uint8Array(
12290
- await globalThis.crypto.subtle.digest("SHA-256", encoded)
12291
- );
12292
- }
12293
- function digestHex(bytes, length) {
12294
- return Array.from(bytes.slice(0, length)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
12295
- }
12296
- function digestUuid(bytes) {
12297
- const hex = digestHex(bytes, 16);
12298
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
12299
- }
12300
12374
  async function batchSpanIds(inputFileId) {
12301
12375
  const [row, span, root] = await Promise.all([
12302
12376
  deterministicDigest("openai:batch:row", inputFileId),
@@ -12787,6 +12861,628 @@ var interceptOpenAIBatchTraceComplete = (target, thisArg, args) => Promise.resol
12787
12861
  return result;
12788
12862
  });
12789
12863
 
12864
+ // src/instrumentation/plugins/openai-agents-api-instrumentation.ts
12865
+ var TERMINAL_TURN_EVENTS = /* @__PURE__ */ new Set([
12866
+ "agent.session.turn.completed",
12867
+ "agent.session.turn.failed",
12868
+ "agent.session.turn.cancelled"
12869
+ ]);
12870
+ var TURN_LIFECYCLE_EVENTS = /* @__PURE__ */ new Set([
12871
+ "agent.session.turn.created",
12872
+ "agent.session.turn.in_progress",
12873
+ ...TERMINAL_TURN_EVENTS
12874
+ ]);
12875
+ var SESSION_EVENTS = /* @__PURE__ */ new Set([
12876
+ "agent.session.created",
12877
+ "agent.session.failed",
12878
+ "agent.session.idle",
12879
+ "agent.session.in_progress",
12880
+ "agent.session.requires_action"
12881
+ ]);
12882
+ var SUBAGENT_EVENTS = /* @__PURE__ */ new Set([
12883
+ "agent.session.subagent.active",
12884
+ "agent.session.subagent.closed",
12885
+ "agent.session.subagent.created"
12886
+ ]);
12887
+ function read2(value, key) {
12888
+ if (!isObject(value)) {
12889
+ return void 0;
12890
+ }
12891
+ try {
12892
+ return Reflect.get(value, key);
12893
+ } catch {
12894
+ return void 0;
12895
+ }
12896
+ }
12897
+ function stringValue(value) {
12898
+ return typeof value === "string" && value.length > 0 ? value : void 0;
12899
+ }
12900
+ function recordValue(record, key) {
12901
+ return Object.hasOwn(record, key) ? record[key] : void 0;
12902
+ }
12903
+ function setRecordValue(record, key, value) {
12904
+ Object.defineProperty(record, key, {
12905
+ configurable: true,
12906
+ enumerable: true,
12907
+ value,
12908
+ writable: true
12909
+ });
12910
+ }
12911
+ function loggedError(value, fallback) {
12912
+ if (value instanceof Error) {
12913
+ return value;
12914
+ }
12915
+ const message = stringValue(read2(value, "message"));
12916
+ return new Error(message ?? (typeof value === "string" ? value : fallback));
12917
+ }
12918
+ function logInstrumentationError(context, error) {
12919
+ debugLogger.debug(`OpenAI Agents API instrumentation ${context}:`, error);
12920
+ }
12921
+ async function childSpanIds2(rootKey, kind, providerId) {
12922
+ const [row, span] = await Promise.all([
12923
+ deterministicDigest("openai:agents:row", rootKey, kind, providerId),
12924
+ deterministicDigest("openai:agents:span", rootKey, kind, providerId)
12925
+ ]);
12926
+ return { rowId: digestUuid(row), spanId: digestHex(span, 8) };
12927
+ }
12928
+ function traceMetadata(args) {
12929
+ const metadata = {};
12930
+ const suppliedMetadata = read2(args, "metadata");
12931
+ if (isObject(suppliedMetadata)) {
12932
+ try {
12933
+ for (const key of Object.keys(suppliedMetadata)) {
12934
+ metadata[key] = read2(suppliedMetadata, key);
12935
+ }
12936
+ } catch (error) {
12937
+ logInstrumentationError("could not read supplied metadata", error);
12938
+ }
12939
+ }
12940
+ const agent = read2(args, "agent");
12941
+ const agentId = stringValue(read2(agent, "id")) ?? stringValue(read2(args, "agent_id"));
12942
+ const agentName = stringValue(read2(agent, "name"));
12943
+ const model = stringValue(read2(agent, "model"));
12944
+ return {
12945
+ ...metadata,
12946
+ api: "agents",
12947
+ ...agentId ? { agent_id: agentId } : {},
12948
+ ...agentName ? { agent_name: agentName } : {},
12949
+ ...model ? { model } : {},
12950
+ provider: "openai"
12951
+ };
12952
+ }
12953
+ function copyState(state) {
12954
+ return {
12955
+ ...state,
12956
+ callItems: { ...state.callItems },
12957
+ eventIds: [...state.eventIds],
12958
+ openTools: { ...state.openTools },
12959
+ subagents: { ...state.subagents },
12960
+ turnSubagents: { ...state.turnSubagents }
12961
+ };
12962
+ }
12963
+ function startRootSpan(state) {
12964
+ const root = SpanComponentsV4.fromStr(state.root);
12965
+ const parent = SpanComponentsV4.fromStr(state.rootParent);
12966
+ const rowId = stringValue(root.data.row_id);
12967
+ const rootSpanId = stringValue(root.data.root_span_id);
12968
+ const spanId = stringValue(root.data.span_id);
12969
+ if (!rowId || !rootSpanId || !spanId) {
12970
+ throw new Error("OpenAI Agents trace root is invalid");
12971
+ }
12972
+ const hasParentSpan = Boolean(
12973
+ parent.data.row_id && parent.data.span_id && parent.data.root_span_id
12974
+ );
12975
+ return withCurrent(
12976
+ NOOP_SPAN,
12977
+ () => _internalStartSpanWithInitialMergeAndParentSpanIds(
12978
+ withSpanInstrumentationName(
12979
+ {
12980
+ name: "openai.agents.turn",
12981
+ type: "task" /* TASK */,
12982
+ parent: state.rootParent,
12983
+ ...!hasParentSpan ? {
12984
+ parentSpanIds: {
12985
+ parentSpanIds: [],
12986
+ rootSpanId
12987
+ }
12988
+ } : {},
12989
+ spanId,
12990
+ startTime: state.startTime,
12991
+ event: { id: rowId }
12992
+ },
12993
+ INSTRUMENTATION_NAMES.OPENAI
12994
+ )
12995
+ )
12996
+ );
12997
+ }
12998
+ async function startSubagentSpan(state, subagentId, input, metadata, visiting = /* @__PURE__ */ new Set()) {
12999
+ const subagent = recordValue(state.subagents, subagentId);
13000
+ let parent = state.root;
13001
+ if (subagent?.parentAgentId && subagent.parentAgentId !== subagentId && recordValue(state.subagents, subagent.parentAgentId) && !visiting.has(subagent.parentAgentId)) {
13002
+ visiting.add(subagentId);
13003
+ parent = await (await startSubagentSpan(
13004
+ state,
13005
+ subagent.parentAgentId,
13006
+ void 0,
13007
+ void 0,
13008
+ visiting
13009
+ )).export();
13010
+ }
13011
+ const ids = await childSpanIds2(state.rootKey, "subagent", subagentId);
13012
+ return withCurrent(
13013
+ NOOP_SPAN,
13014
+ () => _internalStartSpanWithInitialMerge(
13015
+ withSpanInstrumentationName(
13016
+ {
13017
+ name: "openai.agents.subagent",
13018
+ type: "task" /* TASK */,
13019
+ parent,
13020
+ spanId: ids.spanId,
13021
+ startTime: subagent?.openedAt,
13022
+ event: {
13023
+ id: ids.rowId,
13024
+ ...input !== void 0 ? { input } : {},
13025
+ metadata: {
13026
+ ...metadata,
13027
+ agent_id: subagentId,
13028
+ ...subagent?.parentAgentId ? { parent_agent_id: subagent.parentAgentId } : {},
13029
+ provider: "openai"
13030
+ }
13031
+ }
13032
+ },
13033
+ INSTRUMENTATION_NAMES.OPENAI
13034
+ )
13035
+ )
13036
+ );
13037
+ }
13038
+ async function parentForTurn(state, turnId) {
13039
+ const subagentId = turnId ? recordValue(state.turnSubagents, turnId) : void 0;
13040
+ if (!subagentId) {
13041
+ return state.root;
13042
+ }
13043
+ return await (await startSubagentSpan(state, subagentId)).export();
13044
+ }
13045
+ async function startToolSpan(state, tool, input) {
13046
+ const ids = await childSpanIds2(state.rootKey, "tool", tool.itemId);
13047
+ return withCurrent(
13048
+ NOOP_SPAN,
13049
+ async () => _internalStartSpanWithInitialMerge(
13050
+ withSpanInstrumentationName(
13051
+ {
13052
+ name: tool.name,
13053
+ type: "tool" /* TOOL */,
13054
+ parent: await parentForTurn(state, tool.turnId),
13055
+ spanId: ids.spanId,
13056
+ startTime: tool.startTime,
13057
+ event: {
13058
+ id: ids.rowId,
13059
+ ...input !== void 0 ? { input } : {},
13060
+ metadata: {
13061
+ item_id: tool.itemId,
13062
+ provider: "openai",
13063
+ tool_type: tool.toolType,
13064
+ ...tool.turnId ? { turn_id: tool.turnId } : {}
13065
+ }
13066
+ }
13067
+ },
13068
+ INSTRUMENTATION_NAMES.OPENAI
13069
+ )
13070
+ )
13071
+ );
13072
+ }
13073
+ function toolFromItem(item, observedAt) {
13074
+ const itemId = stringValue(read2(item, "id"));
13075
+ const toolType = stringValue(read2(item, "type"));
13076
+ if (!itemId || !toolType) {
13077
+ return void 0;
13078
+ }
13079
+ const turnId = stringValue(read2(item, "turn_id"));
13080
+ switch (toolType) {
13081
+ case "function_call":
13082
+ return {
13083
+ input: read2(item, "arguments"),
13084
+ tool: {
13085
+ itemId,
13086
+ name: stringValue(read2(item, "name")) ?? "Function call",
13087
+ startTime: observedAt,
13088
+ toolType,
13089
+ ...turnId ? { turnId } : {}
13090
+ }
13091
+ };
13092
+ case "mcp_call": {
13093
+ const name = stringValue(read2(item, "name")) ?? "MCP call";
13094
+ const server = stringValue(read2(item, "server_label"));
13095
+ return {
13096
+ input: read2(item, "arguments"),
13097
+ tool: {
13098
+ itemId,
13099
+ name: server ? `${server}.${name}` : name,
13100
+ startTime: observedAt,
13101
+ toolType,
13102
+ ...turnId ? { turnId } : {}
13103
+ }
13104
+ };
13105
+ }
13106
+ case "web_search_call":
13107
+ return {
13108
+ input: read2(item, "action"),
13109
+ tool: {
13110
+ itemId,
13111
+ name: "Web search",
13112
+ startTime: observedAt,
13113
+ toolType,
13114
+ ...turnId ? { turnId } : {}
13115
+ }
13116
+ };
13117
+ case "command_execution":
13118
+ return {
13119
+ input: {
13120
+ command: read2(item, "command"),
13121
+ cwd: read2(item, "cwd")
13122
+ },
13123
+ tool: {
13124
+ itemId,
13125
+ name: "Command execution",
13126
+ startTime: observedAt,
13127
+ toolType,
13128
+ ...turnId ? { turnId } : {}
13129
+ }
13130
+ };
13131
+ default:
13132
+ return void 0;
13133
+ }
13134
+ }
13135
+ function textFromContent(content) {
13136
+ if (!Array.isArray(content)) {
13137
+ return void 0;
13138
+ }
13139
+ const text = [];
13140
+ for (const part of content) {
13141
+ const partText = read2(part, "text");
13142
+ if (read2(part, "type") === "output_text" && typeof partText === "string") {
13143
+ text.push(partText);
13144
+ }
13145
+ }
13146
+ return text.length > 0 ? text.join("") : void 0;
13147
+ }
13148
+ function toolOutput(item, toolType) {
13149
+ switch (toolType) {
13150
+ case "function_call":
13151
+ return read2(item, "output");
13152
+ case "mcp_call":
13153
+ return read2(item, "output");
13154
+ case "web_search_call":
13155
+ return read2(item, "action");
13156
+ case "command_execution":
13157
+ return read2(item, "output");
13158
+ default:
13159
+ return void 0;
13160
+ }
13161
+ }
13162
+ function toolFailed(item, toolType) {
13163
+ const status = read2(item, "status");
13164
+ const explicitError = read2(item, "error");
13165
+ if (explicitError !== void 0 && explicitError !== null) {
13166
+ return loggedError(explicitError, `OpenAI ${toolType} failed`);
13167
+ }
13168
+ if (status === "failed" || status === "incomplete") {
13169
+ return new Error(`OpenAI ${toolType} ${status}`);
13170
+ }
13171
+ if (toolType === "command_execution" && typeof read2(item, "exit_code") === "number" && read2(item, "exit_code") !== 0) {
13172
+ return new Error(
13173
+ `OpenAI command exited with code ${read2(item, "exit_code")}`
13174
+ );
13175
+ }
13176
+ return void 0;
13177
+ }
13178
+ async function completeTool(state, tool, item, endTime) {
13179
+ const span = await startToolSpan(state, tool);
13180
+ const output = toolOutput(item, tool.toolType);
13181
+ const error = toolFailed(item, tool.toolType);
13182
+ span.log({
13183
+ ...output !== void 0 ? { output } : {},
13184
+ ...error ? { error } : {},
13185
+ metadata: {
13186
+ status: read2(item, "status"),
13187
+ ...tool.toolType === "command_execution" ? { exit_code: read2(item, "exit_code") } : {}
13188
+ }
13189
+ });
13190
+ span.end({ endTime });
13191
+ Reflect.deleteProperty(state.openTools, tool.itemId);
13192
+ }
13193
+ async function captureMessage(state, item) {
13194
+ if (read2(item, "type") !== "message" || read2(item, "role") !== "assistant" || read2(item, "phase") !== "final_answer") {
13195
+ return;
13196
+ }
13197
+ const output = textFromContent(read2(item, "content"));
13198
+ if (output === void 0) {
13199
+ return;
13200
+ }
13201
+ const turnId = stringValue(read2(item, "turn_id"));
13202
+ const subagentId = turnId ? recordValue(state.turnSubagents, turnId) : void 0;
13203
+ if (subagentId) {
13204
+ (await startSubagentSpan(state, subagentId)).log({ output });
13205
+ } else {
13206
+ startRootSpan(state).log({ output });
13207
+ }
13208
+ }
13209
+ async function captureItem(state, item, isDone, observedAt) {
13210
+ await captureMessage(state, item);
13211
+ const itemType = stringValue(read2(item, "type"));
13212
+ if (itemType === "function_call_output") {
13213
+ const callId = stringValue(read2(item, "call_id"));
13214
+ const itemId = callId ? recordValue(state.callItems, callId) : void 0;
13215
+ const tool2 = itemId ? recordValue(state.openTools, itemId) : void 0;
13216
+ if (tool2) {
13217
+ await completeTool(state, tool2, item, observedAt);
13218
+ }
13219
+ return;
13220
+ }
13221
+ const descriptor = toolFromItem(item, observedAt);
13222
+ if (!descriptor) {
13223
+ return;
13224
+ }
13225
+ const existing = recordValue(state.openTools, descriptor.tool.itemId);
13226
+ const tool = existing ?? descriptor.tool;
13227
+ setRecordValue(state.openTools, tool.itemId, tool);
13228
+ if (itemType === "function_call") {
13229
+ const callId = stringValue(read2(item, "call_id"));
13230
+ if (callId) {
13231
+ setRecordValue(state.callItems, callId, tool.itemId);
13232
+ }
13233
+ }
13234
+ await startToolSpan(state, tool, descriptor.input);
13235
+ const status = read2(item, "status");
13236
+ const terminalFunctionCall = itemType === "function_call" && (status === "failed" || status === "incomplete");
13237
+ if (itemType !== "function_call" && (isDone || status !== "in_progress") || terminalFunctionCall) {
13238
+ await completeTool(state, tool, item, observedAt);
13239
+ }
13240
+ }
13241
+ function updateSessionMetadata(state, session) {
13242
+ const sessionId = stringValue(read2(session, "id"));
13243
+ const agent = read2(session, "agent");
13244
+ startRootSpan(state).log({
13245
+ metadata: {
13246
+ ...sessionId ? { session_id: sessionId } : {},
13247
+ ...stringValue(read2(agent, "id")) ? { agent_id: read2(agent, "id") } : {},
13248
+ ...stringValue(read2(agent, "name")) ? { agent_name: read2(agent, "name") } : {},
13249
+ ...stringValue(read2(agent, "model")) ? { model: read2(agent, "model") } : {}
13250
+ }
13251
+ });
13252
+ }
13253
+ async function captureSubagent(state, eventType, subagent, observedAt) {
13254
+ const subagentId = stringValue(read2(subagent, "id"));
13255
+ if (!subagentId) {
13256
+ return;
13257
+ }
13258
+ const existing = recordValue(state.subagents, subagentId);
13259
+ const observedOpenedAt = read2(subagent, "opened_at");
13260
+ const openedAt = typeof observedOpenedAt === "number" && Number.isFinite(observedOpenedAt) && observedOpenedAt >= 0 ? observedOpenedAt : existing?.openedAt ?? observedAt;
13261
+ const observedClosedAt = read2(subagent, "closed_at");
13262
+ const closedAt = typeof observedClosedAt === "number" && Number.isFinite(observedClosedAt) && observedClosedAt >= 0 ? observedClosedAt : existing?.closedAt;
13263
+ const parentAgentId = stringValue(read2(subagent, "parent_agent_id")) ?? existing?.parentAgentId;
13264
+ setRecordValue(state.subagents, subagentId, {
13265
+ ...closedAt !== void 0 ? { closedAt } : {},
13266
+ openedAt,
13267
+ ...parentAgentId ? { parentAgentId } : {}
13268
+ });
13269
+ const span = await startSubagentSpan(
13270
+ state,
13271
+ subagentId,
13272
+ read2(subagent, "instructions"),
13273
+ {
13274
+ ...stringValue(read2(subagent, "name")) ? { agent_name: read2(subagent, "name") } : {},
13275
+ status: read2(subagent, "status")
13276
+ }
13277
+ );
13278
+ if (eventType === "agent.session.subagent.closed") {
13279
+ span.end({ endTime: closedAt ?? observedAt });
13280
+ }
13281
+ }
13282
+ async function closeTrace(state, endTime, error, usage) {
13283
+ if (state.ended) {
13284
+ return;
13285
+ }
13286
+ for (const tool of Object.values(state.openTools)) {
13287
+ const span = await startToolSpan(state, tool);
13288
+ span.log({
13289
+ error: error ?? new Error("OpenAI Agents turn ended before tool completion")
13290
+ });
13291
+ span.end({ endTime });
13292
+ }
13293
+ state.openTools = {};
13294
+ for (const subagentId of Object.keys(state.subagents)) {
13295
+ const subagent = state.subagents[subagentId];
13296
+ const span = await startSubagentSpan(state, subagentId);
13297
+ span.end({ endTime: subagent.closedAt ?? endTime });
13298
+ }
13299
+ const root = startRootSpan(state);
13300
+ root.log({
13301
+ ...error ? { error } : {},
13302
+ metrics: parseMetricsFromUsage(usage)
13303
+ });
13304
+ root.end({ endTime });
13305
+ state.ended = true;
13306
+ }
13307
+ async function captureTurnLifecycle(state, event, eventType, observedAt) {
13308
+ const turn = read2(event, "turn");
13309
+ const turnId = stringValue(read2(event, "turn_id")) ?? stringValue(read2(turn, "id"));
13310
+ const subagentId = stringValue(read2(turn, "subagent_id"));
13311
+ if (turnId && subagentId) {
13312
+ setRecordValue(state.turnSubagents, turnId, subagentId);
13313
+ if (!recordValue(state.subagents, subagentId)) {
13314
+ const createdAt = read2(turn, "created_at");
13315
+ setRecordValue(state.subagents, subagentId, {
13316
+ openedAt: typeof createdAt === "number" && Number.isFinite(createdAt) && createdAt >= 0 ? createdAt : observedAt
13317
+ });
13318
+ }
13319
+ await startSubagentSpan(state, subagentId);
13320
+ }
13321
+ const sessionId = stringValue(read2(event, "session_id"));
13322
+ if (sessionId) {
13323
+ startRootSpan(state).log({ metadata: { session_id: sessionId } });
13324
+ }
13325
+ if (!TERMINAL_TURN_EVENTS.has(eventType) || subagentId) {
13326
+ if (subagentId && eventType === "agent.session.turn.failed") {
13327
+ (await startSubagentSpan(state, subagentId)).log({
13328
+ error: loggedError(read2(turn, "error"), "OpenAI subagent turn failed")
13329
+ });
13330
+ }
13331
+ return;
13332
+ }
13333
+ const completedAt = read2(turn, "completed_at");
13334
+ const endTime = typeof completedAt === "number" && Number.isFinite(completedAt) && completedAt >= 0 ? completedAt : observedAt;
13335
+ const usage = read2(event, "usage") ?? read2(turn, "usage");
13336
+ const error = eventType === "agent.session.turn.completed" ? void 0 : loggedError(
13337
+ read2(turn, "error"),
13338
+ eventType === "agent.session.turn.cancelled" ? "OpenAI Agents turn cancelled" : "OpenAI Agents turn failed"
13339
+ );
13340
+ await closeTrace(state, endTime, error, usage);
13341
+ }
13342
+ async function captureEvent(state, event) {
13343
+ if (state.ended) {
13344
+ return state;
13345
+ }
13346
+ const eventType = stringValue(read2(event, "type"));
13347
+ const eventId = stringValue(read2(event, "event_id"));
13348
+ if (!eventType || eventId && state.eventIds.includes(eventId)) {
13349
+ return state;
13350
+ }
13351
+ const next = copyState(state);
13352
+ const observedAt = getCurrentUnixTimestamp();
13353
+ let handled = false;
13354
+ if (SESSION_EVENTS.has(eventType)) {
13355
+ const session = read2(event, "session");
13356
+ if (session) {
13357
+ updateSessionMetadata(next, session);
13358
+ }
13359
+ handled = true;
13360
+ }
13361
+ if (eventType === "agent.session.turn.item.added") {
13362
+ await captureItem(next, read2(event, "item"), false, observedAt);
13363
+ handled = true;
13364
+ } else if (eventType === "agent.session.turn.item.done") {
13365
+ await captureItem(next, read2(event, "item"), true, observedAt);
13366
+ handled = true;
13367
+ } else if (TURN_LIFECYCLE_EVENTS.has(eventType)) {
13368
+ await captureTurnLifecycle(next, event, eventType, observedAt);
13369
+ handled = true;
13370
+ } else if (SUBAGENT_EVENTS.has(eventType)) {
13371
+ await captureSubagent(next, eventType, read2(event, "subagent"), observedAt);
13372
+ handled = true;
13373
+ } else if (eventType === "agent.session.turn.output_text.delta" && next.firstTokenAt === void 0 && stringValue(read2(event, "delta"))) {
13374
+ next.firstTokenAt = observedAt;
13375
+ startRootSpan(next).log({
13376
+ metrics: { time_to_first_token: observedAt - next.startTime }
13377
+ });
13378
+ handled = true;
13379
+ } else if (eventType === "agent.session.failed") {
13380
+ const session = read2(event, "session");
13381
+ const lastActiveAt = read2(session, "last_active_at");
13382
+ const endTime = typeof lastActiveAt === "number" && Number.isFinite(lastActiveAt) && lastActiveAt >= 0 ? lastActiveAt : observedAt;
13383
+ await closeTrace(
13384
+ next,
13385
+ endTime,
13386
+ loggedError(read2(session, "error"), "OpenAI Agents session failed"),
13387
+ read2(session, "usage")
13388
+ );
13389
+ handled = true;
13390
+ } else if (eventType === "error") {
13391
+ await closeTrace(
13392
+ next,
13393
+ observedAt,
13394
+ loggedError(read2(event, "error"), "OpenAI Agents session failed")
13395
+ );
13396
+ handled = true;
13397
+ }
13398
+ if (!handled) {
13399
+ return state;
13400
+ }
13401
+ if (eventId) {
13402
+ next.eventIds.push(eventId);
13403
+ }
13404
+ return next;
13405
+ }
13406
+ var interceptOpenAIAgentsTraceStart = async (target, thisArg, args) => {
13407
+ const fallback = await Reflect.apply(target, thisArg, args);
13408
+ try {
13409
+ const state = args[0].state;
13410
+ const parent = state.rootParent;
13411
+ const traceArgs = args[0].args;
13412
+ const parentComponents = SpanComponentsV4.fromStr(parent);
13413
+ const hasParentSpan = Boolean(
13414
+ parentComponents.data.row_id && parentComponents.data.span_id && parentComponents.data.root_span_id
13415
+ );
13416
+ const rootComponents = SpanComponentsV4.fromStr(state.root);
13417
+ const rowId = stringValue(rootComponents.data.row_id);
13418
+ const rootSpanId = stringValue(rootComponents.data.root_span_id);
13419
+ const spanId = stringValue(rootComponents.data.span_id);
13420
+ if (!rowId || !rootSpanId || !spanId) {
13421
+ throw new Error("OpenAI Agents trace root is invalid");
13422
+ }
13423
+ withCurrent(
13424
+ NOOP_SPAN,
13425
+ () => _internalStartSpanWithInitialMergeAndParentSpanIds(
13426
+ withSpanInstrumentationName(
13427
+ {
13428
+ name: "openai.agents.turn",
13429
+ type: "task" /* TASK */,
13430
+ parent,
13431
+ ...!hasParentSpan ? {
13432
+ parentSpanIds: {
13433
+ parentSpanIds: [],
13434
+ rootSpanId
13435
+ }
13436
+ } : {},
13437
+ spanId,
13438
+ startTime: state.startTime,
13439
+ event: {
13440
+ id: rowId,
13441
+ input: read2(traceArgs, "input"),
13442
+ metadata: traceMetadata(traceArgs)
13443
+ }
13444
+ },
13445
+ INSTRUMENTATION_NAMES.OPENAI
13446
+ )
13447
+ )
13448
+ );
13449
+ return state;
13450
+ } catch (error) {
13451
+ logInstrumentationError("could not start trace", error);
13452
+ return fallback;
13453
+ }
13454
+ };
13455
+ var interceptOpenAIAgentsTraceCapture = async (target, thisArg, args) => {
13456
+ const fallback = await Reflect.apply(target, thisArg, args);
13457
+ if (!args[0].state) {
13458
+ return fallback;
13459
+ }
13460
+ try {
13461
+ return await captureEvent(args[0].state, args[0].event);
13462
+ } catch (error) {
13463
+ logInstrumentationError("could not capture event", error);
13464
+ return fallback;
13465
+ }
13466
+ };
13467
+ var interceptOpenAIAgentsTraceFail = async (target, thisArg, args) => {
13468
+ const fallback = await Reflect.apply(target, thisArg, args);
13469
+ if (!args[0].state) {
13470
+ return fallback;
13471
+ }
13472
+ try {
13473
+ const next = copyState(args[0].state);
13474
+ await closeTrace(
13475
+ next,
13476
+ getCurrentUnixTimestamp(),
13477
+ loggedError(args[0].error, "OpenAI Agents request failed")
13478
+ );
13479
+ return next;
13480
+ } catch (error) {
13481
+ logInstrumentationError("could not fail trace", error);
13482
+ return fallback;
13483
+ }
13484
+ };
13485
+
12790
13486
  // src/instrumentation/plugins/openai-plugin.ts
12791
13487
  var OpenAIPlugin = class extends BasePlugin {
12792
13488
  constructor() {
@@ -12794,6 +13490,13 @@ var OpenAIPlugin = class extends BasePlugin {
12794
13490
  }
12795
13491
  onEnable() {
12796
13492
  this.unsubscribers.push(
13493
+ openAIChannels.agentsTraceStart.intercept(
13494
+ interceptOpenAIAgentsTraceStart
13495
+ ),
13496
+ openAIChannels.agentsTraceCapture.intercept(
13497
+ interceptOpenAIAgentsTraceCapture
13498
+ ),
13499
+ openAIChannels.agentsTraceFail.intercept(interceptOpenAIAgentsTraceFail),
12797
13500
  openAIChannels.filesCreateTraced.intercept(
12798
13501
  interceptOpenAIFilesCreateTraced
12799
13502
  ),
@@ -13354,7 +14057,7 @@ async function* patchCodexEventStream(events, state) {
13354
14057
  try {
13355
14058
  await handleCodexEvent(state, event);
13356
14059
  } catch (error) {
13357
- logInstrumentationError("OpenAI Codex stream event", error);
14060
+ logInstrumentationError2("OpenAI Codex stream event", error);
13358
14061
  }
13359
14062
  yield event;
13360
14063
  }
@@ -13854,10 +14557,10 @@ function safeLog(span, event) {
13854
14557
  try {
13855
14558
  span.log(event);
13856
14559
  } catch (error) {
13857
- logInstrumentationError("OpenAI Codex span log", error);
14560
+ logInstrumentationError2("OpenAI Codex span log", error);
13858
14561
  }
13859
14562
  }
13860
- function logInstrumentationError(context, error) {
14563
+ function logInstrumentationError2(context, error) {
13861
14564
  debugLogger.error(`Error processing ${context}:`, error);
13862
14565
  }
13863
14566
 
@@ -15239,27 +15942,8 @@ function continuationParentFromCreateSessionParams(params) {
15239
15942
  }
15240
15943
  return context.parent;
15241
15944
  }
15242
- function exportSpanSynchronously(span) {
15243
- const parentInfo = span.getParentInfo();
15244
- if (!parentInfo) {
15245
- return void 0;
15246
- }
15247
- const objectId = parentInfo.objectId.getSync().value;
15248
- if (!objectId && !parentInfo.computeObjectMetadataArgs) {
15249
- return void 0;
15250
- }
15251
- return new SpanComponentsV4({
15252
- object_type: parentInfo.objectType,
15253
- ...objectId ? { object_id: objectId } : {
15254
- compute_object_metadata_args: parentInfo.computeObjectMetadataArgs ?? {}
15255
- },
15256
- row_id: span.id,
15257
- root_span_id: span.rootSpanId,
15258
- span_id: span.spanId
15259
- }).toStr();
15260
- }
15261
15945
  function exportedParent(parent) {
15262
- return typeof parent === "string" ? parent : exportSpanSynchronously(parent);
15946
+ return typeof parent === "string" ? parent : _internalExportParentSynchronously(parent);
15263
15947
  }
15264
15948
  function addSerializedContext(args) {
15265
15949
  if (!isObject(args.continuation) || args.sessionId === void 0) {
@@ -16016,16 +16700,16 @@ function braintrustAISDKTelemetry() {
16016
16700
  if (!toolCallId || !state) {
16017
16701
  return;
16018
16702
  }
16019
- const toolOutput = event.toolOutput;
16703
+ const toolOutput2 = event.toolOutput;
16020
16704
  const workflowToolError = event.success === false && "error" in event ? event.error : void 0;
16021
- if (toolOutput?.type === "tool-error" || workflowToolError !== void 0) {
16022
- const error = toolOutput?.error ?? workflowToolError;
16705
+ if (toolOutput2?.type === "tool-error" || workflowToolError !== void 0) {
16706
+ const error = toolOutput2?.error ?? workflowToolError;
16023
16707
  state.span.log({
16024
16708
  error: error instanceof Error ? error.message : String(error),
16025
16709
  metrics: typeof event.durationMs === "number" ? { duration_ms: event.durationMs } : {}
16026
16710
  });
16027
16711
  } else {
16028
- const output = toolOutput && "output" in toolOutput ? toolOutput.output : event.output;
16712
+ const output = toolOutput2 && "output" in toolOutput2 ? toolOutput2.output : event.output;
16029
16713
  state.span.log({
16030
16714
  ...shouldRecordOutputs(event) ? { output } : {},
16031
16715
  metrics: typeof event.durationMs === "number" ? { duration_ms: event.durationMs } : {}
@@ -18484,9 +19168,9 @@ function patchAISDKStreamingResult(args) {
18484
19168
  }
18485
19169
  finalize({ metrics, output });
18486
19170
  } catch (error) {
18487
- const loggedError = toLoggedError(error);
19171
+ const loggedError2 = toLoggedError(error);
18488
19172
  try {
18489
- span.log({ error: loggedError });
19173
+ span.log({ error: loggedError2 });
18490
19174
  } catch (loggingError) {
18491
19175
  debugLogger.error(
18492
19176
  "Error logging AI SDK streaming failure:",
@@ -18494,7 +19178,7 @@ function patchAISDKStreamingResult(args) {
18494
19178
  );
18495
19179
  }
18496
19180
  finalize({
18497
- error: error instanceof Error ? error : new Error(String(loggedError))
19181
+ error: error instanceof Error ? error : new Error(String(loggedError2))
18498
19182
  });
18499
19183
  }
18500
19184
  };
@@ -18607,9 +19291,9 @@ function patchAISDKStreamingResult(args) {
18607
19291
  }
18608
19292
  controller.enqueue(value);
18609
19293
  } catch (error) {
18610
- const loggedError = toLoggedError(error);
19294
+ const loggedError2 = toLoggedError(error);
18611
19295
  try {
18612
- span.log({ error: loggedError });
19296
+ span.log({ error: loggedError2 });
18613
19297
  } catch (loggingError) {
18614
19298
  debugLogger.error(
18615
19299
  "Error logging AI SDK base stream failure:",
@@ -18617,7 +19301,7 @@ function patchAISDKStreamingResult(args) {
18617
19301
  );
18618
19302
  }
18619
19303
  finalize({
18620
- error: error instanceof Error ? error : new Error(String(loggedError))
19304
+ error: error instanceof Error ? error : new Error(String(loggedError2))
18621
19305
  });
18622
19306
  controller.error(error);
18623
19307
  }
@@ -21511,7 +22195,7 @@ function wrapSendOptionsCallbacks(options, state) {
21511
22195
  try {
21512
22196
  await handleInteractionUpdate(state, args.update);
21513
22197
  } catch (error) {
21514
- logInstrumentationError2("Cursor SDK onDelta", error);
22198
+ logInstrumentationError3("Cursor SDK onDelta", error);
21515
22199
  }
21516
22200
  if (originalOnDelta) {
21517
22201
  return originalOnDelta(args);
@@ -21521,7 +22205,7 @@ function wrapSendOptionsCallbacks(options, state) {
21521
22205
  try {
21522
22206
  handleStepUpdate(state, args.step);
21523
22207
  } catch (error) {
21524
- logInstrumentationError2("Cursor SDK onStep", error);
22208
+ logInstrumentationError3("Cursor SDK onStep", error);
21525
22209
  }
21526
22210
  if (originalOnStep) {
21527
22211
  return originalOnStep(args);
@@ -21603,7 +22287,7 @@ async function* patchCursorStream(stream, state) {
21603
22287
  try {
21604
22288
  await handleStreamMessage2(state, message);
21605
22289
  } catch (error) {
21606
- logInstrumentationError2("Cursor SDK stream", error);
22290
+ logInstrumentationError3("Cursor SDK stream", error);
21607
22291
  }
21608
22292
  yield message;
21609
22293
  }
@@ -21667,7 +22351,7 @@ async function handleToolUpdate(state, update) {
21667
22351
  if (!state.activeToolSpans.has(callId)) {
21668
22352
  state.activeToolSpans.set(
21669
22353
  callId,
21670
- await startToolSpan(state, {
22354
+ await startToolSpan2(state, {
21671
22355
  args,
21672
22356
  callId,
21673
22357
  name,
@@ -21678,7 +22362,7 @@ async function handleToolUpdate(state, update) {
21678
22362
  }
21679
22363
  return;
21680
22364
  }
21681
- const toolState = state.activeToolSpans.get(callId) ?? await startToolSpan(state, {
22365
+ const toolState = state.activeToolSpans.get(callId) ?? await startToolSpan2(state, {
21682
22366
  args,
21683
22367
  callId,
21684
22368
  name,
@@ -21715,7 +22399,7 @@ async function handleStreamMessage2(state, message) {
21715
22399
  } else if (block?.type === "tool_use" && block.id) {
21716
22400
  state.activeToolSpans.set(
21717
22401
  block.id,
21718
- await startToolSpan(state, {
22402
+ await startToolSpan2(state, {
21719
22403
  args: block.input,
21720
22404
  callId: block.id,
21721
22405
  name: block.name,
@@ -21750,7 +22434,7 @@ async function handleToolMessage(state, message) {
21750
22434
  if (!state.activeToolSpans.has(callId)) {
21751
22435
  state.activeToolSpans.set(
21752
22436
  callId,
21753
- await startToolSpan(state, {
22437
+ await startToolSpan2(state, {
21754
22438
  args: message.args,
21755
22439
  callId,
21756
22440
  name: message.name,
@@ -21761,7 +22445,7 @@ async function handleToolMessage(state, message) {
21761
22445
  }
21762
22446
  return;
21763
22447
  }
21764
- const toolState = state.activeToolSpans.get(callId) ?? await startToolSpan(state, {
22448
+ const toolState = state.activeToolSpans.get(callId) ?? await startToolSpan2(state, {
21765
22449
  args: message.args,
21766
22450
  callId,
21767
22451
  name: message.name,
@@ -21788,7 +22472,7 @@ async function handleConversation(state, turns) {
21788
22472
  const command = turn.turn?.shellCommand?.command;
21789
22473
  if (command) {
21790
22474
  const callId = `shell:${state.activeToolSpans.size}:${command}`;
21791
- const toolState = await startToolSpan(state, {
22475
+ const toolState = await startToolSpan2(state, {
21792
22476
  args: turn.turn?.shellCommand,
21793
22477
  callId,
21794
22478
  name: "shell",
@@ -21812,7 +22496,7 @@ async function handleConversationStep(state, step) {
21812
22496
  }
21813
22497
  const toolCall = step.message;
21814
22498
  const callId = typeof toolCall?.callId === "string" ? toolCall.callId : `conversation-tool:${state.activeToolSpans.size}`;
21815
- const toolState = await startToolSpan(state, {
22499
+ const toolState = await startToolSpan2(state, {
21816
22500
  args: extractToolArgs(toolCall),
21817
22501
  callId,
21818
22502
  name: extractToolName(toolCall),
@@ -21843,7 +22527,7 @@ function handleStepUpdate(state, step) {
21843
22527
  state.stepText.push(step.message.text);
21844
22528
  }
21845
22529
  }
21846
- async function startToolSpan(state, args) {
22530
+ async function startToolSpan2(state, args) {
21847
22531
  const name = args.name || "unknown";
21848
22532
  const metadata = {
21849
22533
  "cursor_sdk.tool.status": args.status,
@@ -22130,10 +22814,10 @@ function safeLog2(span, event) {
22130
22814
  try {
22131
22815
  span.log(event);
22132
22816
  } catch (error) {
22133
- logInstrumentationError2("Cursor SDK span log", error);
22817
+ logInstrumentationError3("Cursor SDK span log", error);
22134
22818
  }
22135
22819
  }
22136
- function logInstrumentationError2(context, error) {
22820
+ function logInstrumentationError3(context, error) {
22137
22821
  debugLogger.error(`Error processing ${context}:`, error);
22138
22822
  }
22139
22823
  function cleanMetrics2(metrics) {
@@ -22619,6 +23303,342 @@ var OpenAIAgentsPlugin = class extends BasePlugin {
22619
23303
  }
22620
23304
  };
22621
23305
 
23306
+ // src/instrumentation/plugins/google-generative-ai-channels.ts
23307
+ var googleGenerativeAIChannels = defineChannels(
23308
+ "@google/generative-ai",
23309
+ {
23310
+ generateContent: channel({ channelName: "GenerativeModel.generateContent", kind: "async" }),
23311
+ generateContentStream: channel({ channelName: "GenerativeModel.generateContentStream", kind: "async" }),
23312
+ embedContent: channel({ channelName: "GenerativeModel.embedContent", kind: "async" }),
23313
+ batchEmbedContents: channel({ channelName: "GenerativeModel.batchEmbedContents", kind: "async" }),
23314
+ sendMessage: channel({ channelName: "ChatSession.sendMessage", kind: "async" }),
23315
+ sendMessageStream: channel({ channelName: "ChatSession.sendMessageStream", kind: "async" })
23316
+ },
23317
+ { instrumentationName: INSTRUMENTATION_NAMES.GOOGLE_GENERATIVE_AI }
23318
+ );
23319
+
23320
+ // src/instrumentation/plugins/google-generative-ai-plugin.ts
23321
+ var GENERATION_CONFIG_KEYS = [
23322
+ "temperature",
23323
+ "topP",
23324
+ "topK",
23325
+ "candidateCount",
23326
+ "maxOutputTokens",
23327
+ "stopSequences",
23328
+ "responseMimeType",
23329
+ "responseSchema",
23330
+ "presencePenalty",
23331
+ "frequencyPenalty",
23332
+ "responseLogprobs",
23333
+ "logprobs",
23334
+ "thinkingConfig"
23335
+ ];
23336
+ var GoogleGenerativeAIPlugin = class extends BasePlugin {
23337
+ onEnable() {
23338
+ this.unsubscribers.push(
23339
+ interceptCall(
23340
+ googleGenerativeAIChannels.generateContent,
23341
+ "generateContent"
23342
+ ),
23343
+ interceptCall(
23344
+ googleGenerativeAIChannels.generateContentStream,
23345
+ "generateContentStream"
23346
+ ),
23347
+ interceptCall(googleGenerativeAIChannels.sendMessage, "sendMessage"),
23348
+ interceptCall(
23349
+ googleGenerativeAIChannels.sendMessageStream,
23350
+ "sendMessageStream"
23351
+ ),
23352
+ interceptCall(googleGenerativeAIChannels.embedContent, "embedContent"),
23353
+ interceptCall(
23354
+ googleGenerativeAIChannels.batchEmbedContents,
23355
+ "batchEmbedContents"
23356
+ )
23357
+ );
23358
+ }
23359
+ onDisable() {
23360
+ this.unsubscribers = unsubscribeAll(this.unsubscribers);
23361
+ }
23362
+ };
23363
+ function interceptCall(channel2, operation) {
23364
+ return channel2.intercept((target, thisArg, args) => {
23365
+ const invokeTarget = () => Reflect.apply(target, thisArg, args);
23366
+ if (isAutoInstrumentationSuppressed()) return invokeTarget();
23367
+ const self = thisArg;
23368
+ const chat = operation.startsWith("sendMessage");
23369
+ const embedding = operation === "embedContent" || operation === "batchEmbedContents";
23370
+ const start = getCurrentUnixTimestamp();
23371
+ let span;
23372
+ try {
23373
+ span = startSpan(
23374
+ withSpanInstrumentationName(
23375
+ {
23376
+ name: embedding ? operation === "embedContent" ? "embed_content" : "batch_embed_contents" : "generate_content",
23377
+ spanAttributes: { type: "llm" /* LLM */ },
23378
+ event: extractInput(self, args[0], operation)
23379
+ },
23380
+ INSTRUMENTATION_NAMES.GOOGLE_GENERATIVE_AI
23381
+ )
23382
+ );
23383
+ } catch (error) {
23384
+ debugLogger.error("Error starting Google Generative AI span:", error);
23385
+ return invokeTarget();
23386
+ }
23387
+ let ended = false;
23388
+ const finish = (log) => {
23389
+ if (ended) return;
23390
+ ended = true;
23391
+ try {
23392
+ log();
23393
+ } catch (error) {
23394
+ debugLogger.error("Error logging Google Generative AI span:", error);
23395
+ }
23396
+ try {
23397
+ span.end();
23398
+ } catch (error) {
23399
+ debugLogger.error("Error ending Google Generative AI span:", error);
23400
+ }
23401
+ };
23402
+ if (chat) {
23403
+ try {
23404
+ void self._sendPromise.then(
23405
+ () => {
23406
+ try {
23407
+ span.log(extractInput(self, args[0], operation));
23408
+ } catch (error) {
23409
+ debugLogger.error("Error capturing Google chat history:", error);
23410
+ }
23411
+ },
23412
+ () => {
23413
+ }
23414
+ );
23415
+ } catch (error) {
23416
+ debugLogger.error("Error observing Google chat history:", error);
23417
+ }
23418
+ }
23419
+ let result;
23420
+ try {
23421
+ result = withCurrent(
23422
+ span,
23423
+ () => runWithAutoInstrumentationSuppressed(invokeTarget)
23424
+ );
23425
+ } catch (error) {
23426
+ finish(() => span.log({ error }));
23427
+ throw error;
23428
+ }
23429
+ void Promise.resolve(result).then(
23430
+ (value) => {
23431
+ try {
23432
+ if ("stream" in value) {
23433
+ let firstToken = false;
23434
+ const partial = { candidates: [] };
23435
+ const candidates = /* @__PURE__ */ new Map();
23436
+ patchStreamIfNeeded(value.stream, {
23437
+ aroundNext: (callback) => withCurrent(span, callback),
23438
+ onChunk: (chunk) => {
23439
+ for (const candidate of chunk.candidates ?? []) {
23440
+ const index = candidate.index ?? 0;
23441
+ const previous = candidates.get(index);
23442
+ const parts = [...previous?.content?.parts ?? []];
23443
+ for (const part of candidate.content?.parts ?? []) {
23444
+ const last = parts[parts.length - 1];
23445
+ if (part.text !== void 0 && last?.text !== void 0) {
23446
+ parts[parts.length - 1] = {
23447
+ ...last,
23448
+ text: last.text + part.text
23449
+ };
23450
+ } else parts.push(part);
23451
+ }
23452
+ candidates.set(index, {
23453
+ ...previous,
23454
+ ...candidate,
23455
+ content: {
23456
+ role: candidate.content?.role ?? previous?.content?.role ?? "model",
23457
+ parts
23458
+ }
23459
+ });
23460
+ }
23461
+ partial.candidates = Array.from(candidates.values());
23462
+ if (chunk.usageMetadata)
23463
+ partial.usageMetadata = chunk.usageMetadata;
23464
+ if (!firstToken && chunk.candidates?.some(
23465
+ (candidate) => candidate.content?.parts.some(
23466
+ (part) => part.text !== void 0 ? part.text.length > 0 : Object.keys(part).length > 0
23467
+ )
23468
+ )) {
23469
+ firstToken = true;
23470
+ span.log({
23471
+ metrics: {
23472
+ time_to_first_token: getCurrentUnixTimestamp() - start
23473
+ }
23474
+ });
23475
+ }
23476
+ },
23477
+ onComplete: () => {
23478
+ },
23479
+ onError: (error) => finish(() => {
23480
+ logResponse(span, partial);
23481
+ span.log({ error });
23482
+ }),
23483
+ onCancel: () => finish(() => logResponse(span, partial))
23484
+ });
23485
+ void value.response.then(
23486
+ (response) => finish(() => logResponse(span, response)),
23487
+ (error) => finish(() => {
23488
+ logResponse(span, partial);
23489
+ span.log({ error });
23490
+ })
23491
+ );
23492
+ } else if ("response" in value) {
23493
+ finish(() => logResponse(span, value.response));
23494
+ } else {
23495
+ const metrics = {};
23496
+ const promptTokens = value.usageMetadata?.promptTokenCount;
23497
+ if (typeof promptTokens === "number" && Number.isFinite(promptTokens) && promptTokens >= 0) {
23498
+ metrics.prompt_tokens = promptTokens;
23499
+ metrics.tokens = promptTokens;
23500
+ }
23501
+ for (const detail of value.usageMetadata?.promptTokenDetails ?? []) {
23502
+ if (detail.modality === "AUDIO" && typeof detail.tokenCount === "number" && Number.isFinite(detail.tokenCount) && detail.tokenCount >= 0) {
23503
+ metrics.prompt_audio_tokens = (metrics.prompt_audio_tokens ?? 0) + detail.tokenCount;
23504
+ }
23505
+ }
23506
+ finish(
23507
+ () => span.log({
23508
+ metrics,
23509
+ output: {
23510
+ count: value.embeddings?.length ?? (value.embedding ? 1 : 0)
23511
+ }
23512
+ })
23513
+ );
23514
+ }
23515
+ } catch (error) {
23516
+ debugLogger.error(
23517
+ "Error observing Google Generative AI result:",
23518
+ error
23519
+ );
23520
+ finish(() => {
23521
+ });
23522
+ }
23523
+ },
23524
+ (error) => finish(() => span.log({ error }))
23525
+ );
23526
+ return result;
23527
+ });
23528
+ }
23529
+ function normalizeContent(message) {
23530
+ const parts = (typeof message === "string" ? [message] : message).map(
23531
+ (part) => typeof part === "string" ? { text: part } : part
23532
+ );
23533
+ return {
23534
+ role: parts.some((part) => part.functionResponse) ? "function" : "user",
23535
+ parts
23536
+ };
23537
+ }
23538
+ function extractInput(self, request, operation) {
23539
+ const model = self.model.replace(/^models\//, "");
23540
+ if (operation === "embedContent" || operation === "batchEmbedContents") {
23541
+ const requests = operation === "batchEmbedContents" ? request.requests : [
23542
+ typeof request === "string" || Array.isArray(request) ? { content: normalizeContent(request) } : request
23543
+ ];
23544
+ const dimensions = requests[0]?.outputDimensionality;
23545
+ return {
23546
+ input: {
23547
+ inputs: convertAttachments(requests).map((item) => ({
23548
+ content: item.content.parts.length === 1 && item.content.parts[0].text !== void 0 ? item.content.parts[0].text : item.content.parts.map((part) => {
23549
+ if (part.text !== void 0)
23550
+ return { type: "text", text: part.text };
23551
+ const mimeType = part.inlineData?.mimeType ?? part.fileData?.mimeType;
23552
+ const data = part.inlineData ? typeof part.inlineData.data === "string" ? `data:${mimeType};base64,${part.inlineData.data}` : part.inlineData.data : part.fileData?.fileUri;
23553
+ return mimeType?.startsWith("image/") ? { type: "image_url", image_url: { url: data } } : { type: "file", file: { file_data: data } };
23554
+ })
23555
+ })),
23556
+ ...dimensions !== void 0 && requests.every((item) => item.outputDimensionality === dimensions) ? { output_dimensions: dimensions } : {}
23557
+ },
23558
+ metadata: { model, provider: "google" }
23559
+ };
23560
+ }
23561
+ const chat = operation.startsWith("sendMessage");
23562
+ const config = chat ? self.params ?? {} : self;
23563
+ const params = typeof request === "string" || Array.isArray(request) ? { contents: [normalizeContent(request)] } : request;
23564
+ const system = params.systemInstruction ?? config.systemInstruction;
23565
+ const systemContent = typeof system === "string" ? { role: "system", parts: [{ text: system }] } : system && "parts" in system ? { ...system, role: "system" } : system ? { role: "system", parts: [system] } : void 0;
23566
+ const contents = [
23567
+ ...systemContent ? [systemContent] : [],
23568
+ ...chat ? self._history : [],
23569
+ ...params.contents
23570
+ ];
23571
+ const metadata = { model, provider: "google" };
23572
+ const generation = params.generationConfig ?? config.generationConfig;
23573
+ for (const key of GENERATION_CONFIG_KEYS) {
23574
+ if (generation && Object.hasOwn(generation, key))
23575
+ metadata[key] = generation[key];
23576
+ }
23577
+ for (const key of ["tools", "toolConfig", "safetySettings"]) {
23578
+ const value = params[key] ?? config[key];
23579
+ if (value !== void 0) metadata[key] = value;
23580
+ }
23581
+ const cached = params.cachedContent ?? config.cachedContent;
23582
+ if (cached)
23583
+ metadata.cachedContent = typeof cached === "string" ? cached : cached.name;
23584
+ return { input: convertAttachments({ model, contents }), metadata };
23585
+ }
23586
+ function convertAttachments(value) {
23587
+ const convert = (node) => {
23588
+ if (Array.isArray(node)) return node.map(convert);
23589
+ if (!isObject(node)) return node;
23590
+ if (isObject(node.inlineData)) {
23591
+ const { data, mimeType } = node.inlineData;
23592
+ const processed = processInputAttachments({
23593
+ type: "file",
23594
+ file: { file_data: `data:${mimeType};base64,${data}` }
23595
+ });
23596
+ if (typeof processed.file.file_data === "string")
23597
+ throw new Error("Unable to convert Google inline data");
23598
+ return {
23599
+ ...node,
23600
+ inlineData: { ...node.inlineData, data: processed.file.file_data }
23601
+ };
23602
+ }
23603
+ return Object.fromEntries(
23604
+ Object.entries(node).map(([key, item]) => [key, convert(item)])
23605
+ );
23606
+ };
23607
+ try {
23608
+ return convert(value);
23609
+ } catch (error) {
23610
+ debugLogger.error(
23611
+ "Error converting Google Generative AI attachments:",
23612
+ error
23613
+ );
23614
+ return value;
23615
+ }
23616
+ }
23617
+ function logResponse(span, response) {
23618
+ const usage = response.usageMetadata;
23619
+ const metrics = {};
23620
+ if (usage) {
23621
+ if (usage.promptTokenCount !== void 0)
23622
+ metrics.prompt_tokens = usage.promptTokenCount;
23623
+ if (usage.candidatesTokenCount !== void 0 || usage.thoughtsTokenCount !== void 0)
23624
+ metrics.completion_tokens = (usage.candidatesTokenCount ?? 0) + (usage.thoughtsTokenCount ?? 0);
23625
+ if (usage.totalTokenCount !== void 0)
23626
+ metrics.tokens = usage.totalTokenCount;
23627
+ if (usage.cachedContentTokenCount !== void 0)
23628
+ metrics.prompt_cached_tokens = usage.cachedContentTokenCount;
23629
+ if (usage.thoughtsTokenCount !== void 0)
23630
+ metrics.completion_reasoning_tokens = usage.thoughtsTokenCount;
23631
+ }
23632
+ span.log({
23633
+ output: convertAttachments({
23634
+ candidates: response.candidates,
23635
+ promptFeedback: response.promptFeedback
23636
+ }),
23637
+ metrics,
23638
+ ...response.modelVersion ? { metadata: { model: response.modelVersion } } : {}
23639
+ });
23640
+ }
23641
+
22622
23642
  // src/instrumentation/plugins/google-genai-channels.ts
22623
23643
  var googleGenAIChannels = defineChannels(
22624
23644
  "@google/genai",
@@ -22635,6 +23655,10 @@ var googleGenAIChannels = defineChannels(
22635
23655
  channelName: "models.embedContent",
22636
23656
  kind: "async"
22637
23657
  }),
23658
+ httpResponseJson: channel({
23659
+ channelName: "httpResponse.json",
23660
+ kind: "async"
23661
+ }),
22638
23662
  interactionsCreate: channel({
22639
23663
  channelName: "interactions.create",
22640
23664
  kind: "async"
@@ -22783,13 +23807,45 @@ var GoogleGenAIPlugin = class extends BasePlugin {
22783
23807
  subscribeToEmbedContentChannel() {
22784
23808
  const tracingChannel = googleGenAIChannels.embedContent.tracingChannel();
22785
23809
  const states = /* @__PURE__ */ new WeakMap();
23810
+ const embeddingSpans = /* @__PURE__ */ new WeakSet();
23811
+ this.unsubscribers.push(
23812
+ googleGenAIChannels.httpResponseJson.intercept(
23813
+ (target, thisArg, args) => {
23814
+ const span = currentSpan();
23815
+ const result = Reflect.apply(target, thisArg, args);
23816
+ if (embeddingSpans.has(span)) {
23817
+ void Promise.resolve(result).then(
23818
+ (response) => {
23819
+ try {
23820
+ const metrics = cleanMetrics3(
23821
+ extractEmbedContentMetrics(response)
23822
+ );
23823
+ if (embeddingSpans.has(span) && Object.keys(metrics).length > 0) {
23824
+ span.log({ metrics });
23825
+ }
23826
+ } catch (error) {
23827
+ debugLogger.error(
23828
+ "Error reading Google GenAI embedding usage:",
23829
+ error
23830
+ );
23831
+ }
23832
+ },
23833
+ () => {
23834
+ }
23835
+ // The embedding channel handles the original rejection.
23836
+ );
23837
+ }
23838
+ return result;
23839
+ }
23840
+ )
23841
+ );
22786
23842
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart2(
22787
23843
  tracingChannel,
22788
23844
  states,
22789
23845
  (event) => {
22790
23846
  const params = event.arguments[0];
22791
23847
  const input = serializeEmbedContentInput(params);
22792
- const metadata = extractEmbedContentMetadata(params);
23848
+ const metadata = { provider: "google", model: params.model };
22793
23849
  const span = startSpan(
22794
23850
  withSpanInstrumentationName(
22795
23851
  {
@@ -22802,6 +23858,7 @@ var GoogleGenAIPlugin = class extends BasePlugin {
22802
23858
  INSTRUMENTATION_NAMES.GOOGLE_GENAI
22803
23859
  )
22804
23860
  );
23861
+ embeddingSpans.add(span);
22805
23862
  return {
22806
23863
  span,
22807
23864
  startTime: getCurrentUnixTimestamp()
@@ -22813,7 +23870,7 @@ var GoogleGenAIPlugin = class extends BasePlugin {
22813
23870
  ensureSpanState(states, event, () => {
22814
23871
  const params = event.arguments[0];
22815
23872
  const input = serializeEmbedContentInput(params);
22816
- const metadata = extractEmbedContentMetadata(params);
23873
+ const metadata = { provider: "google", model: params.model };
22817
23874
  const span = startSpan(
22818
23875
  withSpanInstrumentationName(
22819
23876
  {
@@ -22826,6 +23883,7 @@ var GoogleGenAIPlugin = class extends BasePlugin {
22826
23883
  INSTRUMENTATION_NAMES.GOOGLE_GENAI
22827
23884
  )
22828
23885
  );
23886
+ embeddingSpans.add(span);
22829
23887
  return {
22830
23888
  span,
22831
23889
  startTime: getCurrentUnixTimestamp()
@@ -22838,20 +23896,28 @@ var GoogleGenAIPlugin = class extends BasePlugin {
22838
23896
  return;
22839
23897
  }
22840
23898
  try {
22841
- const output = summarizeEmbedContentOutput(event.result);
22842
23899
  spanState.span.log({
22843
- ...output ? { output } : {},
23900
+ output: summarizeEmbedContentOutput(event.result),
22844
23901
  metrics: cleanMetrics3(
22845
23902
  extractEmbedContentMetrics(event.result, spanState.startTime)
22846
23903
  )
22847
23904
  });
22848
23905
  } finally {
23906
+ embeddingSpans.delete(spanState.span);
22849
23907
  spanState.span.end();
22850
23908
  states.delete(event);
22851
23909
  }
22852
23910
  },
22853
23911
  error: (event) => {
22854
- logErrorAndEndSpan(states, event);
23912
+ const spanState = states.get(event);
23913
+ if (!spanState) return;
23914
+ try {
23915
+ spanState.span.log({ error: event.error, output: { count: 0 } });
23916
+ } finally {
23917
+ embeddingSpans.delete(spanState.span);
23918
+ spanState.span.end();
23919
+ states.delete(event);
23920
+ }
22855
23921
  }
22856
23922
  };
22857
23923
  tracingChannel.subscribe(handlers);
@@ -23086,15 +24152,53 @@ function serializeGenerateContentInput(params) {
23086
24152
  return input;
23087
24153
  }
23088
24154
  function serializeEmbedContentInput(params) {
24155
+ let contents = Array.isArray(params.contents) ? params.contents : [params.contents];
24156
+ if (params.model.includes("gemini-embedding-2") && contents.length > 0 && contents.every(
24157
+ (content) => typeof content === "string" || !Array.isArray(content) && !("parts" in content)
24158
+ )) {
24159
+ contents = [contents];
24160
+ }
23089
24161
  const input = {
23090
- model: params.model,
23091
- contents: serializeContentCollection(params.contents)
24162
+ inputs: contents.map((content) => {
24163
+ const parts = typeof content === "string" ? [content] : Array.isArray(content) ? content : "parts" in content ? content.parts : [content];
24164
+ const normalized = parts.flatMap((part) => {
24165
+ if (typeof part === "string") return [{ type: "text", text: part }];
24166
+ if (part.text !== void 0) return [{ type: "text", text: part.text }];
24167
+ const media = part.inlineData ?? part.fileData;
24168
+ if (!media) return [];
24169
+ const data = "data" in media ? `data:${media.mimeType};base64,${typeof media.data === "string" ? media.data : uint8ArrayToBase64(media.data)}` : media.fileUri;
24170
+ return media.mimeType?.startsWith("image/") ? [{ type: "image_url", image_url: { url: data } }] : [
24171
+ {
24172
+ type: "file",
24173
+ file: {
24174
+ file_data: data,
24175
+ ..."displayName" in media && media.displayName ? { filename: media.displayName } : {}
24176
+ }
24177
+ }
24178
+ ];
24179
+ });
24180
+ return {
24181
+ content: normalized.length === 1 && normalized[0].type === "text" ? normalized[0].text : normalized
24182
+ };
24183
+ }),
24184
+ ...params.config?.outputDimensionality !== void 0 ? { output_dimensions: params.config.outputDimensionality } : {}
23092
24185
  };
23093
- const config = params.config ? tryToDict(params.config) : null;
23094
- if (config) {
23095
- input.config = config;
24186
+ try {
24187
+ const processed = processInputAttachments(input);
24188
+ const hasInlineMedia = processed.inputs.some(
24189
+ ({ content }) => Array.isArray(content) && content.some((part) => {
24190
+ const data = part.type === "image_url" ? part.image_url.url : part.type === "file" ? part.file.file_data : void 0;
24191
+ return typeof data === "string" && data.startsWith("data:");
24192
+ })
24193
+ );
24194
+ return hasInlineMedia ? input : processed;
24195
+ } catch (error) {
24196
+ debugLogger.error(
24197
+ "Error processing Google GenAI embedding attachments:",
24198
+ error
24199
+ );
24200
+ return input;
23096
24201
  }
23097
- return input;
23098
24202
  }
23099
24203
  function serializeInteractionInput(params) {
23100
24204
  const input = {
@@ -23282,19 +24386,6 @@ function extractGenerateContentMetadata(params) {
23282
24386
  }
23283
24387
  return metadata;
23284
24388
  }
23285
- function extractEmbedContentMetadata(params) {
23286
- const metadata = {};
23287
- if (params.model) {
23288
- metadata.model = params.model;
23289
- }
23290
- const config = params.config ? tryToDict(params.config) : null;
23291
- if (config) {
23292
- Object.keys(config).forEach((key) => {
23293
- metadata[key] = config[key];
23294
- });
23295
- }
23296
- return metadata;
23297
- }
23298
24389
  function extractGenerateContentMetrics(response, startTime) {
23299
24390
  const metrics = {};
23300
24391
  if (startTime !== void 0) {
@@ -23314,15 +24405,23 @@ function extractEmbedContentMetrics(response, startTime) {
23314
24405
  const end = getCurrentUnixTimestamp();
23315
24406
  metrics.start = startTime;
23316
24407
  metrics.end = end;
23317
- metrics.duration = end - startTime;
23318
- }
23319
- if (response?.usageMetadata) {
23320
- populateUsageMetrics(metrics, response.usageMetadata);
23321
24408
  }
23322
24409
  const embeddingTokenCount = extractEmbedPromptTokenCount(response);
23323
24410
  if (embeddingTokenCount !== void 0) {
23324
24411
  metrics.prompt_tokens = embeddingTokenCount;
23325
- metrics.tokens = embeddingTokenCount;
24412
+ }
24413
+ const totalTokens = response?.usageMetadata?.totalTokenCount ?? embeddingTokenCount;
24414
+ if (totalTokens !== void 0) {
24415
+ metrics.tokens = totalTokens;
24416
+ }
24417
+ const audioTokens = (response?.usageMetadata?.promptTokenDetails ?? response?.usageMetadata?.promptTokensDetails)?.filter(
24418
+ (detail) => detail.modality === "AUDIO" && detail.tokenCount !== void 0
24419
+ );
24420
+ if (audioTokens?.length) {
24421
+ metrics.prompt_audio_tokens = audioTokens.reduce(
24422
+ (sum, detail) => sum + (detail.tokenCount ?? 0),
24423
+ 0
24424
+ );
23326
24425
  }
23327
24426
  return metrics;
23328
24427
  }
@@ -23361,41 +24460,25 @@ function extractEmbedPromptTokenCount(response) {
23361
24460
  if (typeof usagePromptTokens === "number" && Number.isFinite(usagePromptTokens)) {
23362
24461
  return usagePromptTokens;
23363
24462
  }
23364
- const usageTotalTokens = response.usageMetadata?.totalTokenCount;
23365
- if (typeof usageTotalTokens === "number" && Number.isFinite(usageTotalTokens)) {
23366
- return usageTotalTokens;
23367
- }
23368
24463
  const embeddings = Array.isArray(response.embeddings) ? response.embeddings : response.embedding ? [response.embedding] : [];
23369
24464
  if (embeddings.length === 0) {
23370
24465
  return void 0;
23371
24466
  }
23372
24467
  let total = 0;
23373
- let sawAny = false;
23374
24468
  for (const embedding of embeddings) {
23375
24469
  const embeddingStats = tryToDict(tryToDict(embedding)?.statistics);
23376
24470
  const tokenCount2 = embeddingStats?.tokenCount;
23377
24471
  if (typeof tokenCount2 === "number" && Number.isFinite(tokenCount2)) {
23378
24472
  total += tokenCount2;
23379
- sawAny = true;
24473
+ } else {
24474
+ return void 0;
23380
24475
  }
23381
24476
  }
23382
- return sawAny ? total : void 0;
24477
+ return total;
23383
24478
  }
23384
24479
  function summarizeEmbedContentOutput(response) {
23385
- if (!response) {
23386
- return void 0;
23387
- }
23388
- const embeddings = Array.isArray(response.embeddings) ? response.embeddings : response.embedding ? [response.embedding] : [];
23389
- if (embeddings.length === 0) {
23390
- return void 0;
23391
- }
23392
- const firstValues = embeddings[0]?.values;
23393
- if (!Array.isArray(firstValues)) {
23394
- return void 0;
23395
- }
23396
24480
  return {
23397
- embedding_count: embeddings.length,
23398
- embedding_length: firstValues.length
24481
+ count: Array.isArray(response?.embeddings) ? response.embeddings.length : response?.embedding ? 1 : 0
23399
24482
  };
23400
24483
  }
23401
24484
  function populateUsageMetrics(metrics, usage) {
@@ -24262,7 +25345,7 @@ var HuggingFaceTransformersPlugin = class extends BasePlugin {
24262
25345
  getTask(event)
24263
25346
  ),
24264
25347
  extractInput: (args, event) => ({
24265
- input: extractInput(
25348
+ input: extractInput2(
24266
25349
  getTask(event),
24267
25350
  args
24268
25351
  ),
@@ -24352,7 +25435,7 @@ function modelIdentifier(pipeline) {
24352
25435
  }
24353
25436
  return void 0;
24354
25437
  }
24355
- function extractInput(task, args) {
25438
+ function extractInput2(task, args) {
24356
25439
  switch (task) {
24357
25440
  case "feature-extraction":
24358
25441
  return args[0];
@@ -27022,6 +28105,379 @@ function aggregateMistralStreamChunks(chunks) {
27022
28105
  };
27023
28106
  }
27024
28107
 
28108
+ // src/instrumentation/plugins/langgraph-sdk-channels.ts
28109
+ var langGraphSDKChannels = defineChannels(
28110
+ "@langchain/langgraph-sdk",
28111
+ {
28112
+ wait: channel({
28113
+ channelName: "runs.wait",
28114
+ kind: "async"
28115
+ }),
28116
+ stream: channel({
28117
+ channelName: "runs.stream",
28118
+ kind: "sync-stream"
28119
+ })
28120
+ },
28121
+ { instrumentationName: INSTRUMENTATION_NAMES.LANGGRAPH_SDK }
28122
+ );
28123
+
28124
+ // src/instrumentation/plugins/langgraph-sdk-plugin.ts
28125
+ var LangGraphSDKPlugin = class extends BasePlugin {
28126
+ onEnable() {
28127
+ this.unsubscribers.push(
28128
+ langGraphSDKChannels.wait.intercept(
28129
+ (target, self, args) => instrumentRun("wait", args, () => Reflect.apply(target, self, args))
28130
+ ),
28131
+ langGraphSDKChannels.stream.intercept(
28132
+ (target, self, args) => instrumentRun("stream", args, () => Reflect.apply(target, self, args))
28133
+ )
28134
+ );
28135
+ }
28136
+ onDisable() {
28137
+ this.unsubscribers = unsubscribeAll(this.unsubscribers);
28138
+ }
28139
+ };
28140
+ function normalizeMessage(value) {
28141
+ if (!isObject(value)) return value;
28142
+ 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);
28143
+ if (typeof role !== "string") return value;
28144
+ const message = {
28145
+ role,
28146
+ content: value.content ?? ""
28147
+ };
28148
+ for (const key of ["name", "tool_call_id", "refusal"]) {
28149
+ if (value[key] !== void 0) message[key] = value[key];
28150
+ }
28151
+ const additional = isObject(value.additional_kwargs) ? value.additional_kwargs : {};
28152
+ const toolCalls = Array.isArray(value.tool_calls) && value.tool_calls.length ? value.tool_calls : additional.tool_calls;
28153
+ if (Array.isArray(toolCalls) && toolCalls.length > 0) {
28154
+ message.tool_calls = toolCalls.map((call) => {
28155
+ if (!isObject(call)) return call;
28156
+ if (isObject(call.function)) return call;
28157
+ return {
28158
+ id: call.id,
28159
+ type: "function",
28160
+ function: {
28161
+ name: call.name,
28162
+ arguments: typeof call.args === "string" ? call.args : JSON.stringify(call.args ?? {})
28163
+ }
28164
+ };
28165
+ });
28166
+ }
28167
+ if (Array.isArray(value.invalid_tool_calls) && value.invalid_tool_calls.length > 0)
28168
+ message.invalid_tool_calls = value.invalid_tool_calls;
28169
+ if (message.refusal === void 0 && additional.refusal !== void 0)
28170
+ message.refusal = additional.refusal;
28171
+ return message;
28172
+ }
28173
+ function normalizeRunError(value) {
28174
+ let name;
28175
+ let message;
28176
+ if (value instanceof Error) {
28177
+ name = value.name;
28178
+ message = value.message;
28179
+ } else if (isObject(value) && typeof value.error === "string" && typeof value.message === "string") {
28180
+ name = value.error;
28181
+ message = value.message;
28182
+ } else {
28183
+ return value;
28184
+ }
28185
+ for (let depth = 0; depth < 3; depth++) {
28186
+ try {
28187
+ const nested = JSON.parse(
28188
+ message.startsWith(`${name}: `) ? message.slice(name.length + 2) : message
28189
+ );
28190
+ if (!isObject(nested) || typeof nested.error !== "string" || typeof nested.message !== "string")
28191
+ break;
28192
+ name = nested.error;
28193
+ message = nested.message;
28194
+ } catch {
28195
+ break;
28196
+ }
28197
+ }
28198
+ if (value instanceof Error && name === value.name && message === value.message)
28199
+ return value;
28200
+ return Object.assign(new Error(message), { name });
28201
+ }
28202
+ function normalizeState(value) {
28203
+ if (!isObject(value)) return value;
28204
+ return Object.fromEntries(
28205
+ Object.entries(value).map(([key, field]) => {
28206
+ if (key === "messages" && Array.isArray(field))
28207
+ return [key, field.map(normalizeMessage)];
28208
+ if (key === "__error__") {
28209
+ const error = normalizeRunError(field);
28210
+ if (error instanceof Error)
28211
+ return [key, { error: error.name, message: error.message }];
28212
+ }
28213
+ return [key, field];
28214
+ })
28215
+ );
28216
+ }
28217
+ function normalizeRunOutput(value, input) {
28218
+ if (!isObject(value)) return value;
28219
+ if (Array.isArray(value.messages)) {
28220
+ if (value.__interrupt__ !== void 0 || value.__error__ !== void 0)
28221
+ return void 0;
28222
+ const inputMessages = isObject(input) && Array.isArray(input.messages) ? input.messages : [];
28223
+ let inputPrefixLength = 0;
28224
+ while (inputPrefixLength < inputMessages.length) {
28225
+ const previous = inputMessages[inputPrefixLength];
28226
+ const message = value.messages[inputPrefixLength];
28227
+ 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)))
28228
+ break;
28229
+ inputPrefixLength++;
28230
+ }
28231
+ for (let index = value.messages.length - 1; index >= inputPrefixLength; index--) {
28232
+ const message = value.messages[index];
28233
+ const normalized = normalizeMessage(message);
28234
+ if (!isObject(normalized)) continue;
28235
+ if (normalized.role === "user") return void 0;
28236
+ if (normalized.role !== "assistant") continue;
28237
+ if (inputMessages.some((previous) => {
28238
+ if (!isObject(previous) || !isObject(message)) return false;
28239
+ return previous.id !== void 0 && previous.id === message.id && JSON.stringify(normalizeMessage(previous)) === JSON.stringify(normalized);
28240
+ }))
28241
+ continue;
28242
+ return normalized;
28243
+ }
28244
+ return void 0;
28245
+ }
28246
+ const result = Object.fromEntries(
28247
+ Object.entries(value).filter(
28248
+ ([key]) => key !== "__interrupt__" && key !== "__error__"
28249
+ )
28250
+ );
28251
+ return !Object.keys(result).length && (value.__interrupt__ !== void 0 || value.__error__ !== void 0) ? void 0 : result;
28252
+ }
28253
+ function instrumentRun(operation, [threadId, assistantId, options], invoke) {
28254
+ if (isAutoInstrumentationSuppressed()) return invoke();
28255
+ const start = getCurrentUnixTimestamp();
28256
+ let span;
28257
+ try {
28258
+ const metadata = {
28259
+ "langgraph.thread_id": threadId,
28260
+ "langgraph.assistant_id": assistantId
28261
+ };
28262
+ for (const key of [
28263
+ "streamMode",
28264
+ "streamSubgraphs",
28265
+ "interruptBefore",
28266
+ "interruptAfter",
28267
+ "multitaskStrategy",
28268
+ "durability"
28269
+ ]) {
28270
+ if (options?.[key] !== void 0) metadata[key] = options[key];
28271
+ }
28272
+ span = startSpan(
28273
+ withSpanInstrumentationName(
28274
+ {
28275
+ name: `langgraph.runs.${operation}`,
28276
+ spanAttributes: { type: "task" /* TASK */ },
28277
+ event: {
28278
+ input: options?.command === void 0 ? normalizeState(options?.input) : {
28279
+ input: normalizeState(options.input),
28280
+ command: options.command
28281
+ },
28282
+ metadata
28283
+ }
28284
+ },
28285
+ INSTRUMENTATION_NAMES.LANGGRAPH_SDK
28286
+ )
28287
+ );
28288
+ } catch (error) {
28289
+ debugLogger.error("Error starting LangGraph SDK span:", error);
28290
+ return invoke();
28291
+ }
28292
+ let ended = false;
28293
+ let output;
28294
+ let streamError;
28295
+ let firstToken;
28296
+ const updates = [];
28297
+ const usageByMessage = /* @__PURE__ */ new Map();
28298
+ const captureUsage = (id, usage) => {
28299
+ if (!isObject(usage)) return;
28300
+ const metrics = {};
28301
+ for (const [source, destination] of [
28302
+ ["input_tokens", "prompt_tokens"],
28303
+ ["output_tokens", "completion_tokens"],
28304
+ ["total_tokens", "tokens"]
28305
+ ]) {
28306
+ const value = usage[source];
28307
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0)
28308
+ metrics[destination] = value;
28309
+ }
28310
+ if (metrics.tokens === void 0 && metrics.prompt_tokens !== void 0 && metrics.completion_tokens !== void 0)
28311
+ metrics.tokens = metrics.prompt_tokens + metrics.completion_tokens;
28312
+ usageByMessage.set(id, { ...usageByMessage.get(id), ...metrics });
28313
+ };
28314
+ const messages = /* @__PURE__ */ new Map();
28315
+ const messageSnapshots = /* @__PURE__ */ new Map();
28316
+ const finish = (error) => {
28317
+ if (ended) return;
28318
+ ended = true;
28319
+ try {
28320
+ const metrics = {};
28321
+ for (const usage of usageByMessage.values()) {
28322
+ for (const [key, value] of Object.entries(usage))
28323
+ metrics[key] = (metrics[key] ?? 0) + value;
28324
+ }
28325
+ if (firstToken !== void 0)
28326
+ metrics.time_to_first_token = firstToken - start;
28327
+ const finalMessages = [
28328
+ ...new Map([...messages, ...messageSnapshots]).values()
28329
+ ];
28330
+ let loggedOutput = normalizeRunOutput(output, options?.input);
28331
+ if (loggedOutput === void 0 && finalMessages.length)
28332
+ loggedOutput = normalizeRunOutput(
28333
+ { messages: finalMessages },
28334
+ void 0
28335
+ );
28336
+ if (output === void 0 && !finalMessages.length && updates.length) {
28337
+ const results = updates.map((update) => normalizeRunOutput(update, options?.input)).filter((update) => update !== void 0);
28338
+ if (results.length) loggedOutput = { updates: results };
28339
+ }
28340
+ const interrupted = [output, ...updates].find(
28341
+ (state) => isObject(state) && state.__interrupt__ !== void 0
28342
+ );
28343
+ span.log({
28344
+ ...loggedOutput !== void 0 ? { output: loggedOutput } : {},
28345
+ ...isObject(interrupted) ? { metadata: { "langgraph.interrupts": interrupted.__interrupt__ } } : {},
28346
+ ...error !== void 0 || streamError !== void 0 ? { error: normalizeRunError(error ?? streamError) } : {},
28347
+ metrics
28348
+ });
28349
+ } catch (error2) {
28350
+ debugLogger.error("Error logging LangGraph SDK span:", error2);
28351
+ }
28352
+ try {
28353
+ span.end();
28354
+ } catch (error2) {
28355
+ debugLogger.error("Error ending LangGraph SDK span:", error2);
28356
+ }
28357
+ };
28358
+ const observeMessages = (value, streaming) => {
28359
+ if (!isObject(value) || !Array.isArray(value.messages)) return;
28360
+ const inputMessages = isObject(options?.input) && Array.isArray(options.input.messages) ? options.input.messages : [];
28361
+ for (const message of value.messages) {
28362
+ if (!isObject(message) || message.type !== "ai" && message.role !== "assistant")
28363
+ continue;
28364
+ if (message.id !== void 0 && inputMessages.some(
28365
+ (input) => isObject(input) && input.id === message.id
28366
+ ))
28367
+ continue;
28368
+ captureUsage(
28369
+ typeof message.id === "string" ? message.id : "message",
28370
+ message.usage_metadata
28371
+ );
28372
+ if (streaming && (typeof message.content === "string" ? message.content.length > 0 : Array.isArray(message.content) && message.content.some(
28373
+ (part) => isObject(part) && typeof part.text === "string" && part.text.length > 0
28374
+ )))
28375
+ firstToken ??= getCurrentUnixTimestamp();
28376
+ }
28377
+ };
28378
+ const onChunk = ({ event, data }) => {
28379
+ if (ended) return;
28380
+ if (event === "metadata" && isObject(data)) {
28381
+ if (typeof data.run_id === "string")
28382
+ span.log({ metadata: { "langgraph.run_id": data.run_id } });
28383
+ } else if (event === "error") {
28384
+ streamError = normalizeRunError(data);
28385
+ } else if (event === "values") {
28386
+ output = data;
28387
+ observeMessages(data, true);
28388
+ } else if (event === "updates") {
28389
+ if (isObject(data)) {
28390
+ const stateUpdates = [];
28391
+ for (const [node, update] of Object.entries(data)) {
28392
+ observeMessages(update, true);
28393
+ if (isObject(update) && Array.isArray(update.messages)) {
28394
+ for (const message of update.messages) {
28395
+ if (isObject(message))
28396
+ messageSnapshots.set(
28397
+ typeof message.id === "string" ? message.id : `update-${messageSnapshots.size}`,
28398
+ message
28399
+ );
28400
+ }
28401
+ const state = Object.fromEntries(
28402
+ Object.entries(update).filter(([key]) => key !== "messages")
28403
+ );
28404
+ if (Object.keys(state).length) stateUpdates.push([node, state]);
28405
+ } else {
28406
+ stateUpdates.push([node, update]);
28407
+ }
28408
+ }
28409
+ if (stateUpdates.length) updates.push(Object.fromEntries(stateUpdates));
28410
+ } else {
28411
+ updates.push(data);
28412
+ }
28413
+ } else if ((event === "messages" || event === "messages/partial" || event === "messages/complete") && Array.isArray(data)) {
28414
+ const parts = event === "messages" ? [data[0]] : data;
28415
+ for (const part of parts) {
28416
+ if (!isObject(part)) continue;
28417
+ const id = typeof part.id === "string" ? part.id : "message";
28418
+ captureUsage(id, part.usage_metadata);
28419
+ const previous = messages.get(id);
28420
+ messages.set(
28421
+ id,
28422
+ event === "messages" && previous && typeof part.content === "string" && typeof previous.content === "string" ? { ...part, content: previous.content + part.content } : part
28423
+ );
28424
+ if (typeof part.content === "string" && part.content.length > 0)
28425
+ firstToken ??= getCurrentUnixTimestamp();
28426
+ }
28427
+ }
28428
+ };
28429
+ let result;
28430
+ try {
28431
+ result = withCurrent(
28432
+ span,
28433
+ () => runWithAutoInstrumentationSuppressed(invoke)
28434
+ );
28435
+ } catch (error) {
28436
+ finish(error);
28437
+ throw error;
28438
+ }
28439
+ if (operation === "stream") {
28440
+ try {
28441
+ patchStreamIfNeeded(result, {
28442
+ shouldCollect: (chunk) => {
28443
+ try {
28444
+ onChunk(chunk);
28445
+ } catch (error) {
28446
+ debugLogger.error(
28447
+ "Error processing LangGraph stream event:",
28448
+ error
28449
+ );
28450
+ }
28451
+ return false;
28452
+ },
28453
+ aroundNext: (next) => withCurrent(span, () => runWithAutoInstrumentationSuppressed(next)),
28454
+ onComplete: () => finish(),
28455
+ onCancel: () => finish(),
28456
+ onError: (error) => finish(error)
28457
+ });
28458
+ } catch (error) {
28459
+ debugLogger.error("Error observing LangGraph stream:", error);
28460
+ finish();
28461
+ }
28462
+ } else {
28463
+ void Promise.resolve(result).then(
28464
+ (value) => {
28465
+ try {
28466
+ output = value;
28467
+ observeMessages(value, false);
28468
+ if (isObject(value) && isObject(value.__error__))
28469
+ streamError = normalizeRunError(value.__error__);
28470
+ finish();
28471
+ } catch (error) {
28472
+ finish(error);
28473
+ }
28474
+ },
28475
+ (error) => finish(error)
28476
+ );
28477
+ }
28478
+ return result;
28479
+ }
28480
+
27025
28481
  // src/instrumentation/plugins/ollama-channels.ts
27026
28482
  var ollamaChannels = defineChannels(
27027
28483
  "ollama",
@@ -27231,7 +28687,7 @@ function normalizeTextAndImages(content, images) {
27231
28687
  ...unrecognizedImages.length > 0 ? { unrecognizedImages } : {}
27232
28688
  };
27233
28689
  }
27234
- function normalizeMessage(message, toolCallId, syntheticToolCallIdOffset = 0) {
28690
+ function normalizeMessage2(message, toolCallId, syntheticToolCallIdOffset = 0) {
27235
28691
  if (typeof message.role !== "string") {
27236
28692
  return void 0;
27237
28693
  }
@@ -27277,7 +28733,7 @@ function normalizeMessages(messages) {
27277
28733
  toolCallId = pendingToolCallIds.get(toolName)?.shift();
27278
28734
  }
27279
28735
  }
27280
- const normalized = normalizeMessage(
28736
+ const normalized = normalizeMessage2(
27281
28737
  ollamaMessage,
27282
28738
  toolCallId,
27283
28739
  syntheticToolCallIdOffset
@@ -27396,7 +28852,7 @@ function extractOllamaChatOutput(result, syntheticToolCallIdOffset = 0) {
27396
28852
  if (!isObject(result) || !isObject(result.message)) {
27397
28853
  return void 0;
27398
28854
  }
27399
- const message = normalizeMessage(
28855
+ const message = normalizeMessage2(
27400
28856
  result.message,
27401
28857
  void 0,
27402
28858
  syntheticToolCallIdOffset
@@ -30116,14 +31572,14 @@ function extractActionSpanMetadata(args) {
30116
31572
  const options = extractRunInNewSpanOptions(args);
30117
31573
  const labels = isObject(options?.labels) ? options.labels : void 0;
30118
31574
  const metadata = isObject(options?.metadata) ? options.metadata : void 0;
30119
- const actionType = stringValue(labels?.["genkit:metadata:subtype"]);
30120
- const name = stringValue(metadata?.name);
31575
+ const actionType = stringValue2(labels?.["genkit:metadata:subtype"]);
31576
+ const name = stringValue2(metadata?.name);
30121
31577
  if (!actionType || !name) {
30122
31578
  return void 0;
30123
31579
  }
30124
31580
  return {
30125
31581
  actionType,
30126
- key: stringValue(labels?.["genkit:key"]),
31582
+ key: stringValue2(labels?.["genkit:key"]),
30127
31583
  name
30128
31584
  };
30129
31585
  }
@@ -30233,7 +31689,7 @@ function pickNumberMetrics(values) {
30233
31689
  })
30234
31690
  );
30235
31691
  }
30236
- function stringValue(value) {
31692
+ function stringValue2(value) {
30237
31693
  return typeof value === "string" ? value : void 0;
30238
31694
  }
30239
31695
 
@@ -30918,7 +32374,7 @@ function subscribeToFlueContext(value, state) {
30918
32374
  try {
30919
32375
  unsubscribe?.();
30920
32376
  } catch (error) {
30921
- logInstrumentationError3("Flue context unsubscribe", error);
32377
+ logInstrumentationError4("Flue context unsubscribe", error);
30922
32378
  }
30923
32379
  };
30924
32380
  try {
@@ -30934,7 +32390,7 @@ function subscribeToFlueContext(value, state) {
30934
32390
  });
30935
32391
  state.contexts.add(value);
30936
32392
  } catch (error) {
30937
- logInstrumentationError3("Flue context subscription", error);
32393
+ logInstrumentationError4("Flue context subscription", error);
30938
32394
  }
30939
32395
  }
30940
32396
  function isAutoContextTerminalEvent(event, ctx) {
@@ -30990,7 +32446,7 @@ var FlueObserveBridge = class {
30990
32446
  try {
30991
32447
  this.handleEvent(event, flueContextFromUnknown(ctx));
30992
32448
  } catch (error) {
30993
- logInstrumentationError3("Flue observe", error);
32449
+ logInstrumentationError4("Flue observe", error);
30994
32450
  }
30995
32451
  }
30996
32452
  reset() {
@@ -31007,7 +32463,7 @@ var FlueObserveBridge = class {
31007
32463
  try {
31008
32464
  span = this.spanForExecutionOperation(operation, executionContext);
31009
32465
  } catch (error) {
31010
- logInstrumentationError3("Flue execution interceptor", error);
32466
+ logInstrumentationError4("Flue execution interceptor", error);
31011
32467
  }
31012
32468
  return span ? runWithCurrentSpanStore(span, next) : next();
31013
32469
  }
@@ -31213,7 +32669,7 @@ var FlueObserveBridge = class {
31213
32669
  this.runsById.delete(event.runId);
31214
32670
  }
31215
32671
  void flush().catch((error) => {
31216
- logInstrumentationError3("Flue flush", error);
32672
+ logInstrumentationError4("Flue flush", error);
31217
32673
  });
31218
32674
  }
31219
32675
  handleOperationStart(event) {
@@ -31988,17 +33444,17 @@ function safeLog3(span, event) {
31988
33444
  try {
31989
33445
  span.log(event);
31990
33446
  } catch (error) {
31991
- logInstrumentationError3("Flue span log", error);
33447
+ logInstrumentationError4("Flue span log", error);
31992
33448
  }
31993
33449
  }
31994
33450
  function safeEnd(span, endTime) {
31995
33451
  try {
31996
33452
  span.end(endTime === void 0 ? void 0 : { endTime });
31997
33453
  } catch (error) {
31998
- logInstrumentationError3("Flue span end", error);
33454
+ logInstrumentationError4("Flue span end", error);
31999
33455
  }
32000
33456
  }
32001
- function logInstrumentationError3(label, error) {
33457
+ function logInstrumentationError4(label, error) {
32002
33458
  debugLogger.debug(`Error in ${label} instrumentation:`, error);
32003
33459
  }
32004
33460
 
@@ -32566,10 +34022,10 @@ var LangSmithPlugin = class extends BasePlugin {
32566
34022
  const creates = ownValue(batch, "runCreates");
32567
34023
  if (Array.isArray(creates)) {
32568
34024
  const parentFirst = [...creates].sort((left, right) => {
32569
- const leftId = stringValue2(ownValue(left, "id"));
32570
- const rightId = stringValue2(ownValue(right, "id"));
32571
- const leftParent = stringValue2(ownValue(left, "parent_run_id"));
32572
- const rightParent = stringValue2(ownValue(right, "parent_run_id"));
34025
+ const leftId = stringValue3(ownValue(left, "id"));
34026
+ const rightId = stringValue3(ownValue(right, "id"));
34027
+ const leftParent = stringValue3(ownValue(left, "parent_run_id"));
34028
+ const rightParent = stringValue3(ownValue(right, "parent_run_id"));
32573
34029
  if (leftParent && leftParent === rightId) {
32574
34030
  return 1;
32575
34031
  }
@@ -32588,13 +34044,13 @@ var LangSmithPlugin = class extends BasePlugin {
32588
34044
  if (Array.isArray(updates)) {
32589
34045
  for (const run of updates) {
32590
34046
  this.containLifecycleFailure("batchIngestRuns update", () => {
32591
- this.processUpdate(stringValue2(ownValue(run, "id")) ?? "", run);
34047
+ this.processUpdate(stringValue3(ownValue(run, "id")) ?? "", run);
32592
34048
  });
32593
34049
  }
32594
34050
  }
32595
34051
  }
32596
34052
  processCreate(run) {
32597
- const id = stringValue2(ownValue(run, "id"));
34053
+ const id = stringValue3(ownValue(run, "id"));
32598
34054
  if (!id || this.completedRuns.get(id)) {
32599
34055
  return;
32600
34056
  }
@@ -32627,7 +34083,7 @@ var LangSmithPlugin = class extends BasePlugin {
32627
34083
  this.endIfComplete(id, activeRun, run);
32628
34084
  }
32629
34085
  processUpdate(explicitId, run) {
32630
- const id = stringValue2(explicitId) ?? stringValue2(ownValue(run, "id"));
34086
+ const id = stringValue3(explicitId) ?? stringValue3(ownValue(run, "id"));
32631
34087
  if (!id || this.completedRuns.get(id)) {
32632
34088
  return;
32633
34089
  }
@@ -32650,13 +34106,13 @@ var LangSmithPlugin = class extends BasePlugin {
32650
34106
  this.endIfComplete(id, active, active.run);
32651
34107
  }
32652
34108
  startRunSpan(id, run) {
32653
- const traceId = stringValue2(ownValue(run, "trace_id")) ?? id;
32654
- const parentId = stringValue2(ownValue(run, "parent_run_id")) ?? stringValue2(ownValue(ownValue(run, "parent_run"), "id"));
34109
+ const traceId = stringValue3(ownValue(run, "trace_id")) ?? id;
34110
+ const parentId = stringValue3(ownValue(run, "parent_run_id")) ?? stringValue3(ownValue(ownValue(run, "parent_run"), "id"));
32655
34111
  const startTime = timestampSeconds(ownValue(run, "start_time"));
32656
34112
  return startSpan(
32657
34113
  withSpanInstrumentationName(
32658
34114
  {
32659
- name: stringValue2(ownValue(run, "name")) ?? "LangSmith run",
34115
+ name: stringValue3(ownValue(run, "name")) ?? "LangSmith run",
32660
34116
  spanId: id,
32661
34117
  parentSpanIds: {
32662
34118
  parentSpanIds: parentId ? [parentId] : [],
@@ -32748,7 +34204,7 @@ function mergeRuns(previous, current) {
32748
34204
  function isRecord2(value) {
32749
34205
  return typeof value === "object" && value !== null && !Array.isArray(value);
32750
34206
  }
32751
- function stringValue2(value) {
34207
+ function stringValue3(value) {
32752
34208
  return typeof value === "string" && value.length > 0 ? value : void 0;
32753
34209
  }
32754
34210
  function timestampSeconds(value) {
@@ -32766,7 +34222,7 @@ function timestampSeconds(value) {
32766
34222
  return void 0;
32767
34223
  }
32768
34224
  function dottedOrderDepth(run) {
32769
- const dottedOrder = stringValue2(ownValue(run, "dotted_order"));
34225
+ const dottedOrder = stringValue3(ownValue(run, "dotted_order"));
32770
34226
  return dottedOrder ? dottedOrder.split(".").length : Number.MAX_SAFE_INTEGER;
32771
34227
  }
32772
34228
  function mapRunType(runType) {
@@ -32971,7 +34427,7 @@ var PiCodingAgentPlugin = class extends BasePlugin {
32971
34427
  }
32972
34428
  );
32973
34429
  } catch (error) {
32974
- logInstrumentationError4("Pi Coding Agent prompt start", error);
34430
+ logInstrumentationError5("Pi Coding Agent prompt start", error);
32975
34431
  }
32976
34432
  if (!state) {
32977
34433
  return runWithAutoInstrumentationSuppressed(invokeTarget);
@@ -33104,12 +34560,12 @@ function installPiAgentInstrumentation(agent) {
33104
34560
  () => handlePiAgentEvent(state, event)
33105
34561
  );
33106
34562
  } catch (error) {
33107
- logInstrumentationError4("Pi Coding Agent event", error);
34563
+ logInstrumentationError5("Pi Coding Agent event", error);
33108
34564
  }
33109
34565
  });
33110
34566
  piAgentEventSubscriptions.add(agent);
33111
34567
  } catch (error) {
33112
- logInstrumentationError4("Pi Coding Agent event subscription", error);
34568
+ logInstrumentationError5("Pi Coding Agent event subscription", error);
33113
34569
  }
33114
34570
  }
33115
34571
  function makeInstrumentedStreamFunction(agent, originalStreamFunction, property) {
@@ -33159,7 +34615,7 @@ function wrapPiToolExecutors(tools) {
33159
34615
  });
33160
34616
  tool.execute = wrappedExecute;
33161
34617
  } catch (error) {
33162
- logInstrumentationError4("Pi Coding Agent tool wrapping", error);
34618
+ logInstrumentationError5("Pi Coding Agent tool wrapping", error);
33163
34619
  }
33164
34620
  }
33165
34621
  }
@@ -33238,7 +34694,7 @@ function patchAssistantMessageStream(stream, promptState, llmState) {
33238
34694
  try {
33239
34695
  await iterator.return();
33240
34696
  } catch (cleanupError) {
33241
- logInstrumentationError4(
34697
+ logInstrumentationError5(
33242
34698
  "Pi Coding Agent stream cleanup",
33243
34699
  cleanupError
33244
34700
  );
@@ -33403,7 +34859,7 @@ function finishPiPromptRun(state, error) {
33403
34859
  try {
33404
34860
  state.span.end();
33405
34861
  } catch (endError) {
33406
- logInstrumentationError4("Pi Coding Agent prompt end", endError);
34862
+ logInstrumentationError5("Pi Coding Agent prompt end", endError);
33407
34863
  }
33408
34864
  }
33409
34865
  }
@@ -33735,10 +35191,10 @@ function safeLog4(span, event) {
33735
35191
  try {
33736
35192
  span.log(event);
33737
35193
  } catch (error) {
33738
- logInstrumentationError4("Pi Coding Agent span log", error);
35194
+ logInstrumentationError5("Pi Coding Agent span log", error);
33739
35195
  }
33740
35196
  }
33741
- function logInstrumentationError4(context, error) {
35197
+ function logInstrumentationError5(context, error) {
33742
35198
  debugLogger.debug(`${context}:`, error);
33743
35199
  }
33744
35200
 
@@ -33976,7 +35432,7 @@ function handleAgentStreamEvent(state, event) {
33976
35432
  finalizeModelSpan(state, event);
33977
35433
  break;
33978
35434
  case "beforeToolCallEvent":
33979
- startToolSpan2(state, event);
35435
+ startToolSpan3(state, event);
33980
35436
  break;
33981
35437
  case "afterToolCallEvent":
33982
35438
  finalizeToolSpan(state, event);
@@ -34001,7 +35457,7 @@ function handleAgentStreamEvent(state, event) {
34001
35457
  break;
34002
35458
  }
34003
35459
  } catch (error) {
34004
- logInstrumentationError5("Strands Agent SDK event", error);
35460
+ logInstrumentationError6("Strands Agent SDK event", error);
34005
35461
  }
34006
35462
  }
34007
35463
  function handleMultiAgentStreamEvent(state, event, activeChildParents) {
@@ -34037,7 +35493,7 @@ function handleMultiAgentStreamEvent(state, event, activeChildParents) {
34037
35493
  break;
34038
35494
  }
34039
35495
  } catch (error) {
34040
- logInstrumentationError5("Strands Agent SDK multi-agent event", error);
35496
+ logInstrumentationError6("Strands Agent SDK multi-agent event", error);
34041
35497
  }
34042
35498
  }
34043
35499
  function buildModelSpanInput(event, attachmentCache) {
@@ -34116,7 +35572,7 @@ function finalizeModelSpan(state, event) {
34116
35572
  });
34117
35573
  modelState.span.end();
34118
35574
  }
34119
- function startToolSpan2(state, event) {
35575
+ function startToolSpan3(state, event) {
34120
35576
  const toolUse = event.toolUse;
34121
35577
  const key = toolKey2(toolUse);
34122
35578
  if (state.activeTools.has(key)) {
@@ -34396,7 +35852,7 @@ function getModelConfig(model) {
34396
35852
  try {
34397
35853
  return model.getConfig();
34398
35854
  } catch (error) {
34399
- logInstrumentationError5("Strands Agent SDK model config", error);
35855
+ logInstrumentationError6("Strands Agent SDK model config", error);
34400
35856
  return void 0;
34401
35857
  }
34402
35858
  }
@@ -34479,7 +35935,7 @@ function processStrandsInputAttachments(input, cache = createStrandsAttachmentCa
34479
35935
  try {
34480
35936
  return processStrandsInputNode(input, cache);
34481
35937
  } catch (error) {
34482
- logInstrumentationError5("Strands Agent SDK input attachments", error);
35938
+ logInstrumentationError6("Strands Agent SDK input attachments", error);
34483
35939
  return input;
34484
35940
  }
34485
35941
  }
@@ -34699,13 +36155,484 @@ function safeLog5(span, event) {
34699
36155
  try {
34700
36156
  span.log(event);
34701
36157
  } catch (error) {
34702
- logInstrumentationError5("Strands Agent SDK span log", error);
36158
+ logInstrumentationError6("Strands Agent SDK span log", error);
34703
36159
  }
34704
36160
  }
34705
- function logInstrumentationError5(context, error) {
36161
+ function logInstrumentationError6(context, error) {
34706
36162
  debugLogger.debug(`${context}:`, error);
34707
36163
  }
34708
36164
 
36165
+ // src/instrumentation/plugins/elevenlabs-channels.ts
36166
+ var elevenLabsChannels = defineChannels(
36167
+ "@elevenlabs/elevenlabs-js",
36168
+ {
36169
+ convert: channel({
36170
+ channelName: "textToSpeech.convert",
36171
+ kind: "async"
36172
+ }),
36173
+ stream: channel({
36174
+ channelName: "textToSpeech.stream",
36175
+ kind: "async"
36176
+ }),
36177
+ convertWithTimestamps: channel({ channelName: "textToSpeech.convertWithTimestamps", kind: "async" }),
36178
+ streamWithTimestamps: channel({ channelName: "textToSpeech.streamWithTimestamps", kind: "async" }),
36179
+ transcribe: channel({ channelName: "speechToText.convert", kind: "async" })
36180
+ },
36181
+ { instrumentationName: INSTRUMENTATION_NAMES.ELEVENLABS }
36182
+ );
36183
+
36184
+ // src/instrumentation/plugins/elevenlabs-plugin.ts
36185
+ var ElevenLabsPlugin = class extends BasePlugin {
36186
+ onEnable() {
36187
+ for (const method of [
36188
+ "convert",
36189
+ "stream",
36190
+ "convertWithTimestamps",
36191
+ "streamWithTimestamps"
36192
+ ]) {
36193
+ this.unsubscribers.push(
36194
+ interceptCall2(
36195
+ elevenLabsChannels[method],
36196
+ `elevenlabs.textToSpeech.${method}`,
36197
+ ([voice, request]) => ({
36198
+ input: {
36199
+ operation: "speech",
36200
+ prompt: request.text,
36201
+ parameters: {
36202
+ voice,
36203
+ format: request.outputFormat,
36204
+ language: request.languageCode,
36205
+ speed: request.voiceSettings?.speed
36206
+ }
36207
+ },
36208
+ metadata: {
36209
+ provider: "elevenlabs",
36210
+ model: request.modelId ?? "eleven_multilingual_v2"
36211
+ }
36212
+ }),
36213
+ (value, args, span, finish, headers, started) => captureSpeech(
36214
+ value,
36215
+ args[1],
36216
+ method,
36217
+ span,
36218
+ finish,
36219
+ started,
36220
+ headers
36221
+ )
36222
+ )
36223
+ );
36224
+ }
36225
+ this.unsubscribers.push(
36226
+ interceptCall2(
36227
+ elevenLabsChannels.transcribe,
36228
+ "elevenlabs.speechToText.convert",
36229
+ ([request]) => {
36230
+ if (request.webhook) return void 0;
36231
+ const file = request.file;
36232
+ const filename = typeof File !== "undefined" && file instanceof File ? file.name : "audio";
36233
+ const contentType = file instanceof Blob ? file.type || "application/octet-stream" : "application/octet-stream";
36234
+ 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;
36235
+ const fileData = blob ? new Attachment({ data: blob, filename, contentType }) : request.cloudStorageUrl;
36236
+ return {
36237
+ input: {
36238
+ operation: "transcribe",
36239
+ content: fileData ? [{ type: "file", file: { filename, file_data: fileData } }] : [],
36240
+ parameters: {
36241
+ language: request.languageCode,
36242
+ timestamp_granularities: request.timestampsGranularity
36243
+ }
36244
+ },
36245
+ metadata: { provider: "elevenlabs", model: request.modelId }
36246
+ };
36247
+ },
36248
+ (value, _args, span, finish) => {
36249
+ const result = value;
36250
+ const transcripts = result.transcripts ?? [result];
36251
+ span.log({
36252
+ output: {
36253
+ content: transcripts.flatMap(
36254
+ (transcript) => typeof transcript.text === "string" ? [{ type: "text", text: transcript.text }] : []
36255
+ ),
36256
+ annotations: {
36257
+ language: result.languageCode,
36258
+ words: result.words ?? (result.transcripts ? result.transcripts.flatMap(
36259
+ (transcript) => transcript.words ?? []
36260
+ ) : void 0)
36261
+ }
36262
+ }
36263
+ });
36264
+ finish();
36265
+ },
36266
+ ([request], span) => {
36267
+ const file = request.file;
36268
+ if (!isAsyncIterable(file)) return;
36269
+ const chunks = [];
36270
+ const filename = isObject(file) && typeof file.path === "string" ? file.path.split(/[\\/]/).pop() || "audio" : "audio";
36271
+ observeAudioStream(
36272
+ file,
36273
+ (chunk) => chunks.push(new Uint8Array(chunk)),
36274
+ () => {
36275
+ const contentType = "application/octet-stream";
36276
+ const data = new Blob(chunks, {
36277
+ type: contentType
36278
+ });
36279
+ chunks.length = 0;
36280
+ span.log({
36281
+ input: {
36282
+ content: [
36283
+ {
36284
+ type: "file",
36285
+ file: {
36286
+ filename,
36287
+ file_data: new Attachment({
36288
+ data,
36289
+ filename,
36290
+ contentType
36291
+ })
36292
+ }
36293
+ }
36294
+ ]
36295
+ }
36296
+ });
36297
+ },
36298
+ () => {
36299
+ chunks.length = 0;
36300
+ },
36301
+ span
36302
+ );
36303
+ }
36304
+ )
36305
+ );
36306
+ }
36307
+ onDisable() {
36308
+ this.unsubscribers = unsubscribeAll(this.unsubscribers);
36309
+ }
36310
+ };
36311
+ function interceptCall2(channel2, name, input, output, beforeInvoke) {
36312
+ return channel2.intercept((target, self, args) => {
36313
+ const invoke = () => Reflect.apply(target, self, args);
36314
+ if (isAutoInstrumentationSuppressed()) return invoke();
36315
+ const started = Date.now() / 1e3;
36316
+ let span;
36317
+ try {
36318
+ const event = input(args);
36319
+ if (event !== void 0)
36320
+ span = startSpan(
36321
+ withSpanInstrumentationName(
36322
+ {
36323
+ name,
36324
+ spanAttributes: { type: "llm" /* LLM */ },
36325
+ event
36326
+ },
36327
+ INSTRUMENTATION_NAMES.ELEVENLABS
36328
+ )
36329
+ );
36330
+ } catch (error) {
36331
+ debugLogger.error("Error starting ElevenLabs span", error);
36332
+ return invoke();
36333
+ }
36334
+ if (!span) return invoke();
36335
+ const activeSpan = span;
36336
+ let ended = false;
36337
+ const finish = (error) => {
36338
+ if (ended) return;
36339
+ ended = true;
36340
+ try {
36341
+ if (error !== void 0) activeSpan.log({ error });
36342
+ activeSpan.end();
36343
+ } catch (loggingError) {
36344
+ debugLogger.error("Error ending ElevenLabs span", loggingError);
36345
+ }
36346
+ };
36347
+ try {
36348
+ beforeInvoke?.(args, span);
36349
+ } catch (error) {
36350
+ debugLogger.error("Error observing ElevenLabs input", error);
36351
+ }
36352
+ let result;
36353
+ try {
36354
+ result = withCurrent(
36355
+ span,
36356
+ () => runWithAutoInstrumentationSuppressed(invoke)
36357
+ );
36358
+ } catch (error) {
36359
+ finish(error);
36360
+ throw error;
36361
+ }
36362
+ const capture = (value, headers) => {
36363
+ try {
36364
+ output(value, args, span, finish, headers, started);
36365
+ } catch (error) {
36366
+ debugLogger.error("Error capturing ElevenLabs output", error);
36367
+ finish();
36368
+ }
36369
+ };
36370
+ try {
36371
+ if (isObject(result) && typeof result.withRawResponse === "function") {
36372
+ void result.withRawResponse().then(
36373
+ ({
36374
+ data,
36375
+ rawResponse
36376
+ }) => capture(data, rawResponse?.headers),
36377
+ finish
36378
+ );
36379
+ } else {
36380
+ void Promise.resolve(result).then((value) => capture(value), finish);
36381
+ }
36382
+ } catch (error) {
36383
+ debugLogger.error("Error observing ElevenLabs result", error);
36384
+ finish();
36385
+ }
36386
+ return result;
36387
+ });
36388
+ }
36389
+ function captureSpeech(value, request, method, span, finish, started, headers) {
36390
+ const format = request.outputFormat ?? "mp3_44100_128";
36391
+ 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;
36392
+ const headerType = headers?.get("content-type")?.split(";")[0];
36393
+ const contentType = headerType?.startsWith("audio/") ? headerType : formatType;
36394
+ const disposition = headers?.get("content-disposition");
36395
+ const headerFilename = disposition?.match(
36396
+ /filename="([^"]+)"|filename=([^;]+)/i
36397
+ );
36398
+ const filename = headerFilename?.[1] ?? headerFilename?.[2]?.trim() ?? `speech.${contentType ? getExtensionFromMediaType(contentType) : "bin"}`;
36399
+ const chunks = [];
36400
+ const alignments = [];
36401
+ let bytes = 0;
36402
+ let first = true;
36403
+ let stopped = false;
36404
+ const observe = (chunk) => {
36405
+ if (stopped || chunk.byteLength === 0) return;
36406
+ if (first && method.startsWith("stream")) {
36407
+ span.log({
36408
+ metrics: { time_to_first_token: Date.now() / 1e3 - started }
36409
+ });
36410
+ }
36411
+ first = false;
36412
+ chunks.push(new Uint8Array(chunk));
36413
+ bytes += chunk.byteLength;
36414
+ };
36415
+ const complete = () => {
36416
+ if (stopped) return;
36417
+ stopped = true;
36418
+ try {
36419
+ const content = [];
36420
+ if (contentType && bytes) {
36421
+ const data = new Uint8Array(bytes);
36422
+ let offset = 0;
36423
+ for (const chunk of chunks) {
36424
+ data.set(chunk, offset);
36425
+ offset += chunk.length;
36426
+ }
36427
+ content.push({
36428
+ type: "file",
36429
+ file: {
36430
+ filename,
36431
+ byte_size: bytes,
36432
+ file_data: new Attachment({
36433
+ data: new Blob([data], { type: contentType }),
36434
+ filename,
36435
+ contentType
36436
+ })
36437
+ }
36438
+ });
36439
+ }
36440
+ span.log({
36441
+ output: {
36442
+ content,
36443
+ ...alignments.length ? { annotations: alignments } : {}
36444
+ }
36445
+ });
36446
+ } finally {
36447
+ chunks.length = 0;
36448
+ finish();
36449
+ }
36450
+ };
36451
+ const cancel = (error) => {
36452
+ stopped = true;
36453
+ chunks.length = 0;
36454
+ finish(error);
36455
+ };
36456
+ const timestampChunk = (chunk) => {
36457
+ const binary = atob(chunk.audioBase64);
36458
+ observe(Uint8Array.from(binary, (character) => character.charCodeAt(0)));
36459
+ if (chunk.alignment || chunk.normalizedAlignment)
36460
+ alignments.push({
36461
+ alignment: chunk.alignment,
36462
+ normalized_alignment: chunk.normalizedAlignment
36463
+ });
36464
+ };
36465
+ if (method === "convertWithTimestamps") {
36466
+ timestampChunk(value);
36467
+ complete();
36468
+ } else if (method === "streamWithTimestamps") {
36469
+ patchStreamIfNeeded(value, {
36470
+ shouldCollect: (chunk) => {
36471
+ try {
36472
+ timestampChunk(chunk);
36473
+ } catch (error) {
36474
+ debugLogger.error("Error collecting ElevenLabs timestamps", error);
36475
+ cancel();
36476
+ }
36477
+ return false;
36478
+ },
36479
+ onComplete: complete,
36480
+ onCancel: () => cancel(),
36481
+ onError: cancel,
36482
+ aroundNext: (next) => withCurrent(span, next)
36483
+ });
36484
+ } else {
36485
+ observeAudioStream(value, observe, complete, cancel, span);
36486
+ }
36487
+ }
36488
+ function observeAudioStream(value, observe, complete, cancel, span) {
36489
+ let ended = false;
36490
+ const safeObserve = (chunk) => {
36491
+ if (ended) return;
36492
+ try {
36493
+ observe(chunk);
36494
+ } catch (error) {
36495
+ debugLogger.error("Error collecting ElevenLabs audio", error);
36496
+ end(false);
36497
+ }
36498
+ };
36499
+ const end = (success, error) => {
36500
+ if (ended) return;
36501
+ ended = true;
36502
+ try {
36503
+ if (success) complete();
36504
+ else cancel(error);
36505
+ } catch (loggingError) {
36506
+ debugLogger.error("Error logging ElevenLabs audio", loggingError);
36507
+ cancel();
36508
+ }
36509
+ };
36510
+ if (!isObject(value) || !Object.isExtensible(value)) {
36511
+ end(false);
36512
+ return;
36513
+ }
36514
+ if (typeof value.read === "function" && typeof value.on === "function") {
36515
+ value.on("end", () => end(true));
36516
+ value.on("close", () => end(false));
36517
+ const emit2 = value.emit;
36518
+ if (typeof emit2 === "function")
36519
+ value.emit = function(event, ...args) {
36520
+ if (event === "data" && args[0] instanceof Uint8Array)
36521
+ safeObserve(args[0]);
36522
+ if (event === "error") end(false, args[0]);
36523
+ return Reflect.apply(emit2, this, [event, ...args]);
36524
+ };
36525
+ return;
36526
+ }
36527
+ if (typeof value.getReader === "function") {
36528
+ const webStream = value;
36529
+ const pipeTo = webStream.pipeTo;
36530
+ const pipeThrough = webStream.pipeThrough;
36531
+ webStream.pipeTo = function(destination, options) {
36532
+ if (!isObject(destination) || this.locked || destination.locked)
36533
+ return pipeTo.call(this, destination, options);
36534
+ const tap = new TransformStream({
36535
+ transform(chunk, controller) {
36536
+ safeObserve(chunk);
36537
+ controller.enqueue(chunk);
36538
+ },
36539
+ flush() {
36540
+ end(true);
36541
+ }
36542
+ });
36543
+ const observed = pipeThrough.call(
36544
+ this,
36545
+ tap,
36546
+ options
36547
+ );
36548
+ return observed.pipeTo(destination, options).catch((error) => {
36549
+ end(false, error);
36550
+ throw error;
36551
+ });
36552
+ };
36553
+ webStream.pipeThrough = function(transform, options) {
36554
+ if (this.locked || transform.writable.locked || transform.readable.locked)
36555
+ return pipeThrough.call(this, transform, options);
36556
+ const result = webStream.pipeTo.call(this, transform.writable, options);
36557
+ void result.catch(() => {
36558
+ });
36559
+ return transform.readable;
36560
+ };
36561
+ const getReader = value.getReader;
36562
+ value.getReader = function(...args) {
36563
+ const reader = Reflect.apply(getReader, this, args);
36564
+ const read3 = reader.read;
36565
+ reader.read = function(...readArgs) {
36566
+ return Promise.resolve(
36567
+ withCurrent(span, () => Reflect.apply(read3, this, readArgs))
36568
+ ).then(
36569
+ (result) => {
36570
+ if (result.value) safeObserve(result.value);
36571
+ if (result.done) end(true);
36572
+ return result;
36573
+ },
36574
+ (error) => {
36575
+ end(false, error);
36576
+ throw error;
36577
+ }
36578
+ );
36579
+ };
36580
+ const readerCancel = reader.cancel;
36581
+ reader.cancel = function(...cancelArgs) {
36582
+ const result = Reflect.apply(readerCancel, this, cancelArgs);
36583
+ end(false);
36584
+ return result;
36585
+ };
36586
+ return reader;
36587
+ };
36588
+ const streamCancel = value.cancel;
36589
+ if (typeof streamCancel === "function")
36590
+ value.cancel = function(...args) {
36591
+ const result = Reflect.apply(streamCancel, this, args);
36592
+ void Promise.resolve(result).then(
36593
+ () => end(false),
36594
+ () => {
36595
+ }
36596
+ );
36597
+ return result;
36598
+ };
36599
+ }
36600
+ if (typeof value.getReader === "function" && typeof value.values === "function") {
36601
+ const values = value.values;
36602
+ const iterate = function(...args) {
36603
+ const iterator = Reflect.apply(values, this, args);
36604
+ patchStreamIfNeeded(iterator, {
36605
+ shouldCollect(chunk) {
36606
+ safeObserve(chunk);
36607
+ return false;
36608
+ },
36609
+ onComplete: () => end(true),
36610
+ onCancel: () => end(false),
36611
+ onError: (error) => end(false, error),
36612
+ aroundNext: (next) => withCurrent(span, next)
36613
+ });
36614
+ return iterator;
36615
+ };
36616
+ value.values = iterate;
36617
+ Object.defineProperty(value, Symbol.asyncIterator, {
36618
+ configurable: true,
36619
+ writable: true,
36620
+ value: iterate
36621
+ });
36622
+ } else if (isAsyncIterable(value)) {
36623
+ patchStreamIfNeeded(value, {
36624
+ shouldCollect: (chunk) => {
36625
+ safeObserve(chunk);
36626
+ return false;
36627
+ },
36628
+ onComplete: () => end(true),
36629
+ onCancel: () => end(false),
36630
+ onError: (error) => end(false, error),
36631
+ aroundNext: (next) => withCurrent(span, next)
36632
+ });
36633
+ } else if (typeof value.getReader !== "function") end(false);
36634
+ }
36635
+
34709
36636
  // src/instrumentation/plugins/voyageai-channels.ts
34710
36637
  var voyageAIChannels = defineChannels(
34711
36638
  "voyageai",
@@ -34773,7 +36700,7 @@ var VoyageAIPlugin = class extends BasePlugin {
34773
36700
  this.unsubscribers = unsubscribeAll(this.unsubscribers);
34774
36701
  }
34775
36702
  };
34776
- function interceptVoyageAICall(channel2, name, extractInput2, extractOutput2, extractMetrics2 = extractUsageMetrics3) {
36703
+ function interceptVoyageAICall(channel2, name, extractInput3, extractOutput2, extractMetrics2 = extractUsageMetrics3) {
34777
36704
  return channel2.intercept((target, thisArg, args) => {
34778
36705
  const invokeTarget = () => Reflect.apply(target, thisArg, args);
34779
36706
  if (isAutoInstrumentationSuppressed()) {
@@ -34781,7 +36708,7 @@ function interceptVoyageAICall(channel2, name, extractInput2, extractOutput2, ex
34781
36708
  }
34782
36709
  let span;
34783
36710
  try {
34784
- const { input, metadata } = extractInput2(args);
36711
+ const { input, metadata } = extractInput3(args);
34785
36712
  span = startSpan(
34786
36713
  withSpanInstrumentationName(
34787
36714
  {
@@ -35131,14 +37058,14 @@ var CloudflareAIChatPlugin = class extends BasePlugin {
35131
37058
  const result = event.arguments[0];
35132
37059
  state = agent ? this.findResponseState(
35133
37060
  agent,
35134
- stringValue3(ownValue2(result, "requestId"))
37061
+ stringValue4(ownValue2(result, "requestId"))
35135
37062
  ) : void 0;
35136
37063
  if (!state) {
35137
37064
  return;
35138
37065
  }
35139
37066
  state.responseObserved = true;
35140
37067
  const output = serializeMessage(ownValue2(result, "message"));
35141
- const status = stringValue3(ownValue2(result, "status"));
37068
+ const status = stringValue4(ownValue2(result, "status"));
35142
37069
  const error = ownValue2(result, "error");
35143
37070
  const input = ownValue2(result, "continuation") === true ? state.input : serializeMessages(readProperty(agent, "messages"))?.filter(
35144
37071
  (message) => typeof output?.id !== "string" || message.id !== output.id
@@ -35185,7 +37112,7 @@ var CloudflareAIChatPlugin = class extends BasePlugin {
35185
37112
  }
35186
37113
  try {
35187
37114
  const agent = asObject(event.self);
35188
- const requestId = stringValue3(event.arguments[0]);
37115
+ const requestId = stringValue4(event.arguments[0]);
35189
37116
  const key = requestId ?? /* @__PURE__ */ Symbol("cloudflare-ai-chat-turn");
35190
37117
  const activeForAgent = agent ? this.getActiveTurns(agent) : void 0;
35191
37118
  const existing = activeForAgent?.get(key);
@@ -35354,7 +37281,7 @@ function ownValue2(value, key) {
35354
37281
  const descriptor = Object.getOwnPropertyDescriptor(object, key);
35355
37282
  return descriptor && "value" in descriptor ? descriptor.value : void 0;
35356
37283
  }
35357
- function stringValue3(value) {
37284
+ function stringValue4(value) {
35358
37285
  return typeof value === "string" ? value : void 0;
35359
37286
  }
35360
37287
  function serializeMessages(value) {
@@ -35472,7 +37399,7 @@ var CloudflareAgentsPlugin = class extends BasePlugin {
35472
37399
  );
35473
37400
  spans.set(event, span);
35474
37401
  } catch (error) {
35475
- logInstrumentationError6("start", error);
37402
+ logInstrumentationError7("start", error);
35476
37403
  }
35477
37404
  },
35478
37405
  asyncEnd: (event) => {
@@ -35492,7 +37419,7 @@ var CloudflareAgentsPlugin = class extends BasePlugin {
35492
37419
  }
35493
37420
  }
35494
37421
  } catch (error) {
35495
- logInstrumentationError6("completion", error);
37422
+ logInstrumentationError7("completion", error);
35496
37423
  } finally {
35497
37424
  safelyEndSpan(span);
35498
37425
  }
@@ -35506,7 +37433,7 @@ var CloudflareAgentsPlugin = class extends BasePlugin {
35506
37433
  try {
35507
37434
  span.log({ error: event.error });
35508
37435
  } catch (error) {
35509
- logInstrumentationError6("rejection", error);
37436
+ logInstrumentationError7("rejection", error);
35510
37437
  } finally {
35511
37438
  safelyEndSpan(span);
35512
37439
  }
@@ -35536,10 +37463,10 @@ function safelyEndSpan(span) {
35536
37463
  try {
35537
37464
  span.end();
35538
37465
  } catch (error) {
35539
- logInstrumentationError6("span end", error);
37466
+ logInstrumentationError7("span end", error);
35540
37467
  }
35541
37468
  }
35542
- function logInstrumentationError6(operation, error) {
37469
+ function logInstrumentationError7(operation, error) {
35543
37470
  debugLogger.error(
35544
37471
  `Failed to process Cloudflare Agents ${operation} instrumentation:`,
35545
37472
  error
@@ -35557,12 +37484,14 @@ var BraintrustPlugin = class extends BasePlugin {
35557
37484
  cloudflareThinkPlugin = null;
35558
37485
  cursorSDKPlugin = null;
35559
37486
  openAIAgentsPlugin = null;
37487
+ googleGenerativeAIPlugin = null;
35560
37488
  googleGenAIPlugin = null;
35561
37489
  huggingFacePlugin = null;
35562
37490
  huggingFaceTransformersPlugin = null;
35563
37491
  openRouterPlugin = null;
35564
37492
  openRouterAgentPlugin = null;
35565
37493
  mistralPlugin = null;
37494
+ langGraphSDKPlugin = null;
35566
37495
  ollamaPlugin = null;
35567
37496
  googleADKPlugin = null;
35568
37497
  coherePlugin = null;
@@ -35575,6 +37504,7 @@ var BraintrustPlugin = class extends BasePlugin {
35575
37504
  langSmithPlugin = null;
35576
37505
  piCodingAgentPlugin = null;
35577
37506
  strandsAgentSDKPlugin = null;
37507
+ elevenLabsPlugin = null;
35578
37508
  voyageAIPlugin = null;
35579
37509
  cloudflareAIChatPlugin = null;
35580
37510
  cloudflareAgentsPlugin = null;
@@ -35616,6 +37546,10 @@ var BraintrustPlugin = class extends BasePlugin {
35616
37546
  this.openAIAgentsPlugin = new OpenAIAgentsPlugin();
35617
37547
  this.openAIAgentsPlugin.enable();
35618
37548
  }
37549
+ if (integrations.googleGenerativeAI !== false) {
37550
+ this.googleGenerativeAIPlugin = new GoogleGenerativeAIPlugin();
37551
+ this.googleGenerativeAIPlugin.enable();
37552
+ }
35619
37553
  if (integrations.googleGenAI !== false && integrations.google !== false) {
35620
37554
  this.googleGenAIPlugin = new GoogleGenAIPlugin();
35621
37555
  this.googleGenAIPlugin.enable();
@@ -35638,6 +37572,10 @@ var BraintrustPlugin = class extends BasePlugin {
35638
37572
  this.mistralPlugin = new MistralPlugin();
35639
37573
  this.mistralPlugin.enable();
35640
37574
  }
37575
+ if (integrations.langgraphSDK !== false) {
37576
+ this.langGraphSDKPlugin = new LangGraphSDKPlugin();
37577
+ this.langGraphSDKPlugin.enable();
37578
+ }
35641
37579
  if (integrations.ollama !== false) {
35642
37580
  this.ollamaPlugin = new OllamaPlugin();
35643
37581
  this.ollamaPlugin.enable();
@@ -35650,6 +37588,10 @@ var BraintrustPlugin = class extends BasePlugin {
35650
37588
  this.coherePlugin = new CoherePlugin();
35651
37589
  this.coherePlugin.enable();
35652
37590
  }
37591
+ if (integrations.elevenlabs !== false) {
37592
+ this.elevenLabsPlugin = new ElevenLabsPlugin();
37593
+ this.elevenLabsPlugin.enable();
37594
+ }
35653
37595
  if (integrations.voyageai !== false) {
35654
37596
  this.voyageAIPlugin = new VoyageAIPlugin();
35655
37597
  this.voyageAIPlugin.enable();
@@ -35734,6 +37676,10 @@ var BraintrustPlugin = class extends BasePlugin {
35734
37676
  this.openAIAgentsPlugin.disable();
35735
37677
  this.openAIAgentsPlugin = null;
35736
37678
  }
37679
+ if (this.googleGenerativeAIPlugin) {
37680
+ this.googleGenerativeAIPlugin.disable();
37681
+ this.googleGenerativeAIPlugin = null;
37682
+ }
35737
37683
  if (this.googleGenAIPlugin) {
35738
37684
  this.googleGenAIPlugin.disable();
35739
37685
  this.googleGenAIPlugin = null;
@@ -35758,6 +37704,10 @@ var BraintrustPlugin = class extends BasePlugin {
35758
37704
  this.mistralPlugin.disable();
35759
37705
  this.mistralPlugin = null;
35760
37706
  }
37707
+ if (this.langGraphSDKPlugin) {
37708
+ this.langGraphSDKPlugin.disable();
37709
+ this.langGraphSDKPlugin = null;
37710
+ }
35761
37711
  if (this.ollamaPlugin) {
35762
37712
  this.ollamaPlugin.disable();
35763
37713
  this.ollamaPlugin = null;
@@ -35770,6 +37720,10 @@ var BraintrustPlugin = class extends BasePlugin {
35770
37720
  this.coherePlugin.disable();
35771
37721
  this.coherePlugin = null;
35772
37722
  }
37723
+ if (this.elevenLabsPlugin) {
37724
+ this.elevenLabsPlugin.disable();
37725
+ this.elevenLabsPlugin = null;
37726
+ }
35773
37727
  if (this.voyageAIPlugin) {
35774
37728
  this.voyageAIPlugin.disable();
35775
37729
  this.voyageAIPlugin = null;
@@ -35828,7 +37782,31 @@ var MAX_STORED_LLM_INPUTS = 100;
35828
37782
  var MAX_STORED_REASONING_BLOCKS = 100;
35829
37783
  var MAX_STORED_SPAN_REFERENCES = 1e4;
35830
37784
  var MAX_STORED_STEP_STARTS = 1e4;
37785
+ var EVE_HANDLED_EVENT_TYPES = /* @__PURE__ */ new Set([
37786
+ "action.result",
37787
+ "actions.requested",
37788
+ "message.completed",
37789
+ "message.received",
37790
+ "reasoning.completed",
37791
+ "result.completed",
37792
+ "session.completed",
37793
+ "session.failed",
37794
+ "session.started",
37795
+ "step.completed",
37796
+ "step.failed",
37797
+ "step.started",
37798
+ "subagent.called",
37799
+ "subagent.completed",
37800
+ "turn.completed",
37801
+ "turn.failed",
37802
+ "turn.started"
37803
+ ]);
35831
37804
  function braintrustEveHook(options) {
37805
+ if (!options || typeof options.defineState !== "function") {
37806
+ throw new TypeError(
37807
+ "braintrustEveHook requires Eve's defineState function"
37808
+ );
37809
+ }
35832
37810
  const state = options.defineState(EVE_TRACE_STATE_KEY, emptyEveTraceState);
35833
37811
  const bridge = new EveBridge(state);
35834
37812
  return {
@@ -35840,15 +37818,27 @@ function braintrustEveHook(options) {
35840
37818
  };
35841
37819
  }
35842
37820
  function createLegacyEveInstrumentation(options) {
37821
+ if (!options || typeof options.defineState !== "function") {
37822
+ throw new TypeError(
37823
+ "braintrustEveInstrumentation requires Eve's defineState function"
37824
+ );
37825
+ }
35843
37826
  const state = options.defineState(EVE_TRACE_STATE_KEY, emptyEveTraceState);
35844
37827
  return {
35845
37828
  events: {
35846
37829
  "step.started": (input) => {
35847
37830
  try {
37831
+ if (!isEveInstrumentationStepStartedEventInput(input)) {
37832
+ debugLogger.warn(
37833
+ "Ignoring malformed Eve instrumentation step.started event"
37834
+ );
37835
+ return void 0;
37836
+ }
35848
37837
  captureEveModelInput(state, input);
35849
37838
  } catch (error) {
35850
37839
  debugLogger.warn("Error in Eve LLM input capture:", error);
35851
37840
  }
37841
+ return void 0;
35852
37842
  }
35853
37843
  },
35854
37844
  recordInputs: false,
@@ -35857,7 +37847,77 @@ function createLegacyEveInstrumentation(options) {
35857
37847
  };
35858
37848
  }
35859
37849
  function isEveHandleMessageStreamEvent(event) {
35860
- return isObject(event) && typeof event["type"] === "string";
37850
+ if (!isObject(event) || typeof event["type"] !== "string") {
37851
+ return false;
37852
+ }
37853
+ const type = event["type"];
37854
+ if (type === "session.completed") {
37855
+ return true;
37856
+ }
37857
+ if (!isObject(event["data"])) {
37858
+ return false;
37859
+ }
37860
+ const data = event["data"];
37861
+ if (type === "session.started") {
37862
+ return true;
37863
+ }
37864
+ if (type === "session.failed") {
37865
+ return typeof data["sessionId"] === "string" && typeof data["code"] === "string" && typeof data["message"] === "string";
37866
+ }
37867
+ if (type === "session.waiting") {
37868
+ return data["wait"] === "next-user-message";
37869
+ }
37870
+ if (typeof data["turnId"] !== "string" || typeof data["sequence"] !== "number" || !Number.isFinite(data["sequence"])) {
37871
+ return false;
37872
+ }
37873
+ if (type === "turn.started" || type === "turn.completed" || type === "subagent.called" || type === "subagent.completed") {
37874
+ if (type === "subagent.called") {
37875
+ return typeof data["callId"] === "string" && typeof data["childSessionId"] === "string" && typeof data["name"] === "string";
37876
+ }
37877
+ if (type === "subagent.completed") {
37878
+ return typeof data["callId"] === "string" && typeof data["subagentName"] === "string";
37879
+ }
37880
+ return true;
37881
+ }
37882
+ if (type === "turn.failed") {
37883
+ return typeof data["code"] === "string" && typeof data["message"] === "string";
37884
+ }
37885
+ if (type === "message.received") {
37886
+ return typeof data["message"] === "string";
37887
+ }
37888
+ if (typeof data["stepIndex"] !== "number" || !Number.isFinite(data["stepIndex"]) || data["stepIndex"] < 0) {
37889
+ return false;
37890
+ }
37891
+ switch (type) {
37892
+ case "step.started":
37893
+ return true;
37894
+ case "message.completed":
37895
+ return typeof data["finishReason"] === "string" && (typeof data["message"] === "string" || data["message"] === null);
37896
+ case "reasoning.completed":
37897
+ return typeof data["reasoning"] === "string";
37898
+ case "result.completed":
37899
+ return true;
37900
+ case "step.completed":
37901
+ return typeof data["finishReason"] === "string";
37902
+ case "step.failed":
37903
+ return typeof data["code"] === "string" && typeof data["message"] === "string";
37904
+ case "actions.requested":
37905
+ return Array.isArray(data["actions"]);
37906
+ case "action.result":
37907
+ return isObject(data["result"]) && (data["status"] === "completed" || data["status"] === "failed" || data["status"] === "rejected");
37908
+ default:
37909
+ return false;
37910
+ }
37911
+ }
37912
+ function isEveInstrumentationStepStartedEventInput(input) {
37913
+ if (!isObject(input)) {
37914
+ return false;
37915
+ }
37916
+ const modelInput = input["modelInput"];
37917
+ const session = input["session"];
37918
+ const step = input["step"];
37919
+ const turn = input["turn"];
37920
+ 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"]);
35861
37921
  }
35862
37922
  var ResumedEveSpan = class {
35863
37923
  constructor(reference) {
@@ -36026,7 +38086,17 @@ var EveBridge = class {
36026
38086
  });
36027
38087
  }
36028
38088
  async handle(event, ctx, hookMetadata) {
38089
+ try {
38090
+ await this.handleUnchecked(event, ctx, hookMetadata);
38091
+ } catch (error) {
38092
+ debugLogger.warn("Error in Eve hook instrumentation:", error);
38093
+ }
38094
+ }
38095
+ async handleUnchecked(event, ctx, hookMetadata) {
36029
38096
  if (!isEveHandleMessageStreamEvent(event)) {
38097
+ if (isObject(event) && typeof event["type"] === "string" && EVE_HANDLED_EVENT_TYPES.has(event["type"])) {
38098
+ debugLogger.warn(`Ignoring malformed Eve hook ${event["type"]} event`);
38099
+ }
36030
38100
  return;
36031
38101
  }
36032
38102
  const run = async () => {
@@ -36352,9 +38422,14 @@ var EveBridge = class {
36352
38422
  }
36353
38423
  for (const action of traceActions) {
36354
38424
  const name = action.kind === "tool-call" ? action.toolName : action.subagentName ?? action.name ?? "agent";
38425
+ let args = "null";
38426
+ try {
38427
+ args = JSON.stringify(action.input) ?? "null";
38428
+ } catch {
38429
+ }
36355
38430
  toolCallsById.set(action.callId, {
36356
38431
  function: {
36357
- arguments: JSON.stringify(action.input),
38432
+ arguments: args,
36358
38433
  name
36359
38434
  },
36360
38435
  id: action.callId,
@@ -37223,17 +39298,33 @@ function consumeCapturedEveModelInput(state, sessionId, turnId, stepIndex) {
37223
39298
  }
37224
39299
  }
37225
39300
  function capturedModelInput(modelInput) {
37226
- const { instructions, messages } = modelInput;
37227
- const value = [];
37228
- if (typeof instructions === "string") {
37229
- value.push({ content: instructions, role: "system" });
37230
- } else if (Array.isArray(instructions)) {
37231
- value.push(...instructions.map(capturedEveModelMessage));
37232
- } else if (instructions) {
37233
- value.push(capturedEveModelMessage(instructions));
37234
- }
37235
- value.push(...messages.map(capturedEveModelMessage));
37236
39301
  try {
39302
+ if (!isObject(modelInput) || !Array.isArray(modelInput["messages"])) {
39303
+ return void 0;
39304
+ }
39305
+ const value = [];
39306
+ const instructions = modelInput["instructions"];
39307
+ if (typeof instructions === "string") {
39308
+ value.push({ content: instructions, role: "system" });
39309
+ } else if (Array.isArray(instructions)) {
39310
+ for (const instruction of instructions) {
39311
+ const captured = capturedEveModelMessage(instruction);
39312
+ if (captured?.role === "system") {
39313
+ value.push(captured);
39314
+ }
39315
+ }
39316
+ } else {
39317
+ const captured = capturedEveModelMessage(instructions);
39318
+ if (captured?.role === "system") {
39319
+ value.push(captured);
39320
+ }
39321
+ }
39322
+ for (const message of modelInput["messages"]) {
39323
+ const captured = capturedEveModelMessage(message);
39324
+ if (captured) {
39325
+ value.push(captured);
39326
+ }
39327
+ }
37237
39328
  const cloned = JSON.parse(JSON.stringify(value));
37238
39329
  if (!Array.isArray(cloned)) {
37239
39330
  return void 0;
@@ -37244,116 +39335,202 @@ function capturedModelInput(modelInput) {
37244
39335
  }
37245
39336
  }
37246
39337
  function capturedEveModelMessage(message) {
37247
- const { content, role } = message;
39338
+ if (!isObject(message)) {
39339
+ return void 0;
39340
+ }
39341
+ const role = message["role"];
39342
+ if (role !== "system" && role !== "user" && role !== "assistant" && role !== "tool") {
39343
+ return void 0;
39344
+ }
39345
+ const content = message["content"];
37248
39346
  if (typeof content === "string") {
37249
39347
  return { content, role };
37250
39348
  }
37251
- return { content: content.map(capturedEveModelContentPart), role };
39349
+ if (!Array.isArray(content)) {
39350
+ return void 0;
39351
+ }
39352
+ const capturedContent = [];
39353
+ for (const part of content) {
39354
+ const captured = capturedEveModelContentPart(part);
39355
+ if (captured) {
39356
+ capturedContent.push(captured);
39357
+ }
39358
+ }
39359
+ return { content: capturedContent, role };
37252
39360
  }
37253
39361
  function capturedEveModelContentPart(part) {
37254
- switch (part.type) {
39362
+ if (!isObject(part) || typeof part["type"] !== "string") {
39363
+ return void 0;
39364
+ }
39365
+ switch (part["type"]) {
37255
39366
  case "text":
37256
- case "reasoning":
37257
- return { text: part.text, type: part.type };
39367
+ case "reasoning": {
39368
+ const text = part["text"];
39369
+ return typeof text === "string" ? { text, type: part["type"] } : void 0;
39370
+ }
37258
39371
  case "image":
39372
+ if (!Object.hasOwn(part, "image")) {
39373
+ return void 0;
39374
+ }
37259
39375
  return {
37260
- image: part.image,
37261
- ...part.mediaType !== void 0 ? { mediaType: part.mediaType } : {},
39376
+ image: part["image"],
39377
+ ...typeof part["mediaType"] === "string" ? { mediaType: part["mediaType"] } : {},
37262
39378
  type: "image"
37263
39379
  };
37264
39380
  case "file":
37265
- case "reasoning-file":
39381
+ case "reasoning-file": {
39382
+ if (!Object.hasOwn(part, "data") || typeof part["mediaType"] !== "string") {
39383
+ return void 0;
39384
+ }
37266
39385
  return {
37267
- data: part.data,
37268
- ...part.type === "file" && part.filename !== void 0 ? { filename: part.filename } : {},
37269
- mediaType: part.mediaType,
37270
- type: part.type
39386
+ data: part["data"],
39387
+ ...part["type"] === "file" && typeof part["filename"] === "string" ? { filename: part["filename"] } : {},
39388
+ mediaType: part["mediaType"],
39389
+ type: part["type"]
37271
39390
  };
39391
+ }
37272
39392
  case "custom":
37273
39393
  return {
37274
- ..."kind" in part ? { kind: part.kind } : {},
39394
+ ...typeof part["kind"] === "string" ? { kind: part["kind"] } : {},
37275
39395
  type: "custom"
37276
39396
  };
37277
- case "tool-call":
39397
+ case "tool-call": {
39398
+ if (typeof part["toolCallId"] !== "string" || typeof part["toolName"] !== "string") {
39399
+ return void 0;
39400
+ }
37278
39401
  return {
37279
- input: part.input,
37280
- ...part.providerExecuted !== void 0 ? { providerExecuted: part.providerExecuted } : {},
37281
- toolCallId: part.toolCallId,
37282
- toolName: part.toolName,
39402
+ input: part["input"],
39403
+ ...typeof part["providerExecuted"] === "boolean" ? { providerExecuted: part["providerExecuted"] } : {},
39404
+ toolCallId: part["toolCallId"],
39405
+ toolName: part["toolName"],
37283
39406
  type: "tool-call"
37284
39407
  };
39408
+ }
37285
39409
  case "tool-result": {
37286
- const output = part.output;
39410
+ const output = part["output"];
39411
+ if (typeof part["toolCallId"] !== "string" || typeof part["toolName"] !== "string" || !isObject(output) || typeof output["type"] !== "string") {
39412
+ return void 0;
39413
+ }
37287
39414
  let capturedOutput;
37288
- switch (output.type) {
39415
+ switch (output["type"]) {
37289
39416
  case "text":
37290
- case "error-text":
37291
- capturedOutput = { type: output.type, value: output.value };
39417
+ case "error-text": {
39418
+ if (typeof output["value"] !== "string") {
39419
+ return void 0;
39420
+ }
39421
+ capturedOutput = {
39422
+ type: output["type"],
39423
+ value: output["value"]
39424
+ };
37292
39425
  break;
39426
+ }
37293
39427
  case "json":
37294
39428
  case "error-json":
37295
- capturedOutput = { type: output.type, value: output.value };
39429
+ capturedOutput = {
39430
+ type: output["type"],
39431
+ value: output["value"]
39432
+ };
37296
39433
  break;
37297
39434
  case "execution-denied":
37298
39435
  capturedOutput = {
37299
- ...output.reason !== void 0 ? { reason: output.reason } : {},
39436
+ ...typeof output["reason"] === "string" ? { reason: output["reason"] } : {},
37300
39437
  type: "execution-denied"
37301
39438
  };
37302
39439
  break;
37303
- case "content":
39440
+ case "content": {
39441
+ if (!Array.isArray(output["value"])) {
39442
+ return void 0;
39443
+ }
39444
+ const value = [];
39445
+ for (const outputPart of output["value"]) {
39446
+ const captured = capturedEveModelContentPart(outputPart);
39447
+ if (captured) {
39448
+ value.push(captured);
39449
+ }
39450
+ }
37304
39451
  capturedOutput = {
37305
39452
  type: "content",
37306
- value: output.value.map(capturedEveModelContentPart)
39453
+ value
37307
39454
  };
37308
39455
  break;
39456
+ }
39457
+ default:
39458
+ return void 0;
37309
39459
  }
37310
39460
  return {
37311
39461
  output: capturedOutput,
37312
- toolCallId: part.toolCallId,
37313
- toolName: part.toolName,
39462
+ toolCallId: part["toolCallId"],
39463
+ toolName: part["toolName"],
37314
39464
  type: "tool-result"
37315
39465
  };
37316
39466
  }
37317
- case "tool-approval-request":
39467
+ case "tool-approval-request": {
39468
+ if (typeof part["approvalId"] !== "string" || typeof part["toolCallId"] !== "string") {
39469
+ return void 0;
39470
+ }
37318
39471
  return {
37319
- approvalId: part.approvalId,
37320
- ...part.isAutomatic !== void 0 ? { isAutomatic: part.isAutomatic } : {},
37321
- ...part.signature !== void 0 ? { signature: part.signature } : {},
37322
- toolCallId: part.toolCallId,
39472
+ approvalId: part["approvalId"],
39473
+ ...typeof part["isAutomatic"] === "boolean" ? { isAutomatic: part["isAutomatic"] } : {},
39474
+ ...typeof part["signature"] === "string" ? { signature: part["signature"] } : {},
39475
+ toolCallId: part["toolCallId"],
37323
39476
  type: "tool-approval-request"
37324
39477
  };
37325
- case "tool-approval-response":
39478
+ }
39479
+ case "tool-approval-response": {
39480
+ if (typeof part["approvalId"] !== "string" || typeof part["approved"] !== "boolean") {
39481
+ return void 0;
39482
+ }
37326
39483
  return {
37327
- approvalId: part.approvalId,
37328
- approved: part.approved,
37329
- ...part.providerExecuted !== void 0 ? { providerExecuted: part.providerExecuted } : {},
37330
- ...part.reason !== void 0 ? { reason: part.reason } : {},
39484
+ approvalId: part["approvalId"],
39485
+ approved: part["approved"],
39486
+ ...typeof part["providerExecuted"] === "boolean" ? { providerExecuted: part["providerExecuted"] } : {},
39487
+ ...typeof part["reason"] === "string" ? { reason: part["reason"] } : {},
37331
39488
  type: "tool-approval-response"
37332
39489
  };
39490
+ }
37333
39491
  case "file-data":
37334
- case "image-data":
39492
+ case "image-data": {
39493
+ if (typeof part["data"] !== "string" || typeof part["mediaType"] !== "string") {
39494
+ return void 0;
39495
+ }
37335
39496
  return {
37336
- data: part.data,
37337
- ...part.type === "file-data" && part.filename !== void 0 ? { filename: part.filename } : {},
37338
- mediaType: part.mediaType,
37339
- type: part.type
39497
+ data: part["data"],
39498
+ ...part["type"] === "file-data" && typeof part["filename"] === "string" ? { filename: part["filename"] } : {},
39499
+ mediaType: part["mediaType"],
39500
+ type: part["type"]
37340
39501
  };
39502
+ }
37341
39503
  case "file-url":
37342
- case "image-url":
39504
+ case "image-url": {
39505
+ if (typeof part["url"] !== "string") {
39506
+ return void 0;
39507
+ }
37343
39508
  return {
37344
- ...part.type === "file-url" && part.mediaType !== void 0 ? { mediaType: part.mediaType } : {},
37345
- type: part.type,
37346
- url: part.url
39509
+ ...part["type"] === "file-url" && typeof part["mediaType"] === "string" ? { mediaType: part["mediaType"] } : {},
39510
+ type: part["type"],
39511
+ url: part["url"]
37347
39512
  };
39513
+ }
37348
39514
  case "file-id":
37349
- case "image-file-id":
37350
- return { fileId: part.fileId, type: part.type };
39515
+ case "image-file-id": {
39516
+ const fileId = part["fileId"];
39517
+ if (typeof fileId !== "string" && !isObject(fileId)) {
39518
+ return void 0;
39519
+ }
39520
+ return { fileId, type: part["type"] };
39521
+ }
37351
39522
  case "file-reference":
37352
- case "image-file-reference":
39523
+ case "image-file-reference": {
39524
+ if (!isObject(part["providerReference"])) {
39525
+ return void 0;
39526
+ }
37353
39527
  return {
37354
- providerReference: part.providerReference,
37355
- type: part.type
39528
+ providerReference: part["providerReference"],
39529
+ type: part["type"]
37356
39530
  };
39531
+ }
39532
+ default:
39533
+ return void 0;
37357
39534
  }
37358
39535
  }
37359
39536
  function isCapturedModelInput(input) {
@@ -37489,18 +39666,54 @@ function createEveInstrumentationProvider(options = {}) {
37489
39666
  recordOutputs: true
37490
39667
  }),
37491
39668
  events: {
37492
- "action.completed": (event, context) => bridge.handleActionTerminal(event, context),
37493
- "action.failed": (event, context) => bridge.handleActionTerminal(event, context),
37494
- "action.started": (event, context) => bridge.handleActionStarted(event, context),
37495
- "model.call.completed": (event, context) => bridge.handleModelTerminal(event, context),
37496
- "model.call.failed": (event, context) => bridge.handleModelTerminal(event, context),
37497
- "model.call.started": (event, context) => bridge.handleModelStarted(event, context),
37498
- "step.attempt.completed": (event) => bridge.handleStepAttemptTerminal(event),
37499
- "step.attempt.failed": (event) => bridge.handleStepAttemptTerminal(event),
37500
- "turn.cancelled": (event, context) => bridge.handleTurnTerminal(event, context),
37501
- "turn.completed": (event, context) => bridge.handleTurnTerminal(event, context),
37502
- "turn.failed": (event, context) => bridge.handleTurnTerminal(event, context),
37503
- "turn.started": (event, context) => bridge.handleTurnStarted(event, context)
39669
+ "action.completed": providerHandler(
39670
+ "action.completed",
39671
+ bridge.handleActionTerminal.bind(bridge)
39672
+ ),
39673
+ "action.failed": providerHandler(
39674
+ "action.failed",
39675
+ bridge.handleActionTerminal.bind(bridge)
39676
+ ),
39677
+ "action.started": providerHandler(
39678
+ "action.started",
39679
+ bridge.handleActionStarted.bind(bridge)
39680
+ ),
39681
+ "model.call.completed": providerHandler(
39682
+ "model.call.completed",
39683
+ bridge.handleModelTerminal.bind(bridge)
39684
+ ),
39685
+ "model.call.failed": providerHandler(
39686
+ "model.call.failed",
39687
+ bridge.handleModelTerminal.bind(bridge)
39688
+ ),
39689
+ "model.call.started": providerHandler(
39690
+ "model.call.started",
39691
+ bridge.handleModelStarted.bind(bridge)
39692
+ ),
39693
+ "step.attempt.completed": providerHandler(
39694
+ "step.attempt.completed",
39695
+ (event) => bridge.handleStepAttemptTerminal(event)
39696
+ ),
39697
+ "step.attempt.failed": providerHandler(
39698
+ "step.attempt.failed",
39699
+ (event) => bridge.handleStepAttemptTerminal(event)
39700
+ ),
39701
+ "turn.cancelled": providerHandler(
39702
+ "turn.cancelled",
39703
+ bridge.handleTurnTerminal.bind(bridge)
39704
+ ),
39705
+ "turn.completed": providerHandler(
39706
+ "turn.completed",
39707
+ bridge.handleTurnTerminal.bind(bridge)
39708
+ ),
39709
+ "turn.failed": providerHandler(
39710
+ "turn.failed",
39711
+ bridge.handleTurnTerminal.bind(bridge)
39712
+ ),
39713
+ "turn.started": providerHandler(
39714
+ "turn.started",
39715
+ bridge.handleTurnStarted.bind(bridge)
39716
+ )
37504
39717
  },
37505
39718
  flush,
37506
39719
  setup: options.setup
@@ -37856,17 +40069,20 @@ function modelOutput(event) {
37856
40069
  const reasoning = [];
37857
40070
  const toolCalls = [];
37858
40071
  for (const part of content) {
37859
- if (part.type === "text") {
37860
- text += part.text;
37861
- } else if (part.type === "reasoning" && part.text.trim().length > 0) {
37862
- reasoning.push({ content: part.text });
37863
- } else if (part.type === "tool-call") {
40072
+ if (!isObject(part)) {
40073
+ continue;
40074
+ }
40075
+ if (part["type"] === "text" && typeof part["text"] === "string") {
40076
+ text += part["text"];
40077
+ } else if (part["type"] === "reasoning" && typeof part["text"] === "string" && part["text"].trim().length > 0) {
40078
+ reasoning.push({ content: part["text"] });
40079
+ } else if (part["type"] === "tool-call" && typeof part["toolName"] === "string" && typeof part["callId"] === "string") {
37864
40080
  toolCalls.push({
37865
40081
  function: {
37866
- arguments: safeJsonStringify(part.input),
37867
- name: part.toolName
40082
+ arguments: safeJsonStringify(part["input"]),
40083
+ name: part["toolName"]
37868
40084
  },
37869
- id: part.callId,
40085
+ id: part["callId"],
37870
40086
  type: "function"
37871
40087
  });
37872
40088
  }
@@ -37885,13 +40101,13 @@ function modelOutput(event) {
37885
40101
  ];
37886
40102
  }
37887
40103
  function usageMetrics(usage) {
37888
- const promptTokens = nonNegativeNumber(usage.inputTokens);
37889
- const completionTokens = nonNegativeNumber(usage.outputTokens);
40104
+ const promptTokens = nonNegativeNumber(usage?.inputTokens);
40105
+ const completionTokens = nonNegativeNumber(usage?.outputTokens);
37890
40106
  const cachedTokens = nonNegativeNumber(
37891
- usage.inputTokenDetails?.cacheReadTokens
40107
+ usage?.inputTokenDetails?.cacheReadTokens
37892
40108
  );
37893
40109
  const cacheCreationTokens = nonNegativeNumber(
37894
- usage.inputTokenDetails?.cacheWriteTokens
40110
+ usage?.inputTokenDetails?.cacheWriteTokens
37895
40111
  );
37896
40112
  return {
37897
40113
  ...promptTokens !== void 0 ? { prompt_tokens: promptTokens } : {},
@@ -37928,10 +40144,76 @@ function turnIdempotencyKey(sessionId, turnId) {
37928
40144
  function actionIdempotencyKey(sessionId, turnId, callId) {
37929
40145
  return `action:${sessionId}:${turnId}:${callId}`;
37930
40146
  }
40147
+ function providerHandler(type, handler) {
40148
+ return async (event, context) => {
40149
+ try {
40150
+ if (!isEveProviderEvent(event, type) || !isEveProviderContext(context)) {
40151
+ debugLogger.warn(`Ignoring malformed Eve provider ${type} event`);
40152
+ return;
40153
+ }
40154
+ await handler(event, context);
40155
+ } catch (error) {
40156
+ debugLogger.warn(`Error in Eve provider ${type}:`, error);
40157
+ }
40158
+ };
40159
+ }
40160
+ function isEveProviderEvent(event, type) {
40161
+ if (!isObject(event) || event["type"] !== type || typeof event["idempotencyKey"] !== "string" || event["idempotencyKey"].length === 0) {
40162
+ return false;
40163
+ }
40164
+ if (type === "turn.started") {
40165
+ const parentLineage = event["parentLineage"];
40166
+ 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));
40167
+ }
40168
+ if (type === "turn.cancelled" || type === "turn.completed" || type === "turn.failed") {
40169
+ return typeof event["sessionId"] === "string" && typeof event["turnId"] === "string";
40170
+ }
40171
+ if (!isEveProviderScope(event["scope"])) {
40172
+ return false;
40173
+ }
40174
+ if (type === "model.call.started") {
40175
+ const model = event["model"];
40176
+ return isObject(model) && typeof model["modelId"] === "string" && typeof model["provider"] === "string";
40177
+ }
40178
+ if (type === "model.call.completed") {
40179
+ return typeof event["finishReason"] === "string" && isObject(event["usage"]) && (event["content"] === void 0 || Array.isArray(event["content"]));
40180
+ }
40181
+ if (type === "model.call.failed") {
40182
+ return true;
40183
+ }
40184
+ if (type === "action.started") {
40185
+ 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");
40186
+ }
40187
+ if (type === "action.completed") {
40188
+ const output = event["output"];
40189
+ return event["outcome"] === "completed" && isObject(output) && (output["type"] === "result" || output["type"] === "error");
40190
+ }
40191
+ if (type === "action.failed") {
40192
+ return event["outcome"] === "abandoned" || event["outcome"] === "cancelled" || event["outcome"] === "failed" || event["outcome"] === "rejected";
40193
+ }
40194
+ return type === "step.attempt.completed" || type === "step.attempt.failed";
40195
+ }
40196
+ function isEveProviderContext(value) {
40197
+ if (!isObject(value) || !isObject(value["state"])) {
40198
+ return false;
40199
+ }
40200
+ return typeof value["state"]["get"] === "function" && typeof value["state"]["set"] === "function";
40201
+ }
40202
+ function isEveProviderScope(value) {
40203
+ 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");
40204
+ }
40205
+ function isEveProviderParentLineage(value) {
40206
+ return isObject(value) && typeof value["callId"] === "string" && typeof value["sessionId"] === "string" && typeof value["turnId"] === "string";
40207
+ }
37931
40208
 
37932
40209
  // src/instrumentation/plugins/eve-instrumentation.ts
37933
40210
  var EVE_INSTRUMENTATION_PROVIDER = /* @__PURE__ */ Symbol.for("eve.instrumentation.provider");
37934
40211
  function braintrustEveInstrumentation(options) {
40212
+ if (!options || typeof options !== "object") {
40213
+ throw new TypeError(
40214
+ "braintrustEveInstrumentation requires an options object"
40215
+ );
40216
+ }
37935
40217
  const definition = "defineState" in options ? createLegacyEveInstrumentation(options) : createEveInstrumentationProvider(options);
37936
40218
  const declaration = {
37937
40219
  ...definition,
@@ -37982,6 +40264,8 @@ var envIntegrationAliases = {
37982
40264
  "openai-agents-core": "openAIAgents",
37983
40265
  openaiagentscore: "openAIAgents",
37984
40266
  google: "google",
40267
+ "google-generative-ai": "googleGenerativeAI",
40268
+ googlegenerativeai: "googleGenerativeAI",
37985
40269
  "google-genai": "googleGenAI",
37986
40270
  googlegenai: "googleGenAI",
37987
40271
  huggingface: "huggingface",
@@ -38012,10 +40296,15 @@ var envIntegrationAliases = {
38012
40296
  "langchain-js": "langchain",
38013
40297
  "@langchain": "langchain",
38014
40298
  langgraph: "langgraph",
40299
+ langgraphsdk: "langgraphSDK",
40300
+ "langgraph-sdk": "langgraphSDK",
40301
+ "@langchain/langgraph-sdk": "langgraphSDK",
38015
40302
  langsmith: "langsmith",
38016
40303
  voyage: "voyageai",
38017
40304
  "voyage-ai": "voyageai",
38018
- voyageai: "voyageai"
40305
+ voyageai: "voyageai",
40306
+ elevenlabs: "elevenlabs",
40307
+ "@elevenlabs/elevenlabs-js": "elevenlabs"
38019
40308
  };
38020
40309
  function getDefaultInstrumentationIntegrations() {
38021
40310
  return {
@@ -38026,6 +40315,7 @@ function getDefaultInstrumentationIntegrations() {
38026
40315
  aisdk: true,
38027
40316
  google: true,
38028
40317
  googleGenAI: true,
40318
+ googleGenerativeAI: true,
38029
40319
  googleADK: true,
38030
40320
  huggingface: true,
38031
40321
  claudeAgentSDK: true,
@@ -38049,8 +40339,10 @@ function getDefaultInstrumentationIntegrations() {
38049
40339
  gitHubCopilot: true,
38050
40340
  langchain: true,
38051
40341
  langgraph: true,
40342
+ langgraphSDK: true,
38052
40343
  langsmith: true,
38053
40344
  voyageai: true,
40345
+ elevenlabs: true,
38054
40346
  piCodingAgent: true,
38055
40347
  strandsAgentSDK: true,
38056
40348
  cloudflareAgents: true