braintrust 3.32.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 (60) hide show
  1. package/README.md +0 -43
  2. package/dev/dist/index.d.mts +31 -0
  3. package/dev/dist/index.d.ts +31 -0
  4. package/dev/dist/index.js +2275 -920
  5. package/dev/dist/index.mjs +1610 -255
  6. package/dist/apply-auto-instrumentation.js +263 -224
  7. package/dist/apply-auto-instrumentation.mjs +45 -6
  8. package/dist/auto-instrumentations/bundler/esbuild.cjs +78 -5
  9. package/dist/auto-instrumentations/bundler/esbuild.mjs +2 -2
  10. package/dist/auto-instrumentations/bundler/next.cjs +78 -5
  11. package/dist/auto-instrumentations/bundler/next.mjs +3 -3
  12. package/dist/auto-instrumentations/bundler/rollup.cjs +78 -5
  13. package/dist/auto-instrumentations/bundler/rollup.mjs +2 -2
  14. package/dist/auto-instrumentations/bundler/vite.cjs +78 -5
  15. package/dist/auto-instrumentations/bundler/vite.mjs +2 -2
  16. package/dist/auto-instrumentations/bundler/webpack-loader.cjs +78 -5
  17. package/dist/auto-instrumentations/bundler/webpack.cjs +78 -5
  18. package/dist/auto-instrumentations/bundler/webpack.mjs +3 -3
  19. package/dist/auto-instrumentations/{chunk-AFND2U7E.mjs → chunk-T2DMPWFI.mjs} +75 -5
  20. package/dist/auto-instrumentations/{chunk-RI4Y55ZF.mjs → chunk-UHJ2DNYJ.mjs} +6 -1
  21. package/dist/auto-instrumentations/{chunk-QEEPRBIS.mjs → chunk-W5QNG3PV.mjs} +1 -1
  22. package/dist/auto-instrumentations/hook.mjs +86 -7
  23. package/dist/auto-instrumentations/index.cjs +76 -5
  24. package/dist/auto-instrumentations/index.d.mts +3 -1
  25. package/dist/auto-instrumentations/index.d.ts +3 -1
  26. package/dist/auto-instrumentations/index.mjs +3 -1
  27. package/dist/browser.d.mts +202 -342
  28. package/dist/browser.d.ts +202 -342
  29. package/dist/browser.js +2586 -623
  30. package/dist/browser.mjs +2586 -623
  31. package/dist/chunk-7P6ASYW6.mjs +9 -0
  32. package/dist/{chunk-BTRLPQG5.js → chunk-AXJTOUOC.js} +2250 -1172
  33. package/dist/{chunk-AW4QECG5.js → chunk-G3VHOHRC.js} +40 -9
  34. package/dist/chunk-MLKGABMK.js +9 -0
  35. package/dist/{chunk-4QSAHP7D.mjs → chunk-MZLBAFVJ.mjs} +1236 -158
  36. package/dist/{chunk-WV6QZI2W.mjs → chunk-TZVZN2JJ.mjs} +39 -8
  37. package/dist/cli.js +1695 -293
  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 +2586 -623
  45. package/dist/edge-light.mjs +2586 -623
  46. package/dist/index.d.mts +202 -342
  47. package/dist/index.d.ts +202 -342
  48. package/dist/index.js +1842 -986
  49. package/dist/index.mjs +1310 -454
  50. package/dist/instrumentation/index.d.mts +5 -245
  51. package/dist/instrumentation/index.d.ts +5 -245
  52. package/dist/instrumentation/index.js +1694 -254
  53. package/dist/instrumentation/index.mjs +1694 -254
  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 +2586 -623
  59. package/dist/workerd.mjs +2586 -623
  60. package/package.json +10 -2
package/dist/cli.js CHANGED
@@ -41,7 +41,7 @@ var require_async = __commonJS({
41
41
  "use strict";
42
42
  Object.defineProperty(exports2, "__esModule", { value: true });
43
43
  exports2.read = void 0;
44
- function read2(path9, settings, callback) {
44
+ function read3(path9, settings, callback) {
45
45
  settings.fs.lstat(path9, (lstatError, lstat) => {
46
46
  if (lstatError !== null) {
47
47
  callFailureCallback(callback, lstatError);
@@ -67,7 +67,7 @@ var require_async = __commonJS({
67
67
  });
68
68
  });
69
69
  }
70
- exports2.read = read2;
70
+ exports2.read = read3;
71
71
  function callFailureCallback(callback, error2) {
72
72
  callback(error2);
73
73
  }
@@ -83,7 +83,7 @@ var require_sync = __commonJS({
83
83
  "use strict";
84
84
  Object.defineProperty(exports2, "__esModule", { value: true });
85
85
  exports2.read = void 0;
86
- function read2(path9, settings) {
86
+ function read3(path9, settings) {
87
87
  const lstat = settings.fs.lstatSync(path9);
88
88
  if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
89
89
  return lstat;
@@ -101,7 +101,7 @@ var require_sync = __commonJS({
101
101
  throw error2;
102
102
  }
103
103
  }
104
- exports2.read = read2;
104
+ exports2.read = read3;
105
105
  }
106
106
  });
107
107
 
@@ -327,14 +327,14 @@ var require_async2 = __commonJS({
327
327
  var constants_1 = require_constants();
328
328
  var utils = require_utils();
329
329
  var common = require_common();
330
- function read2(directory, settings, callback) {
330
+ function read3(directory, settings, callback) {
331
331
  if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
332
332
  readdirWithFileTypes(directory, settings, callback);
333
333
  return;
334
334
  }
335
335
  readdir2(directory, settings, callback);
336
336
  }
337
- exports2.read = read2;
337
+ exports2.read = read3;
338
338
  function readdirWithFileTypes(directory, settings, callback) {
339
339
  settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => {
340
340
  if (readdirError !== null) {
@@ -436,13 +436,13 @@ var require_sync2 = __commonJS({
436
436
  var constants_1 = require_constants();
437
437
  var utils = require_utils();
438
438
  var common = require_common();
439
- function read2(directory, settings) {
439
+ function read3(directory, settings) {
440
440
  if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
441
441
  return readdirWithFileTypes(directory, settings);
442
442
  }
443
443
  return readdir2(directory, settings);
444
444
  }
445
- exports2.read = read2;
445
+ exports2.read = read3;
446
446
  function readdirWithFileTypes(directory, settings) {
447
447
  const dirents = settings.fs.readdirSync(directory, { withFileTypes: true });
448
448
  return dirents.map((dirent) => {
@@ -1236,7 +1236,7 @@ var require_package = __commonJS({
1236
1236
  "package.json"(exports2, module2) {
1237
1237
  module2.exports = {
1238
1238
  name: "braintrust",
1239
- version: "3.32.0",
1239
+ version: "3.33.0",
1240
1240
  description: "SDK for integrating Braintrust",
1241
1241
  repository: {
1242
1242
  type: "git",
@@ -1273,6 +1273,13 @@ var require_package = __commonJS({
1273
1273
  require: "./dist/index.js",
1274
1274
  default: "./dist/index.mjs"
1275
1275
  },
1276
+ "./custom-views": {
1277
+ types: "./dist/custom-views.d.ts",
1278
+ import: "./dist/custom-views.mjs",
1279
+ module: "./dist/custom-views.mjs",
1280
+ require: "./dist/custom-views.js",
1281
+ default: "./dist/custom-views.mjs"
1282
+ },
1276
1283
  "./workerd": {
1277
1284
  import: "./dist/workerd.mjs",
1278
1285
  require: "./dist/workerd.js",
@@ -1444,12 +1451,13 @@ var require_package = __commonJS({
1444
1451
  typescript: "5.4.4",
1445
1452
  vite: "^8.1.5",
1446
1453
  "vite-tsconfig-paths": "^4.3.2",
1447
- vitest: "4.1.5",
1454
+ vitest: "4.1.11",
1448
1455
  webpack: "^5.106.2",
1449
1456
  zod: "^3.25.34"
1450
1457
  },
1451
1458
  dependencies: {
1452
1459
  "@next/env": "^14.2.3",
1460
+ "@types/react": "^18.3.1",
1453
1461
  "@vercel/functions": "^1.0.2",
1454
1462
  acorn: "^8.16.0",
1455
1463
  "acorn-import-attributes": "^1.9.5",
@@ -1516,7 +1524,7 @@ var import_node_util5 = __toESM(require("node:util"));
1516
1524
  var fsWalk = __toESM(require_out3());
1517
1525
  var import_minimatch = require("minimatch");
1518
1526
  var import_argparse = require("argparse");
1519
- var import_uuid3 = require("uuid");
1527
+ var import_uuid4 = require("uuid");
1520
1528
  var import_pluralize4 = __toESM(require("pluralize"));
1521
1529
 
1522
1530
  // src/logger.ts
@@ -7207,6 +7215,7 @@ var INSTRUMENTATION_NAMES = {
7207
7215
  LANGSMITH: "langsmith",
7208
7216
  MASTRA: "mastra",
7209
7217
  MISTRAL: "mistral",
7218
+ LANGGRAPH_SDK: "langgraph-sdk",
7210
7219
  OLLAMA: "ollama",
7211
7220
  OPENAI: "openai",
7212
7221
  OPENAI_AGENTS: "openai-agents",
@@ -7221,7 +7230,7 @@ var INSTRUMENTATION_NAMES = {
7221
7230
  var INTERNAL_SPAN_INSTRUMENTATION_NAME = /* @__PURE__ */ Symbol.for(
7222
7231
  "braintrust.spanInstrumentationName"
7223
7232
  );
7224
- var SDK_VERSION = true ? "3.32.0" : "0.0.0";
7233
+ var SDK_VERSION = true ? "3.33.0" : "0.0.0";
7225
7234
  function withSpanInstrumentationName(args, instrumentationName) {
7226
7235
  return {
7227
7236
  ...args,
@@ -10462,6 +10471,38 @@ function getSpanParentObjectAndPropagatedState(options) {
10462
10471
  function getSpanParentObject(options) {
10463
10472
  return getSpanParentObjectAndPropagatedState(options).parentObject;
10464
10473
  }
10474
+ function _internalExportParentSynchronously(parent) {
10475
+ if ("toStr" in parent) {
10476
+ return parent.toStr();
10477
+ }
10478
+ if ("getParentInfo" in parent) {
10479
+ const parentInfo = parent.getParentInfo();
10480
+ if (!parentInfo) {
10481
+ return void 0;
10482
+ }
10483
+ const objectId = parentInfo.objectId.getSync().value;
10484
+ if (!objectId && !parentInfo.computeObjectMetadataArgs) {
10485
+ return void 0;
10486
+ }
10487
+ return new SpanComponentsV4({
10488
+ object_type: parentInfo.objectType,
10489
+ ...objectId ? { object_id: objectId } : {
10490
+ compute_object_metadata_args: parentInfo.computeObjectMetadataArgs ?? {}
10491
+ },
10492
+ row_id: parent.id,
10493
+ root_span_id: parent.rootSpanId,
10494
+ span_id: parent.spanId
10495
+ }).toStr();
10496
+ }
10497
+ const components = braintrustParentToComponents(parent._getOtelParent());
10498
+ if (!components) {
10499
+ return void 0;
10500
+ }
10501
+ return new SpanComponentsV4({
10502
+ object_type: components.objectType,
10503
+ ...components.objectId ? { object_id: components.objectId } : { compute_object_metadata_args: components.computeArgs ?? {} }
10504
+ }).toStr();
10505
+ }
10465
10506
  function currentBraintrustParent(state) {
10466
10507
  const resolvedState = state ?? _globalState;
10467
10508
  const experiment = currentExperiment({ state: resolvedState });
@@ -11842,10 +11883,16 @@ var SpanImpl = class _SpanImpl {
11842
11883
  inject(carrier) {
11843
11884
  const resolvedCarrier = carrier ?? {};
11844
11885
  try {
11886
+ const braintrustParent = this._getOtelParent() ?? this._propagatedState?.braintrustParent;
11887
+ if (!braintrustParent) {
11888
+ debugLogger.forState(this._state).warn(
11889
+ "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."
11890
+ );
11891
+ }
11845
11892
  _injectIntoCarrier(resolvedCarrier, {
11846
11893
  traceId: this._rootSpanId,
11847
11894
  spanId: this._spanId,
11848
- braintrustParent: this._getOtelParent() ?? this._propagatedState?.braintrustParent,
11895
+ braintrustParent,
11849
11896
  propagatedState: this._propagatedState
11850
11897
  });
11851
11898
  } catch (e) {
@@ -13910,6 +13957,9 @@ function waterfall(tasks, callback) {
13910
13957
  }
13911
13958
  var waterfall$1 = awaitify(waterfall);
13912
13959
 
13960
+ // src/framework.ts
13961
+ var import_uuid3 = require("uuid");
13962
+
13913
13963
  // src/functions/invoke.ts
13914
13964
  async function invoke(args) {
13915
13965
  const {
@@ -13992,11 +14042,268 @@ async function invoke(args) {
13992
14042
  }
13993
14043
 
13994
14044
  // src/trace.ts
14045
+ var spanFilterFields = /* @__PURE__ */ new Set([
14046
+ "spanType",
14047
+ "name",
14048
+ "hasError",
14049
+ "metadata",
14050
+ "duration"
14051
+ ]);
14052
+ function isRecord(value) {
14053
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
14054
+ return false;
14055
+ }
14056
+ const prototype2 = Object.getPrototypeOf(value);
14057
+ return prototype2 === Object.prototype || prototype2 === null;
14058
+ }
14059
+ function validateMetadataValue(value, ancestors) {
14060
+ if (value === null || typeof value === "string" || typeof value === "boolean") {
14061
+ return;
14062
+ }
14063
+ if (typeof value === "number") {
14064
+ if (Number.isFinite(value)) {
14065
+ return;
14066
+ }
14067
+ throw new Error("filters.metadata numbers must be finite");
14068
+ }
14069
+ if (typeof value !== "object" || value === null) {
14070
+ throw new Error("filters.metadata values must be JSON-serializable");
14071
+ }
14072
+ if (!Array.isArray(value) && !isRecord(value)) {
14073
+ throw new Error("filters.metadata values must be JSON-serializable");
14074
+ }
14075
+ if (ancestors.has(value)) {
14076
+ throw new Error("filters.metadata must not contain cycles");
14077
+ }
14078
+ ancestors.add(value);
14079
+ if (Array.isArray(value)) {
14080
+ for (let index = 0; index < value.length; index++) {
14081
+ validateMetadataValue(value[index], ancestors);
14082
+ }
14083
+ } else {
14084
+ if (Object.getOwnPropertySymbols(value).length > 0) {
14085
+ throw new Error("filters.metadata keys must be strings");
14086
+ }
14087
+ for (const nested of Object.values(value)) {
14088
+ validateMetadataValue(nested, ancestors);
14089
+ }
14090
+ }
14091
+ ancestors.delete(value);
14092
+ }
14093
+ function compileMetadataLeaves(metadata, path9 = [], ancestors = /* @__PURE__ */ new WeakSet()) {
14094
+ if (Object.getOwnPropertySymbols(metadata).length > 0) {
14095
+ throw new Error("filters.metadata keys must be strings");
14096
+ }
14097
+ if (ancestors.has(metadata)) {
14098
+ throw new Error("filters.metadata must not contain cycles");
14099
+ }
14100
+ ancestors.add(metadata);
14101
+ const leaves = [];
14102
+ for (const [key, value] of Object.entries(metadata)) {
14103
+ const childPath = [...path9, key];
14104
+ if (isRecord(value)) {
14105
+ leaves.push(...compileMetadataLeaves(value, childPath, ancestors));
14106
+ } else {
14107
+ validateMetadataValue(value, ancestors);
14108
+ leaves.push([childPath, value]);
14109
+ }
14110
+ }
14111
+ ancestors.delete(metadata);
14112
+ return leaves;
14113
+ }
14114
+ function normalizeSpanFilters(filters, spanType) {
14115
+ if (filters != null && !isRecord(filters)) {
14116
+ throw new Error("filters must be an object");
14117
+ }
14118
+ const values = { ...filters ?? {} };
14119
+ if (spanType !== void 0) {
14120
+ if (!Array.isArray(spanType) || !spanType.every((item) => typeof item === "string")) {
14121
+ throw new Error("spanType must be an array of strings");
14122
+ }
14123
+ if (Object.hasOwn(values, "spanType")) {
14124
+ throw new Error(
14125
+ "spanType cannot be provided both directly and in filters"
14126
+ );
14127
+ }
14128
+ if (spanType.length > 0) {
14129
+ values.spanType = spanType;
14130
+ }
14131
+ }
14132
+ if (Object.keys(values).some((field) => !spanFilterFields.has(field))) {
14133
+ throw new Error("Unsupported span filter fields");
14134
+ }
14135
+ for (const field of ["spanType", "name"]) {
14136
+ if (Object.hasOwn(values, field)) {
14137
+ const items = values[field];
14138
+ if (!Array.isArray(items) || !items.every((item) => typeof item === "string")) {
14139
+ throw new Error(`filters.${field} must be an array of strings`);
14140
+ }
14141
+ }
14142
+ }
14143
+ if (Object.hasOwn(values, "hasError") && typeof values.hasError !== "boolean") {
14144
+ throw new Error("filters.hasError must be a boolean");
14145
+ }
14146
+ let compiledMetadataLeaves = [];
14147
+ if (Object.hasOwn(values, "metadata")) {
14148
+ if (!isRecord(values.metadata)) {
14149
+ throw new Error("filters.metadata must be an object");
14150
+ }
14151
+ compiledMetadataLeaves = compileMetadataLeaves(values.metadata);
14152
+ }
14153
+ if (Object.hasOwn(values, "duration")) {
14154
+ if (!isRecord(values.duration) || Object.keys(values.duration).some(
14155
+ (bound) => bound !== "min" && bound !== "max"
14156
+ )) {
14157
+ throw new Error("filters.duration must contain only min and/or max");
14158
+ }
14159
+ if (Object.values(values.duration).some(
14160
+ (bound) => typeof bound !== "number" || !Number.isFinite(bound)
14161
+ )) {
14162
+ throw new Error("filters.duration bounds must be finite numbers");
14163
+ }
14164
+ }
14165
+ const normalized = {};
14166
+ if (Array.isArray(values.spanType)) {
14167
+ normalized.spanType = values.spanType;
14168
+ }
14169
+ if (Array.isArray(values.name)) {
14170
+ normalized.name = values.name;
14171
+ }
14172
+ if (typeof values.hasError === "boolean") {
14173
+ normalized.hasError = values.hasError;
14174
+ }
14175
+ if (isRecord(values.metadata)) {
14176
+ normalized.metadata = values.metadata;
14177
+ }
14178
+ if (isRecord(values.duration)) {
14179
+ normalized.duration = {};
14180
+ if (typeof values.duration.min === "number") {
14181
+ normalized.duration.min = values.duration.min;
14182
+ }
14183
+ if (typeof values.duration.max === "number") {
14184
+ normalized.duration.max = values.duration.max;
14185
+ }
14186
+ }
14187
+ return { filters: normalized, metadataLeaves: compiledMetadataLeaves };
14188
+ }
14189
+ function metadataEqual(actual, expected) {
14190
+ if (expected === null) {
14191
+ return actual === null || actual === void 0;
14192
+ }
14193
+ if (Array.isArray(expected)) {
14194
+ return Array.isArray(actual) && actual.length === expected.length && expected.every((value, index) => metadataEqual(actual[index], value));
14195
+ }
14196
+ if (isRecord(expected)) {
14197
+ if (!isRecord(actual)) {
14198
+ return false;
14199
+ }
14200
+ const expectedKeys = Object.keys(expected);
14201
+ const actualKeys = Object.keys(actual);
14202
+ return actualKeys.length === expectedKeys.length && expectedKeys.every(
14203
+ (key) => Object.hasOwn(actual, key) && metadataEqual(actual[key], expected[key])
14204
+ );
14205
+ }
14206
+ return actual === expected;
14207
+ }
14208
+ function matchesSpanFilters(span, compiledFilters) {
14209
+ const { filters, metadataLeaves } = compiledFilters;
14210
+ if (filters.spanType !== void 0 && !filters.spanType.includes(span.span_attributes?.type ?? "")) {
14211
+ return false;
14212
+ }
14213
+ if (filters.name !== void 0 && !filters.name.includes(span.span_attributes?.name ?? "")) {
14214
+ return false;
14215
+ }
14216
+ if (filters.hasError !== void 0 && (span.error !== null && span.error !== void 0) !== filters.hasError) {
14217
+ return false;
14218
+ }
14219
+ for (const [path9, expected] of metadataLeaves) {
14220
+ let actual = span.metadata;
14221
+ for (const key of path9) {
14222
+ actual = isRecord(actual) && Object.hasOwn(actual, key) ? actual[key] : void 0;
14223
+ }
14224
+ if (!metadataEqual(actual, expected)) {
14225
+ return false;
14226
+ }
14227
+ }
14228
+ if (filters.duration && Object.keys(filters.duration).length > 0) {
14229
+ const metrics = span.metrics;
14230
+ const start = isRecord(metrics) ? metrics.start : void 0;
14231
+ const end = isRecord(metrics) ? metrics.end : void 0;
14232
+ if (typeof start !== "number" || !Number.isFinite(start) || typeof end !== "number" || !Number.isFinite(end)) {
14233
+ return false;
14234
+ }
14235
+ const elapsed = end - start;
14236
+ if (filters.duration.min !== void 0 && elapsed < filters.duration.min) {
14237
+ return false;
14238
+ }
14239
+ if (filters.duration.max !== void 0 && elapsed > filters.duration.max) {
14240
+ return false;
14241
+ }
14242
+ }
14243
+ return true;
14244
+ }
14245
+ function btqlComparison(op, name, value) {
14246
+ return {
14247
+ op,
14248
+ left: { op: "ident", name },
14249
+ right: { op: "literal", value }
14250
+ };
14251
+ }
14252
+ function btqlNullCheck(op, name) {
14253
+ return { op, expr: { op: "ident", name } };
14254
+ }
14255
+ function spanFilterClauses(compiledFilters) {
14256
+ const { filters, metadataLeaves } = compiledFilters;
14257
+ const children = [];
14258
+ for (const [field, attribute] of [
14259
+ ["spanType", "type"],
14260
+ ["name", "name"]
14261
+ ]) {
14262
+ const values = filters[field];
14263
+ if (values !== void 0) {
14264
+ children.push(
14265
+ values.length > 0 ? btqlComparison("in", ["span_attributes", attribute], values) : { op: "literal", value: false }
14266
+ );
14267
+ }
14268
+ }
14269
+ if (filters.hasError !== void 0) {
14270
+ children.push(
14271
+ btqlNullCheck(filters.hasError ? "isnotnull" : "isnull", ["error"])
14272
+ );
14273
+ }
14274
+ for (const [path9, value] of metadataLeaves) {
14275
+ const name = ["metadata", ...path9];
14276
+ children.push(
14277
+ value === null ? btqlNullCheck("isnull", name) : btqlComparison("eq", name, value)
14278
+ );
14279
+ }
14280
+ const elapsed = {
14281
+ op: "sub",
14282
+ left: { op: "ident", name: ["metrics", "end"] },
14283
+ right: { op: "ident", name: ["metrics", "start"] }
14284
+ };
14285
+ if (filters.duration?.min !== void 0) {
14286
+ children.push({
14287
+ op: "ge",
14288
+ left: elapsed,
14289
+ right: { op: "literal", value: filters.duration.min }
14290
+ });
14291
+ }
14292
+ if (filters.duration?.max !== void 0) {
14293
+ children.push({
14294
+ op: "le",
14295
+ left: elapsed,
14296
+ right: { op: "literal", value: filters.duration.max }
14297
+ });
14298
+ }
14299
+ return children;
14300
+ }
13995
14301
  var SpanFetcher = class _SpanFetcher extends ObjectFetcher {
13996
- constructor(objectType, _objectId, rootSpanId, _state, spanTypeFilter, includeScorers = false, brainstoreRealtime = true) {
14302
+ constructor(objectType, _objectId, rootSpanId, _state, spanTypeFilter, includeScorers = false, brainstoreRealtime = true, filters) {
14303
+ const normalizedFilters = normalizeSpanFilters(filters, spanTypeFilter);
13997
14304
  const filterExpr = _SpanFetcher.buildFilter(
13998
14305
  rootSpanId,
13999
- spanTypeFilter,
14306
+ normalizedFilters,
14000
14307
  includeScorers
14001
14308
  );
14002
14309
  super(
@@ -14017,42 +14324,22 @@ var SpanFetcher = class _SpanFetcher extends ObjectFetcher {
14017
14324
  rootSpanId;
14018
14325
  _state;
14019
14326
  spanTypeFilter;
14020
- static buildFilter(rootSpanId, spanTypeFilter, includeScorers = false) {
14327
+ static buildFilter(rootSpanId, filters, includeScorers = false) {
14328
+ const purpose = ["span_attributes", "purpose"];
14021
14329
  const children = [
14022
- // Base filter: root_span_id = 'value'
14023
- {
14024
- op: "eq",
14025
- left: { op: "ident", name: ["root_span_id"] },
14026
- right: { op: "literal", value: rootSpanId }
14027
- }
14330
+ btqlComparison("eq", ["root_span_id"], rootSpanId)
14028
14331
  ];
14029
14332
  if (!includeScorers) {
14030
14333
  children.push({
14031
14334
  op: "or",
14032
14335
  children: [
14033
- {
14034
- op: "isnull",
14035
- expr: { op: "ident", name: ["span_attributes", "purpose"] }
14036
- },
14037
- {
14038
- op: "ne",
14039
- left: { op: "ident", name: ["span_attributes", "purpose"] },
14040
- right: { op: "literal", value: "scorer" }
14041
- }
14336
+ btqlNullCheck("isnull", purpose),
14337
+ btqlComparison("ne", purpose, "scorer")
14042
14338
  ]
14043
14339
  });
14044
14340
  }
14045
- if (spanTypeFilter && spanTypeFilter.length > 0) {
14046
- children.push({
14047
- op: "in",
14048
- left: { op: "ident", name: ["span_attributes", "type"] },
14049
- right: { op: "literal", value: spanTypeFilter }
14050
- });
14051
- }
14052
- return {
14053
- op: "and",
14054
- children
14055
- };
14341
+ children.push(...spanFilterClauses(filters));
14342
+ return { op: "and", children };
14056
14343
  }
14057
14344
  get id() {
14058
14345
  return Promise.resolve(this._objectId);
@@ -14067,67 +14354,80 @@ var CachedSpanFetcher = class {
14067
14354
  fetchFn;
14068
14355
  constructor(objectTypeOrFetchFn, objectId, rootSpanId, getState, brainstoreRealtime = true) {
14069
14356
  if (typeof objectTypeOrFetchFn === "function") {
14070
- this.fetchFn = (spanType) => objectTypeOrFetchFn(spanType);
14357
+ this.fetchFn = async (filters) => (await objectTypeOrFetchFn(filters.filters.spanType)).filter(
14358
+ (span) => matchesSpanFilters(span, filters)
14359
+ );
14071
14360
  } else {
14072
14361
  const objectType = objectTypeOrFetchFn;
14073
- this.fetchFn = async (spanType, includeScorers) => {
14362
+ this.fetchFn = async (filters, includeScorers) => {
14074
14363
  const state = await getState();
14075
14364
  const fetcher = new SpanFetcher(
14076
14365
  objectType,
14077
14366
  objectId,
14078
14367
  rootSpanId,
14079
14368
  state,
14080
- spanType,
14369
+ void 0,
14081
14370
  includeScorers,
14082
- brainstoreRealtime
14371
+ brainstoreRealtime,
14372
+ filters.filters
14083
14373
  );
14084
- const rows = await fetcher.fetchedData();
14085
- return rows.map((row) => ({
14086
- input: row.input,
14087
- output: row.output,
14088
- expected: row.expected,
14089
- error: row.error,
14090
- scores: row.scores,
14091
- metrics: row.metrics,
14092
- metadata: row.metadata,
14093
- span_id: row.span_id,
14094
- span_parents: row.span_parents,
14095
- is_root: row.is_root,
14096
- span_attributes: row.span_attributes,
14097
- id: row.id,
14098
- _xact_id: row._xact_id,
14099
- _pagination_key: row._pagination_key,
14100
- root_span_id: row.root_span_id,
14101
- created: row.created,
14102
- tags: row.tags
14103
- }));
14374
+ let spans = (await fetcher.fetchedData()).map(
14375
+ (row) => ({ ...row })
14376
+ );
14377
+ if (filters.filters.metadata !== void 0) {
14378
+ spans = spans.filter((span) => matchesSpanFilters(span, filters));
14379
+ }
14380
+ return spans;
14104
14381
  };
14105
14382
  }
14106
14383
  }
14107
14384
  async getSpans({
14108
- spanType,
14385
+ spanType: requestedSpanType,
14386
+ filters,
14109
14387
  includeScorers = false
14110
14388
  } = {}) {
14389
+ const normalizedFilters = normalizeSpanFilters(filters, requestedSpanType);
14390
+ const spanType = normalizedFilters.filters.spanType;
14391
+ const hasAdvancedFilters = Object.keys(normalizedFilters.filters).some(
14392
+ (field) => field !== "spanType"
14393
+ );
14394
+ if (spanType?.length === 0) {
14395
+ return [];
14396
+ }
14111
14397
  if (includeScorers) {
14112
- return this.fetchFn(spanType, true);
14398
+ return this.fetchFn(normalizedFilters, true);
14113
14399
  }
14114
14400
  if (this.allFetched) {
14115
- return this.getFromCache(spanType);
14401
+ const spans = this.getFromCache(spanType);
14402
+ return hasAdvancedFilters ? spans.filter((span) => matchesSpanFilters(span, normalizedFilters)) : spans;
14116
14403
  }
14117
- if (!spanType || spanType.length === 0) {
14404
+ if (hasAdvancedFilters && spanType && spanType.every((type) => this.spanCache.has(type))) {
14405
+ return this.getFromCache(spanType).filter(
14406
+ (span) => matchesSpanFilters(span, normalizedFilters)
14407
+ );
14408
+ }
14409
+ if (hasAdvancedFilters) {
14410
+ return this.fetchFn(normalizedFilters, false);
14411
+ }
14412
+ if (!spanType) {
14413
+ this.spanCache.clear();
14118
14414
  await this.fetchSpans(void 0);
14119
- this.allFetched = true;
14415
+ if (this.spanCache.size > 0) {
14416
+ this.allFetched = true;
14417
+ }
14120
14418
  return this.getFromCache(void 0);
14121
14419
  }
14122
- const missingTypes = spanType.filter((t) => !this.spanCache.has(t));
14123
- if (missingTypes.length === 0) {
14124
- return this.getFromCache(spanType);
14420
+ const missingTypes = spanType.filter((type) => !this.spanCache.has(type));
14421
+ if (missingTypes.length > 0) {
14422
+ await this.fetchSpans(missingTypes);
14125
14423
  }
14126
- await this.fetchSpans(missingTypes);
14127
14424
  return this.getFromCache(spanType);
14128
14425
  }
14129
14426
  async fetchSpans(spanType) {
14130
- const spans = await this.fetchFn(spanType, false);
14427
+ const spans = await this.fetchFn(
14428
+ normalizeSpanFilters(spanType ? { spanType } : void 0),
14429
+ false
14430
+ );
14131
14431
  for (const span of spans) {
14132
14432
  const type = span.span_attributes?.type ?? "";
14133
14433
  const existing = this.spanCache.get(type) ?? [];
@@ -14207,34 +14507,20 @@ var LocalTrace = class {
14207
14507
  */
14208
14508
  async getSpans({
14209
14509
  spanType,
14510
+ filters,
14210
14511
  includeScorers = false
14211
14512
  } = {}) {
14513
+ const normalizedFilters = normalizeSpanFilters(filters, spanType);
14212
14514
  const cachedSpans = this.state.spanCache.getByRootSpanId(this.rootSpanId);
14213
14515
  if (cachedSpans && cachedSpans.length > 0) {
14214
- let spans = includeScorers ? cachedSpans : cachedSpans.filter(
14215
- (span) => span.span_attributes?.purpose !== "scorer"
14216
- );
14217
- if (spanType && spanType.length > 0) {
14218
- spans = spans.filter(
14219
- (span) => spanType.includes(span.span_attributes?.type ?? "")
14220
- );
14221
- }
14222
- return spans.map((span) => ({
14223
- input: span.input,
14224
- output: span.output,
14225
- expected: span.expected,
14226
- error: span.error,
14227
- scores: span.scores,
14228
- metrics: span.metrics,
14229
- metadata: span.metadata,
14230
- span_id: span.span_id,
14231
- span_parents: span.span_parents,
14232
- is_root: span.is_root,
14233
- span_attributes: span.span_attributes,
14234
- tags: span.tags
14235
- }));
14516
+ return cachedSpans.filter(
14517
+ (span) => (includeScorers || span.span_attributes?.purpose !== "scorer") && matchesSpanFilters({ ...span }, normalizedFilters)
14518
+ ).map((span) => ({ ...span }));
14236
14519
  }
14237
- return this.cachedFetcher.getSpans({ spanType, includeScorers });
14520
+ return this.cachedFetcher.getSpans({
14521
+ filters: normalizedFilters.filters,
14522
+ includeScorers
14523
+ });
14238
14524
  }
14239
14525
  /**
14240
14526
  * Get the thread (preprocessed messages) for this trace.
@@ -14641,7 +14927,7 @@ async function Eval(name, evaluator, reporterOrOpts) {
14641
14927
  data,
14642
14928
  { disabled: Boolean(options.parent || options.noSendLogs) }
14643
14929
  );
14644
- if (experiment && typeof process !== "undefined" && globalThis.BRAINTRUST_CONTEXT_MANAGER !== void 0) {
14930
+ if (experiment) {
14645
14931
  await experiment._waitForId();
14646
14932
  }
14647
14933
  if (experiment && options.onStart) {
@@ -14973,6 +15259,10 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
14973
15259
  } : void 0;
14974
15260
  const parsedDatumOrigin = ObjectReference.safeParse(datum.origin);
14975
15261
  const origin = inlineDatasetOrigin ?? (parsedDatumOrigin?.success ? parsedDatumOrigin.data : void 0);
15262
+ const upsertId = datum.upsert_id && trialIndex > 0 ? (0, import_uuid3.v5)(
15263
+ `braintrust:eval:${datum.upsert_id}:trial:${trialIndex}`,
15264
+ import_uuid3.v5.URL
15265
+ ) : datum.upsert_id;
14976
15266
  const baseEvent = {
14977
15267
  name: "eval",
14978
15268
  spanAttributes: {
@@ -14983,7 +15273,7 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
14983
15273
  expected: "expected" in datum ? datum.expected : void 0,
14984
15274
  tags: datum.tags,
14985
15275
  origin,
14986
- ...datum.upsert_id ? { id: datum.upsert_id } : {}
15276
+ ...upsertId ? { id: upsertId } : {}
14987
15277
  }
14988
15278
  };
14989
15279
  const callback = async (rootSpan) => {
@@ -17291,6 +17581,18 @@ function defineChannels(pkg, channels, options) {
17291
17581
  var openAIChannels = defineChannels(
17292
17582
  "openai",
17293
17583
  {
17584
+ agentsTraceStart: channel({
17585
+ channelName: "agents.trace.start",
17586
+ kind: "async"
17587
+ }),
17588
+ agentsTraceCapture: channel({
17589
+ channelName: "agents.trace.capture",
17590
+ kind: "async"
17591
+ }),
17592
+ agentsTraceFail: channel({
17593
+ channelName: "agents.trace.fail",
17594
+ kind: "async"
17595
+ }),
17294
17596
  filesCreateTraced: channel({
17295
17597
  channelName: "files.create-traced",
17296
17598
  kind: "async"
@@ -17659,6 +17961,23 @@ function getCachedMetricFromHeaders(headers) {
17659
17961
  return parseCachedHeader(headers.get(LEGACY_CACHED_HEADER));
17660
17962
  }
17661
17963
 
17964
+ // src/instrumentation/plugins/openai-manual-instrumentation-utils.ts
17965
+ async function deterministicDigest(namespace, ...parts) {
17966
+ const encoded = new TextEncoder().encode(
17967
+ [namespace, ...parts].map((part) => `${part.length}:${part}`).join("\0")
17968
+ );
17969
+ return new Uint8Array(
17970
+ await globalThis.crypto.subtle.digest("SHA-256", encoded)
17971
+ );
17972
+ }
17973
+ function digestHex(bytes, length) {
17974
+ return Array.from(bytes.slice(0, length)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
17975
+ }
17976
+ function digestUuid(bytes) {
17977
+ const hex = digestHex(bytes, 16);
17978
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
17979
+ }
17980
+
17662
17981
  // src/instrumentation/plugins/openai-batch-instrumentation.ts
17663
17982
  var SUPPORTED_ENDPOINTS = /* @__PURE__ */ new Set(["/v1/chat/completions", "/v1/responses"]);
17664
17983
  var TERMINAL_STATUSES = /* @__PURE__ */ new Set([
@@ -17699,21 +18018,6 @@ async function exportParent(parent) {
17699
18018
  }
17700
18019
  return void 0;
17701
18020
  }
17702
- async function deterministicDigest(namespace, ...parts) {
17703
- const encoded = new TextEncoder().encode(
17704
- [namespace, ...parts].map((part) => `${part.length}:${part}`).join("\0")
17705
- );
17706
- return new Uint8Array(
17707
- await globalThis.crypto.subtle.digest("SHA-256", encoded)
17708
- );
17709
- }
17710
- function digestHex(bytes, length) {
17711
- return Array.from(bytes.slice(0, length)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
17712
- }
17713
- function digestUuid(bytes) {
17714
- const hex = digestHex(bytes, 16);
17715
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
17716
- }
17717
18021
  async function batchSpanIds(inputFileId) {
17718
18022
  const [row, span, root] = await Promise.all([
17719
18023
  deterministicDigest("openai:batch:row", inputFileId),
@@ -18204,6 +18508,628 @@ var interceptOpenAIBatchTraceComplete = (target, thisArg, args) => Promise.resol
18204
18508
  return result;
18205
18509
  });
18206
18510
 
18511
+ // src/instrumentation/plugins/openai-agents-api-instrumentation.ts
18512
+ var TERMINAL_TURN_EVENTS = /* @__PURE__ */ new Set([
18513
+ "agent.session.turn.completed",
18514
+ "agent.session.turn.failed",
18515
+ "agent.session.turn.cancelled"
18516
+ ]);
18517
+ var TURN_LIFECYCLE_EVENTS = /* @__PURE__ */ new Set([
18518
+ "agent.session.turn.created",
18519
+ "agent.session.turn.in_progress",
18520
+ ...TERMINAL_TURN_EVENTS
18521
+ ]);
18522
+ var SESSION_EVENTS = /* @__PURE__ */ new Set([
18523
+ "agent.session.created",
18524
+ "agent.session.failed",
18525
+ "agent.session.idle",
18526
+ "agent.session.in_progress",
18527
+ "agent.session.requires_action"
18528
+ ]);
18529
+ var SUBAGENT_EVENTS = /* @__PURE__ */ new Set([
18530
+ "agent.session.subagent.active",
18531
+ "agent.session.subagent.closed",
18532
+ "agent.session.subagent.created"
18533
+ ]);
18534
+ function read2(value, key) {
18535
+ if (!isObject(value)) {
18536
+ return void 0;
18537
+ }
18538
+ try {
18539
+ return Reflect.get(value, key);
18540
+ } catch {
18541
+ return void 0;
18542
+ }
18543
+ }
18544
+ function stringValue(value) {
18545
+ return typeof value === "string" && value.length > 0 ? value : void 0;
18546
+ }
18547
+ function recordValue(record, key) {
18548
+ return Object.hasOwn(record, key) ? record[key] : void 0;
18549
+ }
18550
+ function setRecordValue(record, key, value) {
18551
+ Object.defineProperty(record, key, {
18552
+ configurable: true,
18553
+ enumerable: true,
18554
+ value,
18555
+ writable: true
18556
+ });
18557
+ }
18558
+ function loggedError(value, fallback2) {
18559
+ if (value instanceof Error) {
18560
+ return value;
18561
+ }
18562
+ const message = stringValue(read2(value, "message"));
18563
+ return new Error(message ?? (typeof value === "string" ? value : fallback2));
18564
+ }
18565
+ function logInstrumentationError(context2, error2) {
18566
+ debugLogger.debug(`OpenAI Agents API instrumentation ${context2}:`, error2);
18567
+ }
18568
+ async function childSpanIds2(rootKey, kind, providerId) {
18569
+ const [row, span] = await Promise.all([
18570
+ deterministicDigest("openai:agents:row", rootKey, kind, providerId),
18571
+ deterministicDigest("openai:agents:span", rootKey, kind, providerId)
18572
+ ]);
18573
+ return { rowId: digestUuid(row), spanId: digestHex(span, 8) };
18574
+ }
18575
+ function traceMetadata(args) {
18576
+ const metadata = {};
18577
+ const suppliedMetadata = read2(args, "metadata");
18578
+ if (isObject(suppliedMetadata)) {
18579
+ try {
18580
+ for (const key of Object.keys(suppliedMetadata)) {
18581
+ metadata[key] = read2(suppliedMetadata, key);
18582
+ }
18583
+ } catch (error2) {
18584
+ logInstrumentationError("could not read supplied metadata", error2);
18585
+ }
18586
+ }
18587
+ const agent = read2(args, "agent");
18588
+ const agentId = stringValue(read2(agent, "id")) ?? stringValue(read2(args, "agent_id"));
18589
+ const agentName = stringValue(read2(agent, "name"));
18590
+ const model = stringValue(read2(agent, "model"));
18591
+ return {
18592
+ ...metadata,
18593
+ api: "agents",
18594
+ ...agentId ? { agent_id: agentId } : {},
18595
+ ...agentName ? { agent_name: agentName } : {},
18596
+ ...model ? { model } : {},
18597
+ provider: "openai"
18598
+ };
18599
+ }
18600
+ function copyState(state) {
18601
+ return {
18602
+ ...state,
18603
+ callItems: { ...state.callItems },
18604
+ eventIds: [...state.eventIds],
18605
+ openTools: { ...state.openTools },
18606
+ subagents: { ...state.subagents },
18607
+ turnSubagents: { ...state.turnSubagents }
18608
+ };
18609
+ }
18610
+ function startRootSpan(state) {
18611
+ const root = SpanComponentsV4.fromStr(state.root);
18612
+ const parent = SpanComponentsV4.fromStr(state.rootParent);
18613
+ const rowId = stringValue(root.data.row_id);
18614
+ const rootSpanId = stringValue(root.data.root_span_id);
18615
+ const spanId = stringValue(root.data.span_id);
18616
+ if (!rowId || !rootSpanId || !spanId) {
18617
+ throw new Error("OpenAI Agents trace root is invalid");
18618
+ }
18619
+ const hasParentSpan = Boolean(
18620
+ parent.data.row_id && parent.data.span_id && parent.data.root_span_id
18621
+ );
18622
+ return withCurrent(
18623
+ NOOP_SPAN,
18624
+ () => _internalStartSpanWithInitialMergeAndParentSpanIds(
18625
+ withSpanInstrumentationName(
18626
+ {
18627
+ name: "openai.agents.turn",
18628
+ type: "task" /* TASK */,
18629
+ parent: state.rootParent,
18630
+ ...!hasParentSpan ? {
18631
+ parentSpanIds: {
18632
+ parentSpanIds: [],
18633
+ rootSpanId
18634
+ }
18635
+ } : {},
18636
+ spanId,
18637
+ startTime: state.startTime,
18638
+ event: { id: rowId }
18639
+ },
18640
+ INSTRUMENTATION_NAMES.OPENAI
18641
+ )
18642
+ )
18643
+ );
18644
+ }
18645
+ async function startSubagentSpan(state, subagentId, input, metadata, visiting = /* @__PURE__ */ new Set()) {
18646
+ const subagent = recordValue(state.subagents, subagentId);
18647
+ let parent = state.root;
18648
+ if (subagent?.parentAgentId && subagent.parentAgentId !== subagentId && recordValue(state.subagents, subagent.parentAgentId) && !visiting.has(subagent.parentAgentId)) {
18649
+ visiting.add(subagentId);
18650
+ parent = await (await startSubagentSpan(
18651
+ state,
18652
+ subagent.parentAgentId,
18653
+ void 0,
18654
+ void 0,
18655
+ visiting
18656
+ )).export();
18657
+ }
18658
+ const ids = await childSpanIds2(state.rootKey, "subagent", subagentId);
18659
+ return withCurrent(
18660
+ NOOP_SPAN,
18661
+ () => _internalStartSpanWithInitialMerge(
18662
+ withSpanInstrumentationName(
18663
+ {
18664
+ name: "openai.agents.subagent",
18665
+ type: "task" /* TASK */,
18666
+ parent,
18667
+ spanId: ids.spanId,
18668
+ startTime: subagent?.openedAt,
18669
+ event: {
18670
+ id: ids.rowId,
18671
+ ...input !== void 0 ? { input } : {},
18672
+ metadata: {
18673
+ ...metadata,
18674
+ agent_id: subagentId,
18675
+ ...subagent?.parentAgentId ? { parent_agent_id: subagent.parentAgentId } : {},
18676
+ provider: "openai"
18677
+ }
18678
+ }
18679
+ },
18680
+ INSTRUMENTATION_NAMES.OPENAI
18681
+ )
18682
+ )
18683
+ );
18684
+ }
18685
+ async function parentForTurn(state, turnId) {
18686
+ const subagentId = turnId ? recordValue(state.turnSubagents, turnId) : void 0;
18687
+ if (!subagentId) {
18688
+ return state.root;
18689
+ }
18690
+ return await (await startSubagentSpan(state, subagentId)).export();
18691
+ }
18692
+ async function startToolSpan(state, tool, input) {
18693
+ const ids = await childSpanIds2(state.rootKey, "tool", tool.itemId);
18694
+ return withCurrent(
18695
+ NOOP_SPAN,
18696
+ async () => _internalStartSpanWithInitialMerge(
18697
+ withSpanInstrumentationName(
18698
+ {
18699
+ name: tool.name,
18700
+ type: "tool" /* TOOL */,
18701
+ parent: await parentForTurn(state, tool.turnId),
18702
+ spanId: ids.spanId,
18703
+ startTime: tool.startTime,
18704
+ event: {
18705
+ id: ids.rowId,
18706
+ ...input !== void 0 ? { input } : {},
18707
+ metadata: {
18708
+ item_id: tool.itemId,
18709
+ provider: "openai",
18710
+ tool_type: tool.toolType,
18711
+ ...tool.turnId ? { turn_id: tool.turnId } : {}
18712
+ }
18713
+ }
18714
+ },
18715
+ INSTRUMENTATION_NAMES.OPENAI
18716
+ )
18717
+ )
18718
+ );
18719
+ }
18720
+ function toolFromItem(item, observedAt) {
18721
+ const itemId = stringValue(read2(item, "id"));
18722
+ const toolType = stringValue(read2(item, "type"));
18723
+ if (!itemId || !toolType) {
18724
+ return void 0;
18725
+ }
18726
+ const turnId = stringValue(read2(item, "turn_id"));
18727
+ switch (toolType) {
18728
+ case "function_call":
18729
+ return {
18730
+ input: read2(item, "arguments"),
18731
+ tool: {
18732
+ itemId,
18733
+ name: stringValue(read2(item, "name")) ?? "Function call",
18734
+ startTime: observedAt,
18735
+ toolType,
18736
+ ...turnId ? { turnId } : {}
18737
+ }
18738
+ };
18739
+ case "mcp_call": {
18740
+ const name = stringValue(read2(item, "name")) ?? "MCP call";
18741
+ const server = stringValue(read2(item, "server_label"));
18742
+ return {
18743
+ input: read2(item, "arguments"),
18744
+ tool: {
18745
+ itemId,
18746
+ name: server ? `${server}.${name}` : name,
18747
+ startTime: observedAt,
18748
+ toolType,
18749
+ ...turnId ? { turnId } : {}
18750
+ }
18751
+ };
18752
+ }
18753
+ case "web_search_call":
18754
+ return {
18755
+ input: read2(item, "action"),
18756
+ tool: {
18757
+ itemId,
18758
+ name: "Web search",
18759
+ startTime: observedAt,
18760
+ toolType,
18761
+ ...turnId ? { turnId } : {}
18762
+ }
18763
+ };
18764
+ case "command_execution":
18765
+ return {
18766
+ input: {
18767
+ command: read2(item, "command"),
18768
+ cwd: read2(item, "cwd")
18769
+ },
18770
+ tool: {
18771
+ itemId,
18772
+ name: "Command execution",
18773
+ startTime: observedAt,
18774
+ toolType,
18775
+ ...turnId ? { turnId } : {}
18776
+ }
18777
+ };
18778
+ default:
18779
+ return void 0;
18780
+ }
18781
+ }
18782
+ function textFromContent(content) {
18783
+ if (!Array.isArray(content)) {
18784
+ return void 0;
18785
+ }
18786
+ const text = [];
18787
+ for (const part of content) {
18788
+ const partText = read2(part, "text");
18789
+ if (read2(part, "type") === "output_text" && typeof partText === "string") {
18790
+ text.push(partText);
18791
+ }
18792
+ }
18793
+ return text.length > 0 ? text.join("") : void 0;
18794
+ }
18795
+ function toolOutput(item, toolType) {
18796
+ switch (toolType) {
18797
+ case "function_call":
18798
+ return read2(item, "output");
18799
+ case "mcp_call":
18800
+ return read2(item, "output");
18801
+ case "web_search_call":
18802
+ return read2(item, "action");
18803
+ case "command_execution":
18804
+ return read2(item, "output");
18805
+ default:
18806
+ return void 0;
18807
+ }
18808
+ }
18809
+ function toolFailed(item, toolType) {
18810
+ const status = read2(item, "status");
18811
+ const explicitError = read2(item, "error");
18812
+ if (explicitError !== void 0 && explicitError !== null) {
18813
+ return loggedError(explicitError, `OpenAI ${toolType} failed`);
18814
+ }
18815
+ if (status === "failed" || status === "incomplete") {
18816
+ return new Error(`OpenAI ${toolType} ${status}`);
18817
+ }
18818
+ if (toolType === "command_execution" && typeof read2(item, "exit_code") === "number" && read2(item, "exit_code") !== 0) {
18819
+ return new Error(
18820
+ `OpenAI command exited with code ${read2(item, "exit_code")}`
18821
+ );
18822
+ }
18823
+ return void 0;
18824
+ }
18825
+ async function completeTool(state, tool, item, endTime) {
18826
+ const span = await startToolSpan(state, tool);
18827
+ const output = toolOutput(item, tool.toolType);
18828
+ const error2 = toolFailed(item, tool.toolType);
18829
+ span.log({
18830
+ ...output !== void 0 ? { output } : {},
18831
+ ...error2 ? { error: error2 } : {},
18832
+ metadata: {
18833
+ status: read2(item, "status"),
18834
+ ...tool.toolType === "command_execution" ? { exit_code: read2(item, "exit_code") } : {}
18835
+ }
18836
+ });
18837
+ span.end({ endTime });
18838
+ Reflect.deleteProperty(state.openTools, tool.itemId);
18839
+ }
18840
+ async function captureMessage(state, item) {
18841
+ if (read2(item, "type") !== "message" || read2(item, "role") !== "assistant" || read2(item, "phase") !== "final_answer") {
18842
+ return;
18843
+ }
18844
+ const output = textFromContent(read2(item, "content"));
18845
+ if (output === void 0) {
18846
+ return;
18847
+ }
18848
+ const turnId = stringValue(read2(item, "turn_id"));
18849
+ const subagentId = turnId ? recordValue(state.turnSubagents, turnId) : void 0;
18850
+ if (subagentId) {
18851
+ (await startSubagentSpan(state, subagentId)).log({ output });
18852
+ } else {
18853
+ startRootSpan(state).log({ output });
18854
+ }
18855
+ }
18856
+ async function captureItem(state, item, isDone, observedAt) {
18857
+ await captureMessage(state, item);
18858
+ const itemType = stringValue(read2(item, "type"));
18859
+ if (itemType === "function_call_output") {
18860
+ const callId = stringValue(read2(item, "call_id"));
18861
+ const itemId = callId ? recordValue(state.callItems, callId) : void 0;
18862
+ const tool2 = itemId ? recordValue(state.openTools, itemId) : void 0;
18863
+ if (tool2) {
18864
+ await completeTool(state, tool2, item, observedAt);
18865
+ }
18866
+ return;
18867
+ }
18868
+ const descriptor = toolFromItem(item, observedAt);
18869
+ if (!descriptor) {
18870
+ return;
18871
+ }
18872
+ const existing = recordValue(state.openTools, descriptor.tool.itemId);
18873
+ const tool = existing ?? descriptor.tool;
18874
+ setRecordValue(state.openTools, tool.itemId, tool);
18875
+ if (itemType === "function_call") {
18876
+ const callId = stringValue(read2(item, "call_id"));
18877
+ if (callId) {
18878
+ setRecordValue(state.callItems, callId, tool.itemId);
18879
+ }
18880
+ }
18881
+ await startToolSpan(state, tool, descriptor.input);
18882
+ const status = read2(item, "status");
18883
+ const terminalFunctionCall = itemType === "function_call" && (status === "failed" || status === "incomplete");
18884
+ if (itemType !== "function_call" && (isDone || status !== "in_progress") || terminalFunctionCall) {
18885
+ await completeTool(state, tool, item, observedAt);
18886
+ }
18887
+ }
18888
+ function updateSessionMetadata(state, session) {
18889
+ const sessionId = stringValue(read2(session, "id"));
18890
+ const agent = read2(session, "agent");
18891
+ startRootSpan(state).log({
18892
+ metadata: {
18893
+ ...sessionId ? { session_id: sessionId } : {},
18894
+ ...stringValue(read2(agent, "id")) ? { agent_id: read2(agent, "id") } : {},
18895
+ ...stringValue(read2(agent, "name")) ? { agent_name: read2(agent, "name") } : {},
18896
+ ...stringValue(read2(agent, "model")) ? { model: read2(agent, "model") } : {}
18897
+ }
18898
+ });
18899
+ }
18900
+ async function captureSubagent(state, eventType, subagent, observedAt) {
18901
+ const subagentId = stringValue(read2(subagent, "id"));
18902
+ if (!subagentId) {
18903
+ return;
18904
+ }
18905
+ const existing = recordValue(state.subagents, subagentId);
18906
+ const observedOpenedAt = read2(subagent, "opened_at");
18907
+ const openedAt = typeof observedOpenedAt === "number" && Number.isFinite(observedOpenedAt) && observedOpenedAt >= 0 ? observedOpenedAt : existing?.openedAt ?? observedAt;
18908
+ const observedClosedAt = read2(subagent, "closed_at");
18909
+ const closedAt = typeof observedClosedAt === "number" && Number.isFinite(observedClosedAt) && observedClosedAt >= 0 ? observedClosedAt : existing?.closedAt;
18910
+ const parentAgentId = stringValue(read2(subagent, "parent_agent_id")) ?? existing?.parentAgentId;
18911
+ setRecordValue(state.subagents, subagentId, {
18912
+ ...closedAt !== void 0 ? { closedAt } : {},
18913
+ openedAt,
18914
+ ...parentAgentId ? { parentAgentId } : {}
18915
+ });
18916
+ const span = await startSubagentSpan(
18917
+ state,
18918
+ subagentId,
18919
+ read2(subagent, "instructions"),
18920
+ {
18921
+ ...stringValue(read2(subagent, "name")) ? { agent_name: read2(subagent, "name") } : {},
18922
+ status: read2(subagent, "status")
18923
+ }
18924
+ );
18925
+ if (eventType === "agent.session.subagent.closed") {
18926
+ span.end({ endTime: closedAt ?? observedAt });
18927
+ }
18928
+ }
18929
+ async function closeTrace(state, endTime, error2, usage) {
18930
+ if (state.ended) {
18931
+ return;
18932
+ }
18933
+ for (const tool of Object.values(state.openTools)) {
18934
+ const span = await startToolSpan(state, tool);
18935
+ span.log({
18936
+ error: error2 ?? new Error("OpenAI Agents turn ended before tool completion")
18937
+ });
18938
+ span.end({ endTime });
18939
+ }
18940
+ state.openTools = {};
18941
+ for (const subagentId of Object.keys(state.subagents)) {
18942
+ const subagent = state.subagents[subagentId];
18943
+ const span = await startSubagentSpan(state, subagentId);
18944
+ span.end({ endTime: subagent.closedAt ?? endTime });
18945
+ }
18946
+ const root = startRootSpan(state);
18947
+ root.log({
18948
+ ...error2 ? { error: error2 } : {},
18949
+ metrics: parseMetricsFromUsage(usage)
18950
+ });
18951
+ root.end({ endTime });
18952
+ state.ended = true;
18953
+ }
18954
+ async function captureTurnLifecycle(state, event, eventType, observedAt) {
18955
+ const turn = read2(event, "turn");
18956
+ const turnId = stringValue(read2(event, "turn_id")) ?? stringValue(read2(turn, "id"));
18957
+ const subagentId = stringValue(read2(turn, "subagent_id"));
18958
+ if (turnId && subagentId) {
18959
+ setRecordValue(state.turnSubagents, turnId, subagentId);
18960
+ if (!recordValue(state.subagents, subagentId)) {
18961
+ const createdAt = read2(turn, "created_at");
18962
+ setRecordValue(state.subagents, subagentId, {
18963
+ openedAt: typeof createdAt === "number" && Number.isFinite(createdAt) && createdAt >= 0 ? createdAt : observedAt
18964
+ });
18965
+ }
18966
+ await startSubagentSpan(state, subagentId);
18967
+ }
18968
+ const sessionId = stringValue(read2(event, "session_id"));
18969
+ if (sessionId) {
18970
+ startRootSpan(state).log({ metadata: { session_id: sessionId } });
18971
+ }
18972
+ if (!TERMINAL_TURN_EVENTS.has(eventType) || subagentId) {
18973
+ if (subagentId && eventType === "agent.session.turn.failed") {
18974
+ (await startSubagentSpan(state, subagentId)).log({
18975
+ error: loggedError(read2(turn, "error"), "OpenAI subagent turn failed")
18976
+ });
18977
+ }
18978
+ return;
18979
+ }
18980
+ const completedAt = read2(turn, "completed_at");
18981
+ const endTime = typeof completedAt === "number" && Number.isFinite(completedAt) && completedAt >= 0 ? completedAt : observedAt;
18982
+ const usage = read2(event, "usage") ?? read2(turn, "usage");
18983
+ const error2 = eventType === "agent.session.turn.completed" ? void 0 : loggedError(
18984
+ read2(turn, "error"),
18985
+ eventType === "agent.session.turn.cancelled" ? "OpenAI Agents turn cancelled" : "OpenAI Agents turn failed"
18986
+ );
18987
+ await closeTrace(state, endTime, error2, usage);
18988
+ }
18989
+ async function captureEvent(state, event) {
18990
+ if (state.ended) {
18991
+ return state;
18992
+ }
18993
+ const eventType = stringValue(read2(event, "type"));
18994
+ const eventId = stringValue(read2(event, "event_id"));
18995
+ if (!eventType || eventId && state.eventIds.includes(eventId)) {
18996
+ return state;
18997
+ }
18998
+ const next = copyState(state);
18999
+ const observedAt = getCurrentUnixTimestamp();
19000
+ let handled = false;
19001
+ if (SESSION_EVENTS.has(eventType)) {
19002
+ const session = read2(event, "session");
19003
+ if (session) {
19004
+ updateSessionMetadata(next, session);
19005
+ }
19006
+ handled = true;
19007
+ }
19008
+ if (eventType === "agent.session.turn.item.added") {
19009
+ await captureItem(next, read2(event, "item"), false, observedAt);
19010
+ handled = true;
19011
+ } else if (eventType === "agent.session.turn.item.done") {
19012
+ await captureItem(next, read2(event, "item"), true, observedAt);
19013
+ handled = true;
19014
+ } else if (TURN_LIFECYCLE_EVENTS.has(eventType)) {
19015
+ await captureTurnLifecycle(next, event, eventType, observedAt);
19016
+ handled = true;
19017
+ } else if (SUBAGENT_EVENTS.has(eventType)) {
19018
+ await captureSubagent(next, eventType, read2(event, "subagent"), observedAt);
19019
+ handled = true;
19020
+ } else if (eventType === "agent.session.turn.output_text.delta" && next.firstTokenAt === void 0 && stringValue(read2(event, "delta"))) {
19021
+ next.firstTokenAt = observedAt;
19022
+ startRootSpan(next).log({
19023
+ metrics: { time_to_first_token: observedAt - next.startTime }
19024
+ });
19025
+ handled = true;
19026
+ } else if (eventType === "agent.session.failed") {
19027
+ const session = read2(event, "session");
19028
+ const lastActiveAt = read2(session, "last_active_at");
19029
+ const endTime = typeof lastActiveAt === "number" && Number.isFinite(lastActiveAt) && lastActiveAt >= 0 ? lastActiveAt : observedAt;
19030
+ await closeTrace(
19031
+ next,
19032
+ endTime,
19033
+ loggedError(read2(session, "error"), "OpenAI Agents session failed"),
19034
+ read2(session, "usage")
19035
+ );
19036
+ handled = true;
19037
+ } else if (eventType === "error") {
19038
+ await closeTrace(
19039
+ next,
19040
+ observedAt,
19041
+ loggedError(read2(event, "error"), "OpenAI Agents session failed")
19042
+ );
19043
+ handled = true;
19044
+ }
19045
+ if (!handled) {
19046
+ return state;
19047
+ }
19048
+ if (eventId) {
19049
+ next.eventIds.push(eventId);
19050
+ }
19051
+ return next;
19052
+ }
19053
+ var interceptOpenAIAgentsTraceStart = async (target, thisArg, args) => {
19054
+ const fallback2 = await Reflect.apply(target, thisArg, args);
19055
+ try {
19056
+ const state = args[0].state;
19057
+ const parent = state.rootParent;
19058
+ const traceArgs = args[0].args;
19059
+ const parentComponents = SpanComponentsV4.fromStr(parent);
19060
+ const hasParentSpan = Boolean(
19061
+ parentComponents.data.row_id && parentComponents.data.span_id && parentComponents.data.root_span_id
19062
+ );
19063
+ const rootComponents = SpanComponentsV4.fromStr(state.root);
19064
+ const rowId = stringValue(rootComponents.data.row_id);
19065
+ const rootSpanId = stringValue(rootComponents.data.root_span_id);
19066
+ const spanId = stringValue(rootComponents.data.span_id);
19067
+ if (!rowId || !rootSpanId || !spanId) {
19068
+ throw new Error("OpenAI Agents trace root is invalid");
19069
+ }
19070
+ withCurrent(
19071
+ NOOP_SPAN,
19072
+ () => _internalStartSpanWithInitialMergeAndParentSpanIds(
19073
+ withSpanInstrumentationName(
19074
+ {
19075
+ name: "openai.agents.turn",
19076
+ type: "task" /* TASK */,
19077
+ parent,
19078
+ ...!hasParentSpan ? {
19079
+ parentSpanIds: {
19080
+ parentSpanIds: [],
19081
+ rootSpanId
19082
+ }
19083
+ } : {},
19084
+ spanId,
19085
+ startTime: state.startTime,
19086
+ event: {
19087
+ id: rowId,
19088
+ input: read2(traceArgs, "input"),
19089
+ metadata: traceMetadata(traceArgs)
19090
+ }
19091
+ },
19092
+ INSTRUMENTATION_NAMES.OPENAI
19093
+ )
19094
+ )
19095
+ );
19096
+ return state;
19097
+ } catch (error2) {
19098
+ logInstrumentationError("could not start trace", error2);
19099
+ return fallback2;
19100
+ }
19101
+ };
19102
+ var interceptOpenAIAgentsTraceCapture = async (target, thisArg, args) => {
19103
+ const fallback2 = await Reflect.apply(target, thisArg, args);
19104
+ if (!args[0].state) {
19105
+ return fallback2;
19106
+ }
19107
+ try {
19108
+ return await captureEvent(args[0].state, args[0].event);
19109
+ } catch (error2) {
19110
+ logInstrumentationError("could not capture event", error2);
19111
+ return fallback2;
19112
+ }
19113
+ };
19114
+ var interceptOpenAIAgentsTraceFail = async (target, thisArg, args) => {
19115
+ const fallback2 = await Reflect.apply(target, thisArg, args);
19116
+ if (!args[0].state) {
19117
+ return fallback2;
19118
+ }
19119
+ try {
19120
+ const next = copyState(args[0].state);
19121
+ await closeTrace(
19122
+ next,
19123
+ getCurrentUnixTimestamp(),
19124
+ loggedError(args[0].error, "OpenAI Agents request failed")
19125
+ );
19126
+ return next;
19127
+ } catch (error2) {
19128
+ logInstrumentationError("could not fail trace", error2);
19129
+ return fallback2;
19130
+ }
19131
+ };
19132
+
18207
19133
  // src/instrumentation/plugins/openai-plugin.ts
18208
19134
  var OpenAIPlugin = class extends BasePlugin {
18209
19135
  constructor() {
@@ -18211,6 +19137,13 @@ var OpenAIPlugin = class extends BasePlugin {
18211
19137
  }
18212
19138
  onEnable() {
18213
19139
  this.unsubscribers.push(
19140
+ openAIChannels.agentsTraceStart.intercept(
19141
+ interceptOpenAIAgentsTraceStart
19142
+ ),
19143
+ openAIChannels.agentsTraceCapture.intercept(
19144
+ interceptOpenAIAgentsTraceCapture
19145
+ ),
19146
+ openAIChannels.agentsTraceFail.intercept(interceptOpenAIAgentsTraceFail),
18214
19147
  openAIChannels.filesCreateTraced.intercept(
18215
19148
  interceptOpenAIFilesCreateTraced
18216
19149
  ),
@@ -18771,7 +19704,7 @@ async function* patchCodexEventStream(events, state) {
18771
19704
  try {
18772
19705
  await handleCodexEvent(state, event);
18773
19706
  } catch (error2) {
18774
- logInstrumentationError("OpenAI Codex stream event", error2);
19707
+ logInstrumentationError2("OpenAI Codex stream event", error2);
18775
19708
  }
18776
19709
  yield event;
18777
19710
  }
@@ -19271,10 +20204,10 @@ function safeLog(span, event) {
19271
20204
  try {
19272
20205
  span.log(event);
19273
20206
  } catch (error2) {
19274
- logInstrumentationError("OpenAI Codex span log", error2);
20207
+ logInstrumentationError2("OpenAI Codex span log", error2);
19275
20208
  }
19276
20209
  }
19277
- function logInstrumentationError(context2, error2) {
20210
+ function logInstrumentationError2(context2, error2) {
19278
20211
  debugLogger.error(`Error processing ${context2}:`, error2);
19279
20212
  }
19280
20213
 
@@ -20656,27 +21589,8 @@ function continuationParentFromCreateSessionParams(params) {
20656
21589
  }
20657
21590
  return context2.parent;
20658
21591
  }
20659
- function exportSpanSynchronously(span) {
20660
- const parentInfo = span.getParentInfo();
20661
- if (!parentInfo) {
20662
- return void 0;
20663
- }
20664
- const objectId = parentInfo.objectId.getSync().value;
20665
- if (!objectId && !parentInfo.computeObjectMetadataArgs) {
20666
- return void 0;
20667
- }
20668
- return new SpanComponentsV4({
20669
- object_type: parentInfo.objectType,
20670
- ...objectId ? { object_id: objectId } : {
20671
- compute_object_metadata_args: parentInfo.computeObjectMetadataArgs ?? {}
20672
- },
20673
- row_id: span.id,
20674
- root_span_id: span.rootSpanId,
20675
- span_id: span.spanId
20676
- }).toStr();
20677
- }
20678
21592
  function exportedParent(parent) {
20679
- return typeof parent === "string" ? parent : exportSpanSynchronously(parent);
21593
+ return typeof parent === "string" ? parent : _internalExportParentSynchronously(parent);
20680
21594
  }
20681
21595
  function addSerializedContext(args) {
20682
21596
  if (!isObject(args.continuation) || args.sessionId === void 0) {
@@ -21433,16 +22347,16 @@ function braintrustAISDKTelemetry() {
21433
22347
  if (!toolCallId || !state) {
21434
22348
  return;
21435
22349
  }
21436
- const toolOutput = event.toolOutput;
22350
+ const toolOutput2 = event.toolOutput;
21437
22351
  const workflowToolError = event.success === false && "error" in event ? event.error : void 0;
21438
- if (toolOutput?.type === "tool-error" || workflowToolError !== void 0) {
21439
- const error2 = toolOutput?.error ?? workflowToolError;
22352
+ if (toolOutput2?.type === "tool-error" || workflowToolError !== void 0) {
22353
+ const error2 = toolOutput2?.error ?? workflowToolError;
21440
22354
  state.span.log({
21441
22355
  error: error2 instanceof Error ? error2.message : String(error2),
21442
22356
  metrics: typeof event.durationMs === "number" ? { duration_ms: event.durationMs } : {}
21443
22357
  });
21444
22358
  } else {
21445
- const output = toolOutput && "output" in toolOutput ? toolOutput.output : event.output;
22359
+ const output = toolOutput2 && "output" in toolOutput2 ? toolOutput2.output : event.output;
21446
22360
  state.span.log({
21447
22361
  ...shouldRecordOutputs(event) ? { output } : {},
21448
22362
  metrics: typeof event.durationMs === "number" ? { duration_ms: event.durationMs } : {}
@@ -23901,9 +24815,9 @@ function patchAISDKStreamingResult(args) {
23901
24815
  }
23902
24816
  finalize({ metrics, output });
23903
24817
  } catch (error2) {
23904
- const loggedError = toLoggedError(error2);
24818
+ const loggedError2 = toLoggedError(error2);
23905
24819
  try {
23906
- span.log({ error: loggedError });
24820
+ span.log({ error: loggedError2 });
23907
24821
  } catch (loggingError) {
23908
24822
  debugLogger.error(
23909
24823
  "Error logging AI SDK streaming failure:",
@@ -23911,7 +24825,7 @@ function patchAISDKStreamingResult(args) {
23911
24825
  );
23912
24826
  }
23913
24827
  finalize({
23914
- error: error2 instanceof Error ? error2 : new Error(String(loggedError))
24828
+ error: error2 instanceof Error ? error2 : new Error(String(loggedError2))
23915
24829
  });
23916
24830
  }
23917
24831
  };
@@ -24024,9 +24938,9 @@ function patchAISDKStreamingResult(args) {
24024
24938
  }
24025
24939
  controller.enqueue(value);
24026
24940
  } catch (error2) {
24027
- const loggedError = toLoggedError(error2);
24941
+ const loggedError2 = toLoggedError(error2);
24028
24942
  try {
24029
- span.log({ error: loggedError });
24943
+ span.log({ error: loggedError2 });
24030
24944
  } catch (loggingError) {
24031
24945
  debugLogger.error(
24032
24946
  "Error logging AI SDK base stream failure:",
@@ -24034,7 +24948,7 @@ function patchAISDKStreamingResult(args) {
24034
24948
  );
24035
24949
  }
24036
24950
  finalize({
24037
- error: error2 instanceof Error ? error2 : new Error(String(loggedError))
24951
+ error: error2 instanceof Error ? error2 : new Error(String(loggedError2))
24038
24952
  });
24039
24953
  controller.error(error2);
24040
24954
  }
@@ -26928,7 +27842,7 @@ function wrapSendOptionsCallbacks(options, state) {
26928
27842
  try {
26929
27843
  await handleInteractionUpdate(state, args.update);
26930
27844
  } catch (error2) {
26931
- logInstrumentationError2("Cursor SDK onDelta", error2);
27845
+ logInstrumentationError3("Cursor SDK onDelta", error2);
26932
27846
  }
26933
27847
  if (originalOnDelta) {
26934
27848
  return originalOnDelta(args);
@@ -26938,7 +27852,7 @@ function wrapSendOptionsCallbacks(options, state) {
26938
27852
  try {
26939
27853
  handleStepUpdate(state, args.step);
26940
27854
  } catch (error2) {
26941
- logInstrumentationError2("Cursor SDK onStep", error2);
27855
+ logInstrumentationError3("Cursor SDK onStep", error2);
26942
27856
  }
26943
27857
  if (originalOnStep) {
26944
27858
  return originalOnStep(args);
@@ -27020,7 +27934,7 @@ async function* patchCursorStream(stream, state) {
27020
27934
  try {
27021
27935
  await handleStreamMessage2(state, message);
27022
27936
  } catch (error2) {
27023
- logInstrumentationError2("Cursor SDK stream", error2);
27937
+ logInstrumentationError3("Cursor SDK stream", error2);
27024
27938
  }
27025
27939
  yield message;
27026
27940
  }
@@ -27084,7 +27998,7 @@ async function handleToolUpdate(state, update) {
27084
27998
  if (!state.activeToolSpans.has(callId)) {
27085
27999
  state.activeToolSpans.set(
27086
28000
  callId,
27087
- await startToolSpan(state, {
28001
+ await startToolSpan2(state, {
27088
28002
  args,
27089
28003
  callId,
27090
28004
  name,
@@ -27095,7 +28009,7 @@ async function handleToolUpdate(state, update) {
27095
28009
  }
27096
28010
  return;
27097
28011
  }
27098
- const toolState = state.activeToolSpans.get(callId) ?? await startToolSpan(state, {
28012
+ const toolState = state.activeToolSpans.get(callId) ?? await startToolSpan2(state, {
27099
28013
  args,
27100
28014
  callId,
27101
28015
  name,
@@ -27132,7 +28046,7 @@ async function handleStreamMessage2(state, message) {
27132
28046
  } else if (block?.type === "tool_use" && block.id) {
27133
28047
  state.activeToolSpans.set(
27134
28048
  block.id,
27135
- await startToolSpan(state, {
28049
+ await startToolSpan2(state, {
27136
28050
  args: block.input,
27137
28051
  callId: block.id,
27138
28052
  name: block.name,
@@ -27167,7 +28081,7 @@ async function handleToolMessage(state, message) {
27167
28081
  if (!state.activeToolSpans.has(callId)) {
27168
28082
  state.activeToolSpans.set(
27169
28083
  callId,
27170
- await startToolSpan(state, {
28084
+ await startToolSpan2(state, {
27171
28085
  args: message.args,
27172
28086
  callId,
27173
28087
  name: message.name,
@@ -27178,7 +28092,7 @@ async function handleToolMessage(state, message) {
27178
28092
  }
27179
28093
  return;
27180
28094
  }
27181
- const toolState = state.activeToolSpans.get(callId) ?? await startToolSpan(state, {
28095
+ const toolState = state.activeToolSpans.get(callId) ?? await startToolSpan2(state, {
27182
28096
  args: message.args,
27183
28097
  callId,
27184
28098
  name: message.name,
@@ -27205,7 +28119,7 @@ async function handleConversation(state, turns) {
27205
28119
  const command = turn.turn?.shellCommand?.command;
27206
28120
  if (command) {
27207
28121
  const callId = `shell:${state.activeToolSpans.size}:${command}`;
27208
- const toolState = await startToolSpan(state, {
28122
+ const toolState = await startToolSpan2(state, {
27209
28123
  args: turn.turn?.shellCommand,
27210
28124
  callId,
27211
28125
  name: "shell",
@@ -27229,7 +28143,7 @@ async function handleConversationStep(state, step) {
27229
28143
  }
27230
28144
  const toolCall = step.message;
27231
28145
  const callId = typeof toolCall?.callId === "string" ? toolCall.callId : `conversation-tool:${state.activeToolSpans.size}`;
27232
- const toolState = await startToolSpan(state, {
28146
+ const toolState = await startToolSpan2(state, {
27233
28147
  args: extractToolArgs(toolCall),
27234
28148
  callId,
27235
28149
  name: extractToolName(toolCall),
@@ -27260,7 +28174,7 @@ function handleStepUpdate(state, step) {
27260
28174
  state.stepText.push(step.message.text);
27261
28175
  }
27262
28176
  }
27263
- async function startToolSpan(state, args) {
28177
+ async function startToolSpan2(state, args) {
27264
28178
  const name = args.name || "unknown";
27265
28179
  const metadata = {
27266
28180
  "cursor_sdk.tool.status": args.status,
@@ -27547,10 +28461,10 @@ function safeLog2(span, event) {
27547
28461
  try {
27548
28462
  span.log(event);
27549
28463
  } catch (error2) {
27550
- logInstrumentationError2("Cursor SDK span log", error2);
28464
+ logInstrumentationError3("Cursor SDK span log", error2);
27551
28465
  }
27552
28466
  }
27553
- function logInstrumentationError2(context2, error2) {
28467
+ function logInstrumentationError3(context2, error2) {
27554
28468
  debugLogger.error(`Error processing ${context2}:`, error2);
27555
28469
  }
27556
28470
  function cleanMetrics2(metrics) {
@@ -28388,6 +29302,10 @@ var googleGenAIChannels = defineChannels(
28388
29302
  channelName: "models.embedContent",
28389
29303
  kind: "async"
28390
29304
  }),
29305
+ httpResponseJson: channel({
29306
+ channelName: "httpResponse.json",
29307
+ kind: "async"
29308
+ }),
28391
29309
  interactionsCreate: channel({
28392
29310
  channelName: "interactions.create",
28393
29311
  kind: "async"
@@ -28536,13 +29454,45 @@ var GoogleGenAIPlugin = class extends BasePlugin {
28536
29454
  subscribeToEmbedContentChannel() {
28537
29455
  const tracingChannel = googleGenAIChannels.embedContent.tracingChannel();
28538
29456
  const states = /* @__PURE__ */ new WeakMap();
29457
+ const embeddingSpans = /* @__PURE__ */ new WeakSet();
29458
+ this.unsubscribers.push(
29459
+ googleGenAIChannels.httpResponseJson.intercept(
29460
+ (target, thisArg, args) => {
29461
+ const span = currentSpan();
29462
+ const result = Reflect.apply(target, thisArg, args);
29463
+ if (embeddingSpans.has(span)) {
29464
+ void Promise.resolve(result).then(
29465
+ (response) => {
29466
+ try {
29467
+ const metrics = cleanMetrics3(
29468
+ extractEmbedContentMetrics(response)
29469
+ );
29470
+ if (embeddingSpans.has(span) && Object.keys(metrics).length > 0) {
29471
+ span.log({ metrics });
29472
+ }
29473
+ } catch (error2) {
29474
+ debugLogger.error(
29475
+ "Error reading Google GenAI embedding usage:",
29476
+ error2
29477
+ );
29478
+ }
29479
+ },
29480
+ () => {
29481
+ }
29482
+ // The embedding channel handles the original rejection.
29483
+ );
29484
+ }
29485
+ return result;
29486
+ }
29487
+ )
29488
+ );
28539
29489
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart2(
28540
29490
  tracingChannel,
28541
29491
  states,
28542
29492
  (event) => {
28543
29493
  const params = event.arguments[0];
28544
29494
  const input = serializeEmbedContentInput(params);
28545
- const metadata = extractEmbedContentMetadata(params);
29495
+ const metadata = { provider: "google", model: params.model };
28546
29496
  const span = startSpan(
28547
29497
  withSpanInstrumentationName(
28548
29498
  {
@@ -28555,6 +29505,7 @@ var GoogleGenAIPlugin = class extends BasePlugin {
28555
29505
  INSTRUMENTATION_NAMES.GOOGLE_GENAI
28556
29506
  )
28557
29507
  );
29508
+ embeddingSpans.add(span);
28558
29509
  return {
28559
29510
  span,
28560
29511
  startTime: getCurrentUnixTimestamp()
@@ -28566,7 +29517,7 @@ var GoogleGenAIPlugin = class extends BasePlugin {
28566
29517
  ensureSpanState(states, event, () => {
28567
29518
  const params = event.arguments[0];
28568
29519
  const input = serializeEmbedContentInput(params);
28569
- const metadata = extractEmbedContentMetadata(params);
29520
+ const metadata = { provider: "google", model: params.model };
28570
29521
  const span = startSpan(
28571
29522
  withSpanInstrumentationName(
28572
29523
  {
@@ -28579,6 +29530,7 @@ var GoogleGenAIPlugin = class extends BasePlugin {
28579
29530
  INSTRUMENTATION_NAMES.GOOGLE_GENAI
28580
29531
  )
28581
29532
  );
29533
+ embeddingSpans.add(span);
28582
29534
  return {
28583
29535
  span,
28584
29536
  startTime: getCurrentUnixTimestamp()
@@ -28591,20 +29543,28 @@ var GoogleGenAIPlugin = class extends BasePlugin {
28591
29543
  return;
28592
29544
  }
28593
29545
  try {
28594
- const output = summarizeEmbedContentOutput(event.result);
28595
29546
  spanState.span.log({
28596
- ...output ? { output } : {},
29547
+ output: summarizeEmbedContentOutput(event.result),
28597
29548
  metrics: cleanMetrics3(
28598
29549
  extractEmbedContentMetrics(event.result, spanState.startTime)
28599
29550
  )
28600
29551
  });
28601
29552
  } finally {
29553
+ embeddingSpans.delete(spanState.span);
28602
29554
  spanState.span.end();
28603
29555
  states.delete(event);
28604
29556
  }
28605
29557
  },
28606
29558
  error: (event) => {
28607
- logErrorAndEndSpan(states, event);
29559
+ const spanState = states.get(event);
29560
+ if (!spanState) return;
29561
+ try {
29562
+ spanState.span.log({ error: event.error, output: { count: 0 } });
29563
+ } finally {
29564
+ embeddingSpans.delete(spanState.span);
29565
+ spanState.span.end();
29566
+ states.delete(event);
29567
+ }
28608
29568
  }
28609
29569
  };
28610
29570
  tracingChannel.subscribe(handlers);
@@ -28839,15 +29799,53 @@ function serializeGenerateContentInput(params) {
28839
29799
  return input;
28840
29800
  }
28841
29801
  function serializeEmbedContentInput(params) {
29802
+ let contents = Array.isArray(params.contents) ? params.contents : [params.contents];
29803
+ if (params.model.includes("gemini-embedding-2") && contents.length > 0 && contents.every(
29804
+ (content) => typeof content === "string" || !Array.isArray(content) && !("parts" in content)
29805
+ )) {
29806
+ contents = [contents];
29807
+ }
28842
29808
  const input = {
28843
- model: params.model,
28844
- contents: serializeContentCollection(params.contents)
29809
+ inputs: contents.map((content) => {
29810
+ const parts = typeof content === "string" ? [content] : Array.isArray(content) ? content : "parts" in content ? content.parts : [content];
29811
+ const normalized = parts.flatMap((part) => {
29812
+ if (typeof part === "string") return [{ type: "text", text: part }];
29813
+ if (part.text !== void 0) return [{ type: "text", text: part.text }];
29814
+ const media = part.inlineData ?? part.fileData;
29815
+ if (!media) return [];
29816
+ const data = "data" in media ? `data:${media.mimeType};base64,${typeof media.data === "string" ? media.data : uint8ArrayToBase64(media.data)}` : media.fileUri;
29817
+ return media.mimeType?.startsWith("image/") ? [{ type: "image_url", image_url: { url: data } }] : [
29818
+ {
29819
+ type: "file",
29820
+ file: {
29821
+ file_data: data,
29822
+ ..."displayName" in media && media.displayName ? { filename: media.displayName } : {}
29823
+ }
29824
+ }
29825
+ ];
29826
+ });
29827
+ return {
29828
+ content: normalized.length === 1 && normalized[0].type === "text" ? normalized[0].text : normalized
29829
+ };
29830
+ }),
29831
+ ...params.config?.outputDimensionality !== void 0 ? { output_dimensions: params.config.outputDimensionality } : {}
28845
29832
  };
28846
- const config3 = params.config ? tryToDict(params.config) : null;
28847
- if (config3) {
28848
- input.config = config3;
29833
+ try {
29834
+ const processed = processInputAttachments(input);
29835
+ const hasInlineMedia = processed.inputs.some(
29836
+ ({ content }) => Array.isArray(content) && content.some((part) => {
29837
+ const data = part.type === "image_url" ? part.image_url.url : part.type === "file" ? part.file.file_data : void 0;
29838
+ return typeof data === "string" && data.startsWith("data:");
29839
+ })
29840
+ );
29841
+ return hasInlineMedia ? input : processed;
29842
+ } catch (error2) {
29843
+ debugLogger.error(
29844
+ "Error processing Google GenAI embedding attachments:",
29845
+ error2
29846
+ );
29847
+ return input;
28849
29848
  }
28850
- return input;
28851
29849
  }
28852
29850
  function serializeInteractionInput(params) {
28853
29851
  const input = {
@@ -29035,19 +30033,6 @@ function extractGenerateContentMetadata(params) {
29035
30033
  }
29036
30034
  return metadata;
29037
30035
  }
29038
- function extractEmbedContentMetadata(params) {
29039
- const metadata = {};
29040
- if (params.model) {
29041
- metadata.model = params.model;
29042
- }
29043
- const config3 = params.config ? tryToDict(params.config) : null;
29044
- if (config3) {
29045
- Object.keys(config3).forEach((key) => {
29046
- metadata[key] = config3[key];
29047
- });
29048
- }
29049
- return metadata;
29050
- }
29051
30036
  function extractGenerateContentMetrics(response, startTime) {
29052
30037
  const metrics = {};
29053
30038
  if (startTime !== void 0) {
@@ -29067,15 +30052,23 @@ function extractEmbedContentMetrics(response, startTime) {
29067
30052
  const end = getCurrentUnixTimestamp();
29068
30053
  metrics.start = startTime;
29069
30054
  metrics.end = end;
29070
- metrics.duration = end - startTime;
29071
- }
29072
- if (response?.usageMetadata) {
29073
- populateUsageMetrics(metrics, response.usageMetadata);
29074
30055
  }
29075
30056
  const embeddingTokenCount = extractEmbedPromptTokenCount(response);
29076
30057
  if (embeddingTokenCount !== void 0) {
29077
30058
  metrics.prompt_tokens = embeddingTokenCount;
29078
- metrics.tokens = embeddingTokenCount;
30059
+ }
30060
+ const totalTokens = response?.usageMetadata?.totalTokenCount ?? embeddingTokenCount;
30061
+ if (totalTokens !== void 0) {
30062
+ metrics.tokens = totalTokens;
30063
+ }
30064
+ const audioTokens = (response?.usageMetadata?.promptTokenDetails ?? response?.usageMetadata?.promptTokensDetails)?.filter(
30065
+ (detail) => detail.modality === "AUDIO" && detail.tokenCount !== void 0
30066
+ );
30067
+ if (audioTokens?.length) {
30068
+ metrics.prompt_audio_tokens = audioTokens.reduce(
30069
+ (sum, detail) => sum + (detail.tokenCount ?? 0),
30070
+ 0
30071
+ );
29079
30072
  }
29080
30073
  return metrics;
29081
30074
  }
@@ -29114,41 +30107,25 @@ function extractEmbedPromptTokenCount(response) {
29114
30107
  if (typeof usagePromptTokens === "number" && Number.isFinite(usagePromptTokens)) {
29115
30108
  return usagePromptTokens;
29116
30109
  }
29117
- const usageTotalTokens = response.usageMetadata?.totalTokenCount;
29118
- if (typeof usageTotalTokens === "number" && Number.isFinite(usageTotalTokens)) {
29119
- return usageTotalTokens;
29120
- }
29121
30110
  const embeddings = Array.isArray(response.embeddings) ? response.embeddings : response.embedding ? [response.embedding] : [];
29122
30111
  if (embeddings.length === 0) {
29123
30112
  return void 0;
29124
30113
  }
29125
30114
  let total = 0;
29126
- let sawAny = false;
29127
30115
  for (const embedding of embeddings) {
29128
30116
  const embeddingStats = tryToDict(tryToDict(embedding)?.statistics);
29129
30117
  const tokenCount2 = embeddingStats?.tokenCount;
29130
30118
  if (typeof tokenCount2 === "number" && Number.isFinite(tokenCount2)) {
29131
30119
  total += tokenCount2;
29132
- sawAny = true;
30120
+ } else {
30121
+ return void 0;
29133
30122
  }
29134
30123
  }
29135
- return sawAny ? total : void 0;
30124
+ return total;
29136
30125
  }
29137
30126
  function summarizeEmbedContentOutput(response) {
29138
- if (!response) {
29139
- return void 0;
29140
- }
29141
- const embeddings = Array.isArray(response.embeddings) ? response.embeddings : response.embedding ? [response.embedding] : [];
29142
- if (embeddings.length === 0) {
29143
- return void 0;
29144
- }
29145
- const firstValues = embeddings[0]?.values;
29146
- if (!Array.isArray(firstValues)) {
29147
- return void 0;
29148
- }
29149
30127
  return {
29150
- embedding_count: embeddings.length,
29151
- embedding_length: firstValues.length
30128
+ count: Array.isArray(response?.embeddings) ? response.embeddings.length : response?.embedding ? 1 : 0
29152
30129
  };
29153
30130
  }
29154
30131
  function populateUsageMetrics(metrics, usage) {
@@ -32775,6 +33752,379 @@ function aggregateMistralStreamChunks(chunks) {
32775
33752
  };
32776
33753
  }
32777
33754
 
33755
+ // src/instrumentation/plugins/langgraph-sdk-channels.ts
33756
+ var langGraphSDKChannels = defineChannels(
33757
+ "@langchain/langgraph-sdk",
33758
+ {
33759
+ wait: channel({
33760
+ channelName: "runs.wait",
33761
+ kind: "async"
33762
+ }),
33763
+ stream: channel({
33764
+ channelName: "runs.stream",
33765
+ kind: "sync-stream"
33766
+ })
33767
+ },
33768
+ { instrumentationName: INSTRUMENTATION_NAMES.LANGGRAPH_SDK }
33769
+ );
33770
+
33771
+ // src/instrumentation/plugins/langgraph-sdk-plugin.ts
33772
+ var LangGraphSDKPlugin = class extends BasePlugin {
33773
+ onEnable() {
33774
+ this.unsubscribers.push(
33775
+ langGraphSDKChannels.wait.intercept(
33776
+ (target, self, args) => instrumentRun("wait", args, () => Reflect.apply(target, self, args))
33777
+ ),
33778
+ langGraphSDKChannels.stream.intercept(
33779
+ (target, self, args) => instrumentRun("stream", args, () => Reflect.apply(target, self, args))
33780
+ )
33781
+ );
33782
+ }
33783
+ onDisable() {
33784
+ this.unsubscribers = unsubscribeAll(this.unsubscribers);
33785
+ }
33786
+ };
33787
+ function normalizeMessage(value) {
33788
+ if (!isObject(value)) return value;
33789
+ 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);
33790
+ if (typeof role !== "string") return value;
33791
+ const message = {
33792
+ role,
33793
+ content: value.content ?? ""
33794
+ };
33795
+ for (const key of ["name", "tool_call_id", "refusal"]) {
33796
+ if (value[key] !== void 0) message[key] = value[key];
33797
+ }
33798
+ const additional = isObject(value.additional_kwargs) ? value.additional_kwargs : {};
33799
+ const toolCalls = Array.isArray(value.tool_calls) && value.tool_calls.length ? value.tool_calls : additional.tool_calls;
33800
+ if (Array.isArray(toolCalls) && toolCalls.length > 0) {
33801
+ message.tool_calls = toolCalls.map((call) => {
33802
+ if (!isObject(call)) return call;
33803
+ if (isObject(call.function)) return call;
33804
+ return {
33805
+ id: call.id,
33806
+ type: "function",
33807
+ function: {
33808
+ name: call.name,
33809
+ arguments: typeof call.args === "string" ? call.args : JSON.stringify(call.args ?? {})
33810
+ }
33811
+ };
33812
+ });
33813
+ }
33814
+ if (Array.isArray(value.invalid_tool_calls) && value.invalid_tool_calls.length > 0)
33815
+ message.invalid_tool_calls = value.invalid_tool_calls;
33816
+ if (message.refusal === void 0 && additional.refusal !== void 0)
33817
+ message.refusal = additional.refusal;
33818
+ return message;
33819
+ }
33820
+ function normalizeRunError(value) {
33821
+ let name;
33822
+ let message;
33823
+ if (value instanceof Error) {
33824
+ name = value.name;
33825
+ message = value.message;
33826
+ } else if (isObject(value) && typeof value.error === "string" && typeof value.message === "string") {
33827
+ name = value.error;
33828
+ message = value.message;
33829
+ } else {
33830
+ return value;
33831
+ }
33832
+ for (let depth = 0; depth < 3; depth++) {
33833
+ try {
33834
+ const nested = JSON.parse(
33835
+ message.startsWith(`${name}: `) ? message.slice(name.length + 2) : message
33836
+ );
33837
+ if (!isObject(nested) || typeof nested.error !== "string" || typeof nested.message !== "string")
33838
+ break;
33839
+ name = nested.error;
33840
+ message = nested.message;
33841
+ } catch {
33842
+ break;
33843
+ }
33844
+ }
33845
+ if (value instanceof Error && name === value.name && message === value.message)
33846
+ return value;
33847
+ return Object.assign(new Error(message), { name });
33848
+ }
33849
+ function normalizeState(value) {
33850
+ if (!isObject(value)) return value;
33851
+ return Object.fromEntries(
33852
+ Object.entries(value).map(([key, field]) => {
33853
+ if (key === "messages" && Array.isArray(field))
33854
+ return [key, field.map(normalizeMessage)];
33855
+ if (key === "__error__") {
33856
+ const error2 = normalizeRunError(field);
33857
+ if (error2 instanceof Error)
33858
+ return [key, { error: error2.name, message: error2.message }];
33859
+ }
33860
+ return [key, field];
33861
+ })
33862
+ );
33863
+ }
33864
+ function normalizeRunOutput(value, input) {
33865
+ if (!isObject(value)) return value;
33866
+ if (Array.isArray(value.messages)) {
33867
+ if (value.__interrupt__ !== void 0 || value.__error__ !== void 0)
33868
+ return void 0;
33869
+ const inputMessages = isObject(input) && Array.isArray(input.messages) ? input.messages : [];
33870
+ let inputPrefixLength = 0;
33871
+ while (inputPrefixLength < inputMessages.length) {
33872
+ const previous = inputMessages[inputPrefixLength];
33873
+ const message = value.messages[inputPrefixLength];
33874
+ 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)))
33875
+ break;
33876
+ inputPrefixLength++;
33877
+ }
33878
+ for (let index = value.messages.length - 1; index >= inputPrefixLength; index--) {
33879
+ const message = value.messages[index];
33880
+ const normalized = normalizeMessage(message);
33881
+ if (!isObject(normalized)) continue;
33882
+ if (normalized.role === "user") return void 0;
33883
+ if (normalized.role !== "assistant") continue;
33884
+ if (inputMessages.some((previous) => {
33885
+ if (!isObject(previous) || !isObject(message)) return false;
33886
+ return previous.id !== void 0 && previous.id === message.id && JSON.stringify(normalizeMessage(previous)) === JSON.stringify(normalized);
33887
+ }))
33888
+ continue;
33889
+ return normalized;
33890
+ }
33891
+ return void 0;
33892
+ }
33893
+ const result = Object.fromEntries(
33894
+ Object.entries(value).filter(
33895
+ ([key]) => key !== "__interrupt__" && key !== "__error__"
33896
+ )
33897
+ );
33898
+ return !Object.keys(result).length && (value.__interrupt__ !== void 0 || value.__error__ !== void 0) ? void 0 : result;
33899
+ }
33900
+ function instrumentRun(operation, [threadId, assistantId, options], invoke2) {
33901
+ if (isAutoInstrumentationSuppressed()) return invoke2();
33902
+ const start = getCurrentUnixTimestamp();
33903
+ let span;
33904
+ try {
33905
+ const metadata = {
33906
+ "langgraph.thread_id": threadId,
33907
+ "langgraph.assistant_id": assistantId
33908
+ };
33909
+ for (const key of [
33910
+ "streamMode",
33911
+ "streamSubgraphs",
33912
+ "interruptBefore",
33913
+ "interruptAfter",
33914
+ "multitaskStrategy",
33915
+ "durability"
33916
+ ]) {
33917
+ if (options?.[key] !== void 0) metadata[key] = options[key];
33918
+ }
33919
+ span = startSpan(
33920
+ withSpanInstrumentationName(
33921
+ {
33922
+ name: `langgraph.runs.${operation}`,
33923
+ spanAttributes: { type: "task" /* TASK */ },
33924
+ event: {
33925
+ input: options?.command === void 0 ? normalizeState(options?.input) : {
33926
+ input: normalizeState(options.input),
33927
+ command: options.command
33928
+ },
33929
+ metadata
33930
+ }
33931
+ },
33932
+ INSTRUMENTATION_NAMES.LANGGRAPH_SDK
33933
+ )
33934
+ );
33935
+ } catch (error2) {
33936
+ debugLogger.error("Error starting LangGraph SDK span:", error2);
33937
+ return invoke2();
33938
+ }
33939
+ let ended = false;
33940
+ let output;
33941
+ let streamError;
33942
+ let firstToken;
33943
+ const updates = [];
33944
+ const usageByMessage = /* @__PURE__ */ new Map();
33945
+ const captureUsage = (id, usage) => {
33946
+ if (!isObject(usage)) return;
33947
+ const metrics = {};
33948
+ for (const [source, destination] of [
33949
+ ["input_tokens", "prompt_tokens"],
33950
+ ["output_tokens", "completion_tokens"],
33951
+ ["total_tokens", "tokens"]
33952
+ ]) {
33953
+ const value = usage[source];
33954
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0)
33955
+ metrics[destination] = value;
33956
+ }
33957
+ if (metrics.tokens === void 0 && metrics.prompt_tokens !== void 0 && metrics.completion_tokens !== void 0)
33958
+ metrics.tokens = metrics.prompt_tokens + metrics.completion_tokens;
33959
+ usageByMessage.set(id, { ...usageByMessage.get(id), ...metrics });
33960
+ };
33961
+ const messages = /* @__PURE__ */ new Map();
33962
+ const messageSnapshots = /* @__PURE__ */ new Map();
33963
+ const finish = (error2) => {
33964
+ if (ended) return;
33965
+ ended = true;
33966
+ try {
33967
+ const metrics = {};
33968
+ for (const usage of usageByMessage.values()) {
33969
+ for (const [key, value] of Object.entries(usage))
33970
+ metrics[key] = (metrics[key] ?? 0) + value;
33971
+ }
33972
+ if (firstToken !== void 0)
33973
+ metrics.time_to_first_token = firstToken - start;
33974
+ const finalMessages = [
33975
+ ...new Map([...messages, ...messageSnapshots]).values()
33976
+ ];
33977
+ let loggedOutput = normalizeRunOutput(output, options?.input);
33978
+ if (loggedOutput === void 0 && finalMessages.length)
33979
+ loggedOutput = normalizeRunOutput(
33980
+ { messages: finalMessages },
33981
+ void 0
33982
+ );
33983
+ if (output === void 0 && !finalMessages.length && updates.length) {
33984
+ const results = updates.map((update) => normalizeRunOutput(update, options?.input)).filter((update) => update !== void 0);
33985
+ if (results.length) loggedOutput = { updates: results };
33986
+ }
33987
+ const interrupted = [output, ...updates].find(
33988
+ (state) => isObject(state) && state.__interrupt__ !== void 0
33989
+ );
33990
+ span.log({
33991
+ ...loggedOutput !== void 0 ? { output: loggedOutput } : {},
33992
+ ...isObject(interrupted) ? { metadata: { "langgraph.interrupts": interrupted.__interrupt__ } } : {},
33993
+ ...error2 !== void 0 || streamError !== void 0 ? { error: normalizeRunError(error2 ?? streamError) } : {},
33994
+ metrics
33995
+ });
33996
+ } catch (error3) {
33997
+ debugLogger.error("Error logging LangGraph SDK span:", error3);
33998
+ }
33999
+ try {
34000
+ span.end();
34001
+ } catch (error3) {
34002
+ debugLogger.error("Error ending LangGraph SDK span:", error3);
34003
+ }
34004
+ };
34005
+ const observeMessages = (value, streaming) => {
34006
+ if (!isObject(value) || !Array.isArray(value.messages)) return;
34007
+ const inputMessages = isObject(options?.input) && Array.isArray(options.input.messages) ? options.input.messages : [];
34008
+ for (const message of value.messages) {
34009
+ if (!isObject(message) || message.type !== "ai" && message.role !== "assistant")
34010
+ continue;
34011
+ if (message.id !== void 0 && inputMessages.some(
34012
+ (input) => isObject(input) && input.id === message.id
34013
+ ))
34014
+ continue;
34015
+ captureUsage(
34016
+ typeof message.id === "string" ? message.id : "message",
34017
+ message.usage_metadata
34018
+ );
34019
+ if (streaming && (typeof message.content === "string" ? message.content.length > 0 : Array.isArray(message.content) && message.content.some(
34020
+ (part) => isObject(part) && typeof part.text === "string" && part.text.length > 0
34021
+ )))
34022
+ firstToken ??= getCurrentUnixTimestamp();
34023
+ }
34024
+ };
34025
+ const onChunk = ({ event, data }) => {
34026
+ if (ended) return;
34027
+ if (event === "metadata" && isObject(data)) {
34028
+ if (typeof data.run_id === "string")
34029
+ span.log({ metadata: { "langgraph.run_id": data.run_id } });
34030
+ } else if (event === "error") {
34031
+ streamError = normalizeRunError(data);
34032
+ } else if (event === "values") {
34033
+ output = data;
34034
+ observeMessages(data, true);
34035
+ } else if (event === "updates") {
34036
+ if (isObject(data)) {
34037
+ const stateUpdates = [];
34038
+ for (const [node, update] of Object.entries(data)) {
34039
+ observeMessages(update, true);
34040
+ if (isObject(update) && Array.isArray(update.messages)) {
34041
+ for (const message of update.messages) {
34042
+ if (isObject(message))
34043
+ messageSnapshots.set(
34044
+ typeof message.id === "string" ? message.id : `update-${messageSnapshots.size}`,
34045
+ message
34046
+ );
34047
+ }
34048
+ const state = Object.fromEntries(
34049
+ Object.entries(update).filter(([key]) => key !== "messages")
34050
+ );
34051
+ if (Object.keys(state).length) stateUpdates.push([node, state]);
34052
+ } else {
34053
+ stateUpdates.push([node, update]);
34054
+ }
34055
+ }
34056
+ if (stateUpdates.length) updates.push(Object.fromEntries(stateUpdates));
34057
+ } else {
34058
+ updates.push(data);
34059
+ }
34060
+ } else if ((event === "messages" || event === "messages/partial" || event === "messages/complete") && Array.isArray(data)) {
34061
+ const parts = event === "messages" ? [data[0]] : data;
34062
+ for (const part of parts) {
34063
+ if (!isObject(part)) continue;
34064
+ const id = typeof part.id === "string" ? part.id : "message";
34065
+ captureUsage(id, part.usage_metadata);
34066
+ const previous = messages.get(id);
34067
+ messages.set(
34068
+ id,
34069
+ event === "messages" && previous && typeof part.content === "string" && typeof previous.content === "string" ? { ...part, content: previous.content + part.content } : part
34070
+ );
34071
+ if (typeof part.content === "string" && part.content.length > 0)
34072
+ firstToken ??= getCurrentUnixTimestamp();
34073
+ }
34074
+ }
34075
+ };
34076
+ let result;
34077
+ try {
34078
+ result = withCurrent(
34079
+ span,
34080
+ () => runWithAutoInstrumentationSuppressed(invoke2)
34081
+ );
34082
+ } catch (error2) {
34083
+ finish(error2);
34084
+ throw error2;
34085
+ }
34086
+ if (operation === "stream") {
34087
+ try {
34088
+ patchStreamIfNeeded(result, {
34089
+ shouldCollect: (chunk) => {
34090
+ try {
34091
+ onChunk(chunk);
34092
+ } catch (error2) {
34093
+ debugLogger.error(
34094
+ "Error processing LangGraph stream event:",
34095
+ error2
34096
+ );
34097
+ }
34098
+ return false;
34099
+ },
34100
+ aroundNext: (next) => withCurrent(span, () => runWithAutoInstrumentationSuppressed(next)),
34101
+ onComplete: () => finish(),
34102
+ onCancel: () => finish(),
34103
+ onError: (error2) => finish(error2)
34104
+ });
34105
+ } catch (error2) {
34106
+ debugLogger.error("Error observing LangGraph stream:", error2);
34107
+ finish();
34108
+ }
34109
+ } else {
34110
+ void Promise.resolve(result).then(
34111
+ (value) => {
34112
+ try {
34113
+ output = value;
34114
+ observeMessages(value, false);
34115
+ if (isObject(value) && isObject(value.__error__))
34116
+ streamError = normalizeRunError(value.__error__);
34117
+ finish();
34118
+ } catch (error2) {
34119
+ finish(error2);
34120
+ }
34121
+ },
34122
+ (error2) => finish(error2)
34123
+ );
34124
+ }
34125
+ return result;
34126
+ }
34127
+
32778
34128
  // src/instrumentation/plugins/ollama-channels.ts
32779
34129
  var ollamaChannels = defineChannels(
32780
34130
  "ollama",
@@ -32984,7 +34334,7 @@ function normalizeTextAndImages(content, images) {
32984
34334
  ...unrecognizedImages.length > 0 ? { unrecognizedImages } : {}
32985
34335
  };
32986
34336
  }
32987
- function normalizeMessage(message, toolCallId, syntheticToolCallIdOffset = 0) {
34337
+ function normalizeMessage2(message, toolCallId, syntheticToolCallIdOffset = 0) {
32988
34338
  if (typeof message.role !== "string") {
32989
34339
  return void 0;
32990
34340
  }
@@ -33030,7 +34380,7 @@ function normalizeMessages(messages) {
33030
34380
  toolCallId = pendingToolCallIds.get(toolName)?.shift();
33031
34381
  }
33032
34382
  }
33033
- const normalized = normalizeMessage(
34383
+ const normalized = normalizeMessage2(
33034
34384
  ollamaMessage,
33035
34385
  toolCallId,
33036
34386
  syntheticToolCallIdOffset
@@ -33149,7 +34499,7 @@ function extractOllamaChatOutput(result, syntheticToolCallIdOffset = 0) {
33149
34499
  if (!isObject(result) || !isObject(result.message)) {
33150
34500
  return void 0;
33151
34501
  }
33152
- const message = normalizeMessage(
34502
+ const message = normalizeMessage2(
33153
34503
  result.message,
33154
34504
  void 0,
33155
34505
  syntheticToolCallIdOffset
@@ -35869,14 +37219,14 @@ function extractActionSpanMetadata(args) {
35869
37219
  const options = extractRunInNewSpanOptions(args);
35870
37220
  const labels = isObject(options?.labels) ? options.labels : void 0;
35871
37221
  const metadata = isObject(options?.metadata) ? options.metadata : void 0;
35872
- const actionType = stringValue(labels?.["genkit:metadata:subtype"]);
35873
- const name = stringValue(metadata?.name);
37222
+ const actionType = stringValue2(labels?.["genkit:metadata:subtype"]);
37223
+ const name = stringValue2(metadata?.name);
35874
37224
  if (!actionType || !name) {
35875
37225
  return void 0;
35876
37226
  }
35877
37227
  return {
35878
37228
  actionType,
35879
- key: stringValue(labels?.["genkit:key"]),
37229
+ key: stringValue2(labels?.["genkit:key"]),
35880
37230
  name
35881
37231
  };
35882
37232
  }
@@ -35986,7 +37336,7 @@ function pickNumberMetrics(values) {
35986
37336
  })
35987
37337
  );
35988
37338
  }
35989
- function stringValue(value) {
37339
+ function stringValue2(value) {
35990
37340
  return typeof value === "string" ? value : void 0;
35991
37341
  }
35992
37342
 
@@ -36671,7 +38021,7 @@ function subscribeToFlueContext(value, state) {
36671
38021
  try {
36672
38022
  unsubscribe?.();
36673
38023
  } catch (error2) {
36674
- logInstrumentationError3("Flue context unsubscribe", error2);
38024
+ logInstrumentationError4("Flue context unsubscribe", error2);
36675
38025
  }
36676
38026
  };
36677
38027
  try {
@@ -36687,7 +38037,7 @@ function subscribeToFlueContext(value, state) {
36687
38037
  });
36688
38038
  state.contexts.add(value);
36689
38039
  } catch (error2) {
36690
- logInstrumentationError3("Flue context subscription", error2);
38040
+ logInstrumentationError4("Flue context subscription", error2);
36691
38041
  }
36692
38042
  }
36693
38043
  function isAutoContextTerminalEvent(event, ctx) {
@@ -36743,7 +38093,7 @@ var FlueObserveBridge = class {
36743
38093
  try {
36744
38094
  this.handleEvent(event, flueContextFromUnknown(ctx));
36745
38095
  } catch (error2) {
36746
- logInstrumentationError3("Flue observe", error2);
38096
+ logInstrumentationError4("Flue observe", error2);
36747
38097
  }
36748
38098
  }
36749
38099
  reset() {
@@ -36760,7 +38110,7 @@ var FlueObserveBridge = class {
36760
38110
  try {
36761
38111
  span = this.spanForExecutionOperation(operation, executionContext);
36762
38112
  } catch (error2) {
36763
- logInstrumentationError3("Flue execution interceptor", error2);
38113
+ logInstrumentationError4("Flue execution interceptor", error2);
36764
38114
  }
36765
38115
  return span ? runWithCurrentSpanStore(span, next) : next();
36766
38116
  }
@@ -36966,7 +38316,7 @@ var FlueObserveBridge = class {
36966
38316
  this.runsById.delete(event.runId);
36967
38317
  }
36968
38318
  void flush().catch((error2) => {
36969
- logInstrumentationError3("Flue flush", error2);
38319
+ logInstrumentationError4("Flue flush", error2);
36970
38320
  });
36971
38321
  }
36972
38322
  handleOperationStart(event) {
@@ -37741,17 +39091,17 @@ function safeLog3(span, event) {
37741
39091
  try {
37742
39092
  span.log(event);
37743
39093
  } catch (error2) {
37744
- logInstrumentationError3("Flue span log", error2);
39094
+ logInstrumentationError4("Flue span log", error2);
37745
39095
  }
37746
39096
  }
37747
39097
  function safeEnd(span, endTime) {
37748
39098
  try {
37749
39099
  span.end(endTime === void 0 ? void 0 : { endTime });
37750
39100
  } catch (error2) {
37751
- logInstrumentationError3("Flue span end", error2);
39101
+ logInstrumentationError4("Flue span end", error2);
37752
39102
  }
37753
39103
  }
37754
- function logInstrumentationError3(label, error2) {
39104
+ function logInstrumentationError4(label, error2) {
37755
39105
  debugLogger.debug(`Error in ${label} instrumentation:`, error2);
37756
39106
  }
37757
39107
 
@@ -38051,11 +39401,11 @@ function walkGenerations(response) {
38051
39401
  for (const batch of generations) {
38052
39402
  if (Array.isArray(batch)) {
38053
39403
  for (const generation of batch) {
38054
- if (isRecord(generation)) {
39404
+ if (isRecord2(generation)) {
38055
39405
  result.push(generation);
38056
39406
  }
38057
39407
  }
38058
- } else if (isRecord(batch)) {
39408
+ } else if (isRecord2(batch)) {
38059
39409
  result.push(batch);
38060
39410
  }
38061
39411
  }
@@ -38064,11 +39414,11 @@ function walkGenerations(response) {
38064
39414
  function getModelNameFromResponse(response) {
38065
39415
  for (const generation of walkGenerations(response)) {
38066
39416
  const message = generation.message;
38067
- if (!isRecord(message)) {
39417
+ if (!isRecord2(message)) {
38068
39418
  continue;
38069
39419
  }
38070
39420
  const responseMetadata = message.response_metadata;
38071
- if (!isRecord(responseMetadata)) {
39421
+ if (!isRecord2(responseMetadata)) {
38072
39422
  continue;
38073
39423
  }
38074
39424
  const modelName3 = responseMetadata.model_name ?? responseMetadata.model;
@@ -38083,14 +39433,14 @@ function getModelNameFromResponse(response) {
38083
39433
  function getMetricsFromResponse(response) {
38084
39434
  for (const generation of walkGenerations(response)) {
38085
39435
  const message = generation.message;
38086
- if (!isRecord(message)) {
39436
+ if (!isRecord2(message)) {
38087
39437
  continue;
38088
39438
  }
38089
39439
  const usageMetadata = message.usage_metadata;
38090
- if (!isRecord(usageMetadata)) {
39440
+ if (!isRecord2(usageMetadata)) {
38091
39441
  continue;
38092
39442
  }
38093
- const inputTokenDetails = isRecord(usageMetadata.input_token_details) ? usageMetadata.input_token_details : {};
39443
+ const inputTokenDetails = isRecord2(usageMetadata.input_token_details) ? usageMetadata.input_token_details : {};
38094
39444
  const outputTokenDetails = usageMetadata.output_token_details;
38095
39445
  return normalizeTokenMetrics({
38096
39446
  total_tokens: usageMetadata.total_tokens,
@@ -38101,11 +39451,11 @@ function getMetricsFromResponse(response) {
38101
39451
  prompt_cache_creation_5m_tokens: inputTokenDetails.ephemeral_5m_input_tokens,
38102
39452
  prompt_cache_creation_1h_tokens: inputTokenDetails.ephemeral_1h_input_tokens,
38103
39453
  prompt_cached_tokens: inputTokenDetails.cache_read,
38104
- completion_reasoning_tokens: isRecord(outputTokenDetails) ? outputTokenDetails.reasoning : void 0
39454
+ completion_reasoning_tokens: isRecord2(outputTokenDetails) ? outputTokenDetails.reasoning : void 0
38105
39455
  });
38106
39456
  }
38107
39457
  const llmOutput = response.llmOutput || {};
38108
- const tokenUsage = isRecord(llmOutput.tokenUsage) ? llmOutput.tokenUsage : isRecord(llmOutput.estimatedTokens) ? llmOutput.estimatedTokens : {};
39458
+ const tokenUsage = isRecord2(llmOutput.tokenUsage) ? llmOutput.tokenUsage : isRecord2(llmOutput.estimatedTokens) ? llmOutput.estimatedTokens : {};
38109
39459
  return normalizeTokenMetrics({
38110
39460
  total_tokens: tokenUsage.totalTokens,
38111
39461
  prompt_tokens: tokenUsage.promptTokens,
@@ -38119,7 +39469,7 @@ function safeJsonParse(input) {
38119
39469
  return input;
38120
39470
  }
38121
39471
  }
38122
- function isRecord(value) {
39472
+ function isRecord2(value) {
38123
39473
  return typeof value === "object" && value !== null && !Array.isArray(value);
38124
39474
  }
38125
39475
 
@@ -38313,16 +39663,16 @@ var LangSmithPlugin = class extends BasePlugin {
38313
39663
  this.completedRuns.clear();
38314
39664
  }
38315
39665
  processBatch(batch) {
38316
- if (!isRecord2(batch)) {
39666
+ if (!isRecord3(batch)) {
38317
39667
  return;
38318
39668
  }
38319
39669
  const creates = ownValue(batch, "runCreates");
38320
39670
  if (Array.isArray(creates)) {
38321
39671
  const parentFirst = [...creates].sort((left, right) => {
38322
- const leftId = stringValue2(ownValue(left, "id"));
38323
- const rightId = stringValue2(ownValue(right, "id"));
38324
- const leftParent = stringValue2(ownValue(left, "parent_run_id"));
38325
- const rightParent = stringValue2(ownValue(right, "parent_run_id"));
39672
+ const leftId = stringValue3(ownValue(left, "id"));
39673
+ const rightId = stringValue3(ownValue(right, "id"));
39674
+ const leftParent = stringValue3(ownValue(left, "parent_run_id"));
39675
+ const rightParent = stringValue3(ownValue(right, "parent_run_id"));
38326
39676
  if (leftParent && leftParent === rightId) {
38327
39677
  return 1;
38328
39678
  }
@@ -38341,13 +39691,13 @@ var LangSmithPlugin = class extends BasePlugin {
38341
39691
  if (Array.isArray(updates)) {
38342
39692
  for (const run2 of updates) {
38343
39693
  this.containLifecycleFailure("batchIngestRuns update", () => {
38344
- this.processUpdate(stringValue2(ownValue(run2, "id")) ?? "", run2);
39694
+ this.processUpdate(stringValue3(ownValue(run2, "id")) ?? "", run2);
38345
39695
  });
38346
39696
  }
38347
39697
  }
38348
39698
  }
38349
39699
  processCreate(run2) {
38350
- const id = stringValue2(ownValue(run2, "id"));
39700
+ const id = stringValue3(ownValue(run2, "id"));
38351
39701
  if (!id || this.completedRuns.get(id)) {
38352
39702
  return;
38353
39703
  }
@@ -38380,7 +39730,7 @@ var LangSmithPlugin = class extends BasePlugin {
38380
39730
  this.endIfComplete(id, activeRun, run2);
38381
39731
  }
38382
39732
  processUpdate(explicitId, run2) {
38383
- const id = stringValue2(explicitId) ?? stringValue2(ownValue(run2, "id"));
39733
+ const id = stringValue3(explicitId) ?? stringValue3(ownValue(run2, "id"));
38384
39734
  if (!id || this.completedRuns.get(id)) {
38385
39735
  return;
38386
39736
  }
@@ -38403,13 +39753,13 @@ var LangSmithPlugin = class extends BasePlugin {
38403
39753
  this.endIfComplete(id, active, active.run);
38404
39754
  }
38405
39755
  startRunSpan(id, run2) {
38406
- const traceId = stringValue2(ownValue(run2, "trace_id")) ?? id;
38407
- const parentId = stringValue2(ownValue(run2, "parent_run_id")) ?? stringValue2(ownValue(ownValue(run2, "parent_run"), "id"));
39756
+ const traceId = stringValue3(ownValue(run2, "trace_id")) ?? id;
39757
+ const parentId = stringValue3(ownValue(run2, "parent_run_id")) ?? stringValue3(ownValue(ownValue(run2, "parent_run"), "id"));
38408
39758
  const startTime = timestampSeconds(ownValue(run2, "start_time"));
38409
39759
  return startSpan(
38410
39760
  withSpanInstrumentationName(
38411
39761
  {
38412
- name: stringValue2(ownValue(run2, "name")) ?? "LangSmith run",
39762
+ name: stringValue3(ownValue(run2, "name")) ?? "LangSmith run",
38413
39763
  spanId: id,
38414
39764
  parentSpanIds: {
38415
39765
  parentSpanIds: parentId ? [parentId] : [],
@@ -38455,7 +39805,7 @@ var LangSmithPlugin = class extends BasePlugin {
38455
39805
  return false;
38456
39806
  }
38457
39807
  const serialized = ownValue(run2, "serialized");
38458
- return isRecord2(serialized) && ownValue(serialized, "lc") === 1;
39808
+ return isRecord3(serialized) && ownValue(serialized, "lc") === 1;
38459
39809
  }
38460
39810
  containLifecycleFailure(operation, fn) {
38461
39811
  try {
@@ -38469,14 +39819,14 @@ var LangSmithPlugin = class extends BasePlugin {
38469
39819
  }
38470
39820
  };
38471
39821
  function ownValue(value, key) {
38472
- if (!isRecord2(value)) {
39822
+ if (!isRecord3(value)) {
38473
39823
  return void 0;
38474
39824
  }
38475
39825
  const descriptor = Object.getOwnPropertyDescriptor(value, key);
38476
39826
  return descriptor && "value" in descriptor ? descriptor.value : void 0;
38477
39827
  }
38478
39828
  function preferOwnValue(current, previous, key) {
38479
- const currentDescriptor = isRecord2(current) ? Object.getOwnPropertyDescriptor(current, key) : void 0;
39829
+ const currentDescriptor = isRecord3(current) ? Object.getOwnPropertyDescriptor(current, key) : void 0;
38480
39830
  if (currentDescriptor && "value" in currentDescriptor) {
38481
39831
  return currentDescriptor.value;
38482
39832
  }
@@ -38485,7 +39835,7 @@ function preferOwnValue(current, previous, key) {
38485
39835
  function mergeRuns(previous, current) {
38486
39836
  const entries = /* @__PURE__ */ new Map();
38487
39837
  for (const value of [previous, current]) {
38488
- if (!isRecord2(value)) {
39838
+ if (!isRecord3(value)) {
38489
39839
  continue;
38490
39840
  }
38491
39841
  for (const [key, descriptor] of Object.entries(
@@ -38498,10 +39848,10 @@ function mergeRuns(previous, current) {
38498
39848
  }
38499
39849
  return Object.fromEntries(entries);
38500
39850
  }
38501
- function isRecord2(value) {
39851
+ function isRecord3(value) {
38502
39852
  return typeof value === "object" && value !== null && !Array.isArray(value);
38503
39853
  }
38504
- function stringValue2(value) {
39854
+ function stringValue3(value) {
38505
39855
  return typeof value === "string" && value.length > 0 ? value : void 0;
38506
39856
  }
38507
39857
  function timestampSeconds(value) {
@@ -38519,7 +39869,7 @@ function timestampSeconds(value) {
38519
39869
  return void 0;
38520
39870
  }
38521
39871
  function dottedOrderDepth(run2) {
38522
- const dottedOrder = stringValue2(ownValue(run2, "dotted_order"));
39872
+ const dottedOrder = stringValue3(ownValue(run2, "dotted_order"));
38523
39873
  return dottedOrder ? dottedOrder.split(".").length : Number.MAX_SAFE_INTEGER;
38524
39874
  }
38525
39875
  function mapRunType(runType) {
@@ -38537,7 +39887,7 @@ function mapRunType(runType) {
38537
39887
  function extractMetadata2(run2, previous) {
38538
39888
  const extra = preferOwnValue(run2, previous, "extra");
38539
39889
  const rawMetadata = ownValue(extra, "metadata");
38540
- if (!isRecord2(rawMetadata)) {
39890
+ if (!isRecord3(rawMetadata)) {
38541
39891
  return void 0;
38542
39892
  }
38543
39893
  const metadata = {};
@@ -38724,7 +40074,7 @@ var PiCodingAgentPlugin = class extends BasePlugin {
38724
40074
  }
38725
40075
  );
38726
40076
  } catch (error2) {
38727
- logInstrumentationError4("Pi Coding Agent prompt start", error2);
40077
+ logInstrumentationError5("Pi Coding Agent prompt start", error2);
38728
40078
  }
38729
40079
  if (!state) {
38730
40080
  return runWithAutoInstrumentationSuppressed(invokeTarget);
@@ -38857,12 +40207,12 @@ function installPiAgentInstrumentation(agent) {
38857
40207
  () => handlePiAgentEvent(state, event)
38858
40208
  );
38859
40209
  } catch (error2) {
38860
- logInstrumentationError4("Pi Coding Agent event", error2);
40210
+ logInstrumentationError5("Pi Coding Agent event", error2);
38861
40211
  }
38862
40212
  });
38863
40213
  piAgentEventSubscriptions.add(agent);
38864
40214
  } catch (error2) {
38865
- logInstrumentationError4("Pi Coding Agent event subscription", error2);
40215
+ logInstrumentationError5("Pi Coding Agent event subscription", error2);
38866
40216
  }
38867
40217
  }
38868
40218
  function makeInstrumentedStreamFunction(agent, originalStreamFunction, property) {
@@ -38912,7 +40262,7 @@ function wrapPiToolExecutors(tools) {
38912
40262
  });
38913
40263
  tool.execute = wrappedExecute;
38914
40264
  } catch (error2) {
38915
- logInstrumentationError4("Pi Coding Agent tool wrapping", error2);
40265
+ logInstrumentationError5("Pi Coding Agent tool wrapping", error2);
38916
40266
  }
38917
40267
  }
38918
40268
  }
@@ -38991,7 +40341,7 @@ function patchAssistantMessageStream(stream, promptState, llmState) {
38991
40341
  try {
38992
40342
  await iterator.return();
38993
40343
  } catch (cleanupError) {
38994
- logInstrumentationError4(
40344
+ logInstrumentationError5(
38995
40345
  "Pi Coding Agent stream cleanup",
38996
40346
  cleanupError
38997
40347
  );
@@ -39156,7 +40506,7 @@ function finishPiPromptRun(state, error2) {
39156
40506
  try {
39157
40507
  state.span.end();
39158
40508
  } catch (endError) {
39159
- logInstrumentationError4("Pi Coding Agent prompt end", endError);
40509
+ logInstrumentationError5("Pi Coding Agent prompt end", endError);
39160
40510
  }
39161
40511
  }
39162
40512
  }
@@ -39488,10 +40838,10 @@ function safeLog4(span, event) {
39488
40838
  try {
39489
40839
  span.log(event);
39490
40840
  } catch (error2) {
39491
- logInstrumentationError4("Pi Coding Agent span log", error2);
40841
+ logInstrumentationError5("Pi Coding Agent span log", error2);
39492
40842
  }
39493
40843
  }
39494
- function logInstrumentationError4(context2, error2) {
40844
+ function logInstrumentationError5(context2, error2) {
39495
40845
  debugLogger.debug(`${context2}:`, error2);
39496
40846
  }
39497
40847
 
@@ -39729,7 +41079,7 @@ function handleAgentStreamEvent(state, event) {
39729
41079
  finalizeModelSpan(state, event);
39730
41080
  break;
39731
41081
  case "beforeToolCallEvent":
39732
- startToolSpan2(state, event);
41082
+ startToolSpan3(state, event);
39733
41083
  break;
39734
41084
  case "afterToolCallEvent":
39735
41085
  finalizeToolSpan(state, event);
@@ -39754,7 +41104,7 @@ function handleAgentStreamEvent(state, event) {
39754
41104
  break;
39755
41105
  }
39756
41106
  } catch (error2) {
39757
- logInstrumentationError5("Strands Agent SDK event", error2);
41107
+ logInstrumentationError6("Strands Agent SDK event", error2);
39758
41108
  }
39759
41109
  }
39760
41110
  function handleMultiAgentStreamEvent(state, event, activeChildParents) {
@@ -39790,7 +41140,7 @@ function handleMultiAgentStreamEvent(state, event, activeChildParents) {
39790
41140
  break;
39791
41141
  }
39792
41142
  } catch (error2) {
39793
- logInstrumentationError5("Strands Agent SDK multi-agent event", error2);
41143
+ logInstrumentationError6("Strands Agent SDK multi-agent event", error2);
39794
41144
  }
39795
41145
  }
39796
41146
  function buildModelSpanInput(event, attachmentCache) {
@@ -39869,7 +41219,7 @@ function finalizeModelSpan(state, event) {
39869
41219
  });
39870
41220
  modelState.span.end();
39871
41221
  }
39872
- function startToolSpan2(state, event) {
41222
+ function startToolSpan3(state, event) {
39873
41223
  const toolUse = event.toolUse;
39874
41224
  const key = toolKey2(toolUse);
39875
41225
  if (state.activeTools.has(key)) {
@@ -40149,7 +41499,7 @@ function getModelConfig(model) {
40149
41499
  try {
40150
41500
  return model.getConfig();
40151
41501
  } catch (error2) {
40152
- logInstrumentationError5("Strands Agent SDK model config", error2);
41502
+ logInstrumentationError6("Strands Agent SDK model config", error2);
40153
41503
  return void 0;
40154
41504
  }
40155
41505
  }
@@ -40232,7 +41582,7 @@ function processStrandsInputAttachments(input, cache = createStrandsAttachmentCa
40232
41582
  try {
40233
41583
  return processStrandsInputNode(input, cache);
40234
41584
  } catch (error2) {
40235
- logInstrumentationError5("Strands Agent SDK input attachments", error2);
41585
+ logInstrumentationError6("Strands Agent SDK input attachments", error2);
40236
41586
  return input;
40237
41587
  }
40238
41588
  }
@@ -40452,10 +41802,10 @@ function safeLog5(span, event) {
40452
41802
  try {
40453
41803
  span.log(event);
40454
41804
  } catch (error2) {
40455
- logInstrumentationError5("Strands Agent SDK span log", error2);
41805
+ logInstrumentationError6("Strands Agent SDK span log", error2);
40456
41806
  }
40457
41807
  }
40458
- function logInstrumentationError5(context2, error2) {
41808
+ function logInstrumentationError6(context2, error2) {
40459
41809
  debugLogger.debug(`${context2}:`, error2);
40460
41810
  }
40461
41811
 
@@ -40858,10 +42208,10 @@ function observeAudioStream(value, observe, complete, cancel, span) {
40858
42208
  const getReader = value.getReader;
40859
42209
  value.getReader = function(...args) {
40860
42210
  const reader = Reflect.apply(getReader, this, args);
40861
- const read2 = reader.read;
42211
+ const read3 = reader.read;
40862
42212
  reader.read = function(...readArgs) {
40863
42213
  return Promise.resolve(
40864
- withCurrent(span, () => Reflect.apply(read2, this, readArgs))
42214
+ withCurrent(span, () => Reflect.apply(read3, this, readArgs))
40865
42215
  ).then(
40866
42216
  (result) => {
40867
42217
  if (result.value) safeObserve(result.value);
@@ -41355,14 +42705,14 @@ var CloudflareAIChatPlugin = class extends BasePlugin {
41355
42705
  const result = event.arguments[0];
41356
42706
  state = agent ? this.findResponseState(
41357
42707
  agent,
41358
- stringValue3(ownValue2(result, "requestId"))
42708
+ stringValue4(ownValue2(result, "requestId"))
41359
42709
  ) : void 0;
41360
42710
  if (!state) {
41361
42711
  return;
41362
42712
  }
41363
42713
  state.responseObserved = true;
41364
42714
  const output = serializeMessage(ownValue2(result, "message"));
41365
- const status = stringValue3(ownValue2(result, "status"));
42715
+ const status = stringValue4(ownValue2(result, "status"));
41366
42716
  const error2 = ownValue2(result, "error");
41367
42717
  const input = ownValue2(result, "continuation") === true ? state.input : serializeMessages(readProperty(agent, "messages"))?.filter(
41368
42718
  (message) => typeof output?.id !== "string" || message.id !== output.id
@@ -41409,7 +42759,7 @@ var CloudflareAIChatPlugin = class extends BasePlugin {
41409
42759
  }
41410
42760
  try {
41411
42761
  const agent = asObject(event.self);
41412
- const requestId = stringValue3(event.arguments[0]);
42762
+ const requestId = stringValue4(event.arguments[0]);
41413
42763
  const key = requestId ?? /* @__PURE__ */ Symbol("cloudflare-ai-chat-turn");
41414
42764
  const activeForAgent = agent ? this.getActiveTurns(agent) : void 0;
41415
42765
  const existing = activeForAgent?.get(key);
@@ -41578,7 +42928,7 @@ function ownValue2(value, key) {
41578
42928
  const descriptor = Object.getOwnPropertyDescriptor(object, key);
41579
42929
  return descriptor && "value" in descriptor ? descriptor.value : void 0;
41580
42930
  }
41581
- function stringValue3(value) {
42931
+ function stringValue4(value) {
41582
42932
  return typeof value === "string" ? value : void 0;
41583
42933
  }
41584
42934
  function serializeMessages(value) {
@@ -41696,7 +43046,7 @@ var CloudflareAgentsPlugin = class extends BasePlugin {
41696
43046
  );
41697
43047
  spans.set(event, span);
41698
43048
  } catch (error2) {
41699
- logInstrumentationError6("start", error2);
43049
+ logInstrumentationError7("start", error2);
41700
43050
  }
41701
43051
  },
41702
43052
  asyncEnd: (event) => {
@@ -41716,7 +43066,7 @@ var CloudflareAgentsPlugin = class extends BasePlugin {
41716
43066
  }
41717
43067
  }
41718
43068
  } catch (error2) {
41719
- logInstrumentationError6("completion", error2);
43069
+ logInstrumentationError7("completion", error2);
41720
43070
  } finally {
41721
43071
  safelyEndSpan(span);
41722
43072
  }
@@ -41730,7 +43080,7 @@ var CloudflareAgentsPlugin = class extends BasePlugin {
41730
43080
  try {
41731
43081
  span.log({ error: event.error });
41732
43082
  } catch (error2) {
41733
- logInstrumentationError6("rejection", error2);
43083
+ logInstrumentationError7("rejection", error2);
41734
43084
  } finally {
41735
43085
  safelyEndSpan(span);
41736
43086
  }
@@ -41760,10 +43110,10 @@ function safelyEndSpan(span) {
41760
43110
  try {
41761
43111
  span.end();
41762
43112
  } catch (error2) {
41763
- logInstrumentationError6("span end", error2);
43113
+ logInstrumentationError7("span end", error2);
41764
43114
  }
41765
43115
  }
41766
- function logInstrumentationError6(operation, error2) {
43116
+ function logInstrumentationError7(operation, error2) {
41767
43117
  debugLogger.error(
41768
43118
  `Failed to process Cloudflare Agents ${operation} instrumentation:`,
41769
43119
  error2
@@ -41788,6 +43138,7 @@ var BraintrustPlugin = class extends BasePlugin {
41788
43138
  openRouterPlugin = null;
41789
43139
  openRouterAgentPlugin = null;
41790
43140
  mistralPlugin = null;
43141
+ langGraphSDKPlugin = null;
41791
43142
  ollamaPlugin = null;
41792
43143
  googleADKPlugin = null;
41793
43144
  coherePlugin = null;
@@ -41868,6 +43219,10 @@ var BraintrustPlugin = class extends BasePlugin {
41868
43219
  this.mistralPlugin = new MistralPlugin();
41869
43220
  this.mistralPlugin.enable();
41870
43221
  }
43222
+ if (integrations.langgraphSDK !== false) {
43223
+ this.langGraphSDKPlugin = new LangGraphSDKPlugin();
43224
+ this.langGraphSDKPlugin.enable();
43225
+ }
41871
43226
  if (integrations.ollama !== false) {
41872
43227
  this.ollamaPlugin = new OllamaPlugin();
41873
43228
  this.ollamaPlugin.enable();
@@ -41996,6 +43351,10 @@ var BraintrustPlugin = class extends BasePlugin {
41996
43351
  this.mistralPlugin.disable();
41997
43352
  this.mistralPlugin = null;
41998
43353
  }
43354
+ if (this.langGraphSDKPlugin) {
43355
+ this.langGraphSDKPlugin.disable();
43356
+ this.langGraphSDKPlugin = null;
43357
+ }
41999
43358
  if (this.ollamaPlugin) {
42000
43359
  this.ollamaPlugin.disable();
42001
43360
  this.ollamaPlugin = null;
@@ -42137,6 +43496,9 @@ var envIntegrationAliases = {
42137
43496
  "langchain-js": "langchain",
42138
43497
  "@langchain": "langchain",
42139
43498
  langgraph: "langgraph",
43499
+ langgraphsdk: "langgraphSDK",
43500
+ "langgraph-sdk": "langgraphSDK",
43501
+ "@langchain/langgraph-sdk": "langgraphSDK",
42140
43502
  langsmith: "langsmith",
42141
43503
  voyage: "voyageai",
42142
43504
  "voyage-ai": "voyageai",
@@ -42177,6 +43539,7 @@ function getDefaultInstrumentationIntegrations() {
42177
43539
  gitHubCopilot: true,
42178
43540
  langchain: true,
42179
43541
  langgraph: true,
43542
+ langgraphSDK: true,
42180
43543
  langsmith: true,
42181
43544
  voyageai: true,
42182
43545
  elevenlabs: true,
@@ -42873,8 +44236,8 @@ var import_node_url = require("node:url");
42873
44236
  // src/auto-instrumentations/configs/ai-sdk.ts
42874
44237
  var aiSDKConfigs = [
42875
44238
  // HarnessAgent turn methods are published only from the package's ESM
42876
- // `./agent` entrypoint. The compiled class expression is anonymous, so match
42877
- // the first async method with each public name instead of a class name.
44239
+ // `./agent` entrypoint. Target the class binding so similarly named getters
44240
+ // on stream result classes are not mistaken for agent turn methods.
42878
44241
  ...[
42879
44242
  ["createSession", harnessAgentChannels.createSession.channelName],
42880
44243
  ["generate", harnessAgentChannels.generate.channelName],
@@ -42889,6 +44252,7 @@ var aiSDKConfigs = [
42889
44252
  filePath: "dist/agent/index.js"
42890
44253
  },
42891
44254
  functionQuery: {
44255
+ className: "HarnessAgent",
42892
44256
  methodName,
42893
44257
  kind: "Async",
42894
44258
  index: 0
@@ -43294,9 +44658,9 @@ var aiSDKConfigs = [
43294
44658
  // src/auto-instrumentations/configs/anthropic.ts
43295
44659
  var anthropicConfigs = [
43296
44660
  // Each logical target is listed for both published module formats:
43297
- // `.mjs` covers ESM imports, while `.js` covers CJS requires. The Bedrock
43298
- // SDK delegates CJS `messages.create` calls through these Anthropic SDK
43299
- // `.js` resource files.
44661
+ // `.mjs` covers ESM imports, while `.js` covers CJS requires. Both
44662
+ // @anthropic-ai/bedrock-sdk and @anthropic-ai/vertex-sdk instantiate these
44663
+ // shared Anthropic resources, so they use the same targets and channels.
43300
44664
  // Messages API - create in older SDK layouts (supports streaming via stream=true parameter)
43301
44665
  {
43302
44666
  channelName: anthropicChannels.messagesCreate.channelName,
@@ -44467,6 +45831,21 @@ var googleGenAIConfigs = [
44467
45831
  kind: "Async"
44468
45832
  }
44469
45833
  },
45834
+ // The SDK's embedding response converter drops usageMetadata. Observe the
45835
+ // parsed HTTP response before conversion; the plugin scopes this to embeddings.
45836
+ {
45837
+ channelName: googleGenAIChannels.httpResponseJson.channelName,
45838
+ module: {
45839
+ name: "@google/genai",
45840
+ versionRange: ">=1.0.0",
45841
+ filePath: "dist/node/index.mjs"
45842
+ },
45843
+ functionQuery: {
45844
+ className: "HttpResponse",
45845
+ methodName: "json",
45846
+ kind: "Async"
45847
+ }
45848
+ },
44470
45849
  // BaseInteractions.create - Interactions API entry point
44471
45850
  {
44472
45851
  channelName: googleGenAIChannels.interactionsCreate.channelName,
@@ -45174,6 +46553,26 @@ var mistralConfigs = [
45174
46553
  }
45175
46554
  ];
45176
46555
 
46556
+ // src/auto-instrumentations/configs/langgraph-sdk.ts
46557
+ var langGraphSDKConfigs = [
46558
+ "js",
46559
+ "cjs"
46560
+ ].flatMap(
46561
+ (extension) => ["wait", "stream"].map((methodName) => ({
46562
+ channelName: langGraphSDKChannels[methodName].channelName,
46563
+ module: {
46564
+ name: "@langchain/langgraph-sdk",
46565
+ versionRange: ">=1.9.25 <2.0.0",
46566
+ filePath: `dist/client/runs/index.${extension}`
46567
+ },
46568
+ functionQuery: {
46569
+ className: "RunsClient",
46570
+ methodName,
46571
+ kind: methodName === "stream" ? "Sync" : "Async"
46572
+ }
46573
+ }))
46574
+ );
46575
+
45177
46576
  // src/auto-instrumentations/configs/ollama.ts
45178
46577
  var methods = [
45179
46578
  ["chat", ollamaChannels.chat.channelName],
@@ -45736,6 +47135,7 @@ var defaultInstrumentationConfigGroups = [
45736
47135
  configs: openRouterAgentConfigs
45737
47136
  },
45738
47137
  { integrations: ["mistral"], configs: mistralConfigs },
47138
+ { integrations: ["langgraphSDK"], configs: langGraphSDKConfigs },
45739
47139
  { integrations: ["ollama"], configs: ollamaConfigs },
45740
47140
  { integrations: ["googleADK"], configs: googleADKConfigs },
45741
47141
  { integrations: ["cohere"], configs: cohereConfigs },
@@ -48846,9 +50246,10 @@ async function initFile({
48846
50246
  outFile: bundleFile,
48847
50247
  tsconfig,
48848
50248
  plugins: [],
48849
- externalPackages
50249
+ externalPackages,
50250
+ markKnownPackagesExternal: false
48850
50251
  }),
48851
- external: ["fsevents", "chokidar"],
50252
+ external: ["fsevents", "chokidar", ...externalPackages ?? []],
48852
50253
  write: true,
48853
50254
  minify: true,
48854
50255
  sourcemap: true
@@ -49156,12 +50557,13 @@ function buildOpts({
49156
50557
  outFile,
49157
50558
  tsconfig,
49158
50559
  plugins: argPlugins,
49159
- externalPackages
50560
+ externalPackages,
50561
+ markKnownPackagesExternal = true
49160
50562
  }) {
49161
50563
  const plugins = [
49162
50564
  braintrustEsbuildPlugin(),
49163
50565
  nativeNodeModulesPlugin,
49164
- createMarkKnownPackagesExternalPlugin(externalPackages),
50566
+ ...markKnownPackagesExternal ? [createMarkKnownPackagesExternalPlugin(externalPackages)] : [],
49165
50567
  ...(argPlugins || []).map((fn) => fn(fileName))
49166
50568
  ];
49167
50569
  return {
@@ -49206,13 +50608,13 @@ async function initializeHandles({
49206
50608
  );
49207
50609
  process.exit(0);
49208
50610
  }
49209
- const tmpDir = import_node_path7.default.join(import_node_os.default.tmpdir(), `btevals-${(0, import_uuid3.v4)().slice(0, 8)}`);
50611
+ const tmpDir = import_node_path7.default.join(import_node_os.default.tmpdir(), `btevals-${(0, import_uuid4.v4)().slice(0, 8)}`);
49210
50612
  const initPromises = [];
49211
50613
  for (const file of Object.keys(files)) {
49212
50614
  const baseName = `${import_node_path7.default.basename(
49213
50615
  file,
49214
50616
  import_node_path7.default.extname(file)
49215
- )}-${(0, import_uuid3.v4)().slice(0, 8)}`;
50617
+ )}-${(0, import_uuid4.v4)().slice(0, 8)}`;
49216
50618
  const outFile = import_node_path7.default.join(tmpDir, `${baseName}.${OUT_EXT}`);
49217
50619
  const bundleFile = import_node_path7.default.join(tmpDir, `${baseName}.bundle.js`);
49218
50620
  initPromises.push(