braintrust 3.5.0 → 3.6.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 (41) hide show
  1. package/dev/dist/index.d.mts +4 -2
  2. package/dev/dist/index.d.ts +4 -2
  3. package/dev/dist/index.js +1353 -211
  4. package/dev/dist/index.mjs +1170 -28
  5. package/dist/auto-instrumentations/bundler/esbuild.cjs +81 -0
  6. package/dist/auto-instrumentations/bundler/esbuild.mjs +2 -2
  7. package/dist/auto-instrumentations/bundler/rollup.cjs +81 -0
  8. package/dist/auto-instrumentations/bundler/rollup.mjs +2 -2
  9. package/dist/auto-instrumentations/bundler/vite.cjs +81 -0
  10. package/dist/auto-instrumentations/bundler/vite.mjs +2 -2
  11. package/dist/auto-instrumentations/bundler/webpack.cjs +81 -0
  12. package/dist/auto-instrumentations/bundler/webpack.mjs +2 -2
  13. package/dist/auto-instrumentations/{chunk-DQTPSXJB.mjs → chunk-F7WAXFNM.mjs} +82 -1
  14. package/dist/auto-instrumentations/{chunk-F3TJZ3Z2.mjs → chunk-WOUC73KB.mjs} +3 -1
  15. package/dist/auto-instrumentations/hook.mjs +139 -49
  16. package/dist/auto-instrumentations/index.cjs +82 -0
  17. package/dist/auto-instrumentations/index.d.mts +3 -1
  18. package/dist/auto-instrumentations/index.d.ts +3 -1
  19. package/dist/auto-instrumentations/index.mjs +3 -1
  20. package/dist/browser.d.mts +17 -4
  21. package/dist/browser.d.ts +17 -4
  22. package/dist/browser.js +1479 -232
  23. package/dist/browser.mjs +1479 -232
  24. package/dist/cli.js +1162 -20
  25. package/dist/edge-light.d.mts +1 -1
  26. package/dist/edge-light.d.ts +1 -1
  27. package/dist/edge-light.js +1412 -222
  28. package/dist/edge-light.mjs +1412 -222
  29. package/dist/index.d.mts +30 -17
  30. package/dist/index.d.ts +30 -17
  31. package/dist/index.js +1763 -514
  32. package/dist/index.mjs +1458 -209
  33. package/dist/instrumentation/index.d.mts +3 -0
  34. package/dist/instrumentation/index.d.ts +3 -0
  35. package/dist/instrumentation/index.js +1102 -19
  36. package/dist/instrumentation/index.mjs +1102 -19
  37. package/dist/workerd.d.mts +1 -1
  38. package/dist/workerd.d.ts +1 -1
  39. package/dist/workerd.js +1412 -222
  40. package/dist/workerd.mjs +1412 -222
  41. package/package.json +1 -1
package/dev/dist/index.js CHANGED
@@ -2,6 +2,64 @@
2
2
  var _nodeasync_hooks = require('node:async_hooks');
3
3
  var _nodediagnostics_channel = require('node:diagnostics_channel'); var diagnostics_channel = _interopRequireWildcard(_nodediagnostics_channel);
4
4
  var _nodepath = require('node:path'); var path = _interopRequireWildcard(_nodepath);
5
+
6
+ // src/auto-instrumentations/patch-tracing-channel.ts
7
+ function patchTracingChannel(tracingChannelFn) {
8
+ const dummyChannel = tracingChannelFn("__braintrust_probe__");
9
+ const TracingChannel = _optionalChain([dummyChannel, 'optionalAccess', _2 => _2.constructor]);
10
+ if (!_optionalChain([TracingChannel, 'optionalAccess', _3 => _3.prototype])) {
11
+ return;
12
+ }
13
+ if (!Object.getOwnPropertyDescriptor(TracingChannel.prototype, "hasSubscribers")) {
14
+ Object.defineProperty(TracingChannel.prototype, "hasSubscribers", {
15
+ configurable: true,
16
+ enumerable: false,
17
+ get() {
18
+ return Boolean(
19
+ _optionalChain([this, 'access', _4 => _4.start, 'optionalAccess', _5 => _5.hasSubscribers]) || _optionalChain([this, 'access', _6 => _6.end, 'optionalAccess', _7 => _7.hasSubscribers]) || _optionalChain([this, 'access', _8 => _8.asyncStart, 'optionalAccess', _9 => _9.hasSubscribers]) || _optionalChain([this, 'access', _10 => _10.asyncEnd, 'optionalAccess', _11 => _11.hasSubscribers]) || _optionalChain([this, 'access', _12 => _12.error, 'optionalAccess', _13 => _13.hasSubscribers])
20
+ );
21
+ }
22
+ });
23
+ }
24
+ if (TracingChannel.prototype.tracePromise) {
25
+ TracingChannel.prototype.tracePromise = function(fn, context = {}, thisArg, ...args) {
26
+ const { start, end, asyncStart, asyncEnd, error } = this;
27
+ function reject2(err) {
28
+ context.error = err;
29
+ _optionalChain([error, 'optionalAccess', _14 => _14.publish, 'call', _15 => _15(context)]);
30
+ _optionalChain([asyncStart, 'optionalAccess', _16 => _16.publish, 'call', _17 => _17(context)]);
31
+ _optionalChain([asyncEnd, 'optionalAccess', _18 => _18.publish, 'call', _19 => _19(context)]);
32
+ return Promise.reject(err);
33
+ }
34
+ function resolve(result) {
35
+ context.result = result;
36
+ _optionalChain([asyncStart, 'optionalAccess', _20 => _20.publish, 'call', _21 => _21(context)]);
37
+ _optionalChain([asyncEnd, 'optionalAccess', _22 => _22.publish, 'call', _23 => _23(context)]);
38
+ return result;
39
+ }
40
+ return start.runStores(context, () => {
41
+ try {
42
+ const result = Reflect.apply(fn, thisArg, args);
43
+ _optionalChain([end, 'optionalAccess', _24 => _24.publish, 'call', _25 => _25(context)]);
44
+ if (result && (typeof result === "object" || typeof result === "function") && typeof result.then === "function") {
45
+ return result.then(resolve, reject2);
46
+ }
47
+ context.result = result;
48
+ _optionalChain([asyncStart, 'optionalAccess', _26 => _26.publish, 'call', _27 => _27(context)]);
49
+ _optionalChain([asyncEnd, 'optionalAccess', _28 => _28.publish, 'call', _29 => _29(context)]);
50
+ return result;
51
+ } catch (err) {
52
+ context.error = err;
53
+ _optionalChain([error, 'optionalAccess', _30 => _30.publish, 'call', _31 => _31(context)]);
54
+ _optionalChain([end, 'optionalAccess', _32 => _32.publish, 'call', _33 => _33(context)]);
55
+ throw err;
56
+ }
57
+ });
58
+ };
59
+ }
60
+ }
61
+
62
+ // src/node/config.ts
5
63
  var _promises = require('node:fs/promises'); var fs = _interopRequireWildcard(_promises);
6
64
  var _nodeos = require('node:os'); var os = _interopRequireWildcard(_nodeos);
7
65
  var _nodefs = require('node:fs'); var fsSync = _interopRequireWildcard(_nodefs);
@@ -157,8 +215,8 @@ function setDebugLogStateResolver(resolver) {
157
215
  debugLogStateResolver = resolver;
158
216
  }
159
217
  function resolveDebugLogLevel(state) {
160
- const stateLevel = _optionalChain([state, 'optionalAccess', _2 => _2.getDebugLogLevel, 'optionalCall', _3 => _3()]);
161
- const hasStateOverride = _nullishCoalesce(_optionalChain([state, 'optionalAccess', _4 => _4.hasDebugLogLevelOverride, 'optionalCall', _5 => _5()]), () => ( false));
218
+ const stateLevel = _optionalChain([state, 'optionalAccess', _34 => _34.getDebugLogLevel, 'optionalCall', _35 => _35()]);
219
+ const hasStateOverride = _nullishCoalesce(_optionalChain([state, 'optionalAccess', _36 => _36.hasDebugLogLevelOverride, 'optionalCall', _37 => _37()]), () => ( false));
162
220
  if (hasStateOverride) {
163
221
  return stateLevel;
164
222
  }
@@ -187,7 +245,7 @@ function emit(method, state, args) {
187
245
  }
188
246
  }
189
247
  function createDebugLogger(state) {
190
- const resolveState = () => _nullishCoalesce(state, () => ( _optionalChain([debugLogStateResolver, 'optionalCall', _6 => _6()])));
248
+ const resolveState = () => _nullishCoalesce(state, () => ( _optionalChain([debugLogStateResolver, 'optionalCall', _38 => _38()])));
191
249
  return {
192
250
  info(...args) {
193
251
  emit("info", resolveState(), args);
@@ -232,7 +290,7 @@ async function getBaseBranch(remote = void 0) {
232
290
  if (git === null) {
233
291
  throw new Error("Not in a git repo");
234
292
  }
235
- const remoteName = await _asyncNullishCoalesce(remote, async () => ( await _asyncOptionalChain([(await git.getRemotes()), 'access', async _7 => _7[0], 'optionalAccess', async _8 => _8.name])));
293
+ const remoteName = await _asyncNullishCoalesce(remote, async () => ( await _asyncOptionalChain([(await git.getRemotes()), 'access', async _39 => _39[0], 'optionalAccess', async _40 => _40.name])));
236
294
  if (!remoteName) {
237
295
  throw new Error("No remote found");
238
296
  }
@@ -325,7 +383,7 @@ async function getRepoInfo(settings) {
325
383
  return repo;
326
384
  }
327
385
  let sanitized = {};
328
- _optionalChain([settings, 'access', _9 => _9.fields, 'optionalAccess', _10 => _10.forEach, 'call', _11 => _11((field) => {
386
+ _optionalChain([settings, 'access', _41 => _41.fields, 'optionalAccess', _42 => _42.forEach, 'call', _43 => _43((field) => {
329
387
  sanitized = { ...sanitized, [field]: repo[field] };
330
388
  })]);
331
389
  return sanitized;
@@ -411,9 +469,9 @@ function getCallerLocation() {
411
469
  const entries = getStackTrace();
412
470
  for (const frame of entries) {
413
471
  if (thisDir === void 0) {
414
- thisDir = _optionalChain([isomorph_default, 'access', _12 => _12.pathDirname, 'optionalCall', _13 => _13(frame.fileName)]);
472
+ thisDir = _optionalChain([isomorph_default, 'access', _44 => _44.pathDirname, 'optionalCall', _45 => _45(frame.fileName)]);
415
473
  }
416
- if (_optionalChain([isomorph_default, 'access', _14 => _14.pathDirname, 'optionalCall', _15 => _15(frame.fileName)]) !== thisDir) {
474
+ if (_optionalChain([isomorph_default, 'access', _46 => _46.pathDirname, 'optionalCall', _47 => _47(frame.fileName)]) !== thisDir) {
417
475
  return {
418
476
  caller_functionname: frame.functionName,
419
477
  caller_filename: frame.fileName,
@@ -660,7 +718,7 @@ var SpanComponentsV1 = class _SpanComponentsV1 {
660
718
  return {
661
719
  objectType: this.objectType,
662
720
  objectId: this.objectId,
663
- rowIds: _optionalChain([this, 'access', _16 => _16.rowIds, 'optionalAccess', _17 => _17.toObject, 'call', _18 => _18()])
721
+ rowIds: _optionalChain([this, 'access', _48 => _48.rowIds, 'optionalAccess', _49 => _49.toObject, 'call', _50 => _50()])
664
722
  };
665
723
  }
666
724
  };
@@ -874,7 +932,7 @@ var SpanComponentsV2 = class _SpanComponentsV2 {
874
932
  objectType: this.objectType,
875
933
  objectId: this.objectId,
876
934
  computeObjectMetadataArgs: this.computeObjectMetadataArgs,
877
- rowIds: _optionalChain([this, 'access', _19 => _19.rowIds, 'optionalAccess', _20 => _20.toObject, 'call', _21 => _21()])
935
+ rowIds: _optionalChain([this, 'access', _51 => _51.rowIds, 'optionalAccess', _52 => _52.toObject, 'call', _53 => _53()])
878
936
  };
879
937
  }
880
938
  };
@@ -1414,20 +1472,20 @@ function slugify(text, options) {
1414
1472
  \u00FF: "y"
1415
1473
  };
1416
1474
  const replacement = "-";
1417
- const trim = _optionalChain([options, 'optionalAccess', _22 => _22.trim]) !== false;
1475
+ const trim = _optionalChain([options, 'optionalAccess', _54 => _54.trim]) !== false;
1418
1476
  let slug = text.normalize().split("").reduce((result, ch) => {
1419
1477
  const mapped = charMap[ch] || ch;
1420
1478
  const appendChar = mapped === replacement ? " " : mapped;
1421
1479
  return result + appendChar.replace(/[^\w\s$*_+~.()'"!\-:@]+/g, "");
1422
1480
  }, "");
1423
- if (_optionalChain([options, 'optionalAccess', _23 => _23.strict])) {
1481
+ if (_optionalChain([options, 'optionalAccess', _55 => _55.strict])) {
1424
1482
  slug = slug.replace(/[^A-Za-z0-9\s]/g, "");
1425
1483
  }
1426
1484
  if (trim) {
1427
1485
  slug = slug.trim();
1428
1486
  }
1429
1487
  slug = slug.replace(/\s+/g, replacement);
1430
- if (_optionalChain([options, 'optionalAccess', _24 => _24.lower])) {
1488
+ if (_optionalChain([options, 'optionalAccess', _56 => _56.lower])) {
1431
1489
  slug = slug.toLowerCase();
1432
1490
  }
1433
1491
  return slug;
@@ -3566,8 +3624,8 @@ var mustachePlugin = {
3566
3624
  defaultOptions: { strict: true, escape: jsonEscape },
3567
3625
  createRenderer() {
3568
3626
  const opts = _nullishCoalesce(this.defaultOptions, () => ( {}));
3569
- const escapeFn = _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _25 => _25.escape]), () => ( jsonEscape));
3570
- const strictDefault = typeof _optionalChain([opts, 'optionalAccess', _26 => _26.strict]) === "boolean" ? opts.strict : true;
3627
+ const escapeFn = _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _57 => _57.escape]), () => ( jsonEscape));
3628
+ const strictDefault = typeof _optionalChain([opts, 'optionalAccess', _58 => _58.strict]) === "boolean" ? opts.strict : true;
3571
3629
  return {
3572
3630
  render(template, variables, escape, strict) {
3573
3631
  const esc = _nullishCoalesce(escape, () => ( escapeFn));
@@ -3601,7 +3659,7 @@ var TemplatePluginRegistry = (_class5 = class {constructor() { _class5.prototype
3601
3659
  return Array.from(this.plugins.keys());
3602
3660
  }
3603
3661
  get(name) {
3604
- return _optionalChain([this, 'access', _27 => _27.plugins, 'access', _28 => _28.get, 'call', _29 => _29(name), 'optionalAccess', _30 => _30.renderer]);
3662
+ return _optionalChain([this, 'access', _59 => _59.plugins, 'access', _60 => _60.get, 'call', _61 => _61(name), 'optionalAccess', _62 => _62.renderer]);
3605
3663
  }
3606
3664
  isRegistered(name) {
3607
3665
  return this.plugins.has(name);
@@ -4235,7 +4293,7 @@ var SpanCache = (_class6 = class {
4235
4293
  // Small in-memory index tracking which rootSpanIds have data
4236
4294
  __init14() {this.rootSpanIndex = /* @__PURE__ */ new Set()}
4237
4295
  constructor(options) {;_class6.prototype.__init8.call(this);_class6.prototype.__init9.call(this);_class6.prototype.__init10.call(this);_class6.prototype.__init11.call(this);_class6.prototype.__init12.call(this);_class6.prototype.__init13.call(this);_class6.prototype.__init14.call(this);_class6.prototype.__init15.call(this);_class6.prototype.__init16.call(this);_class6.prototype.__init17.call(this);
4238
- this._explicitlyDisabled = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _31 => _31.disabled]), () => ( false));
4296
+ this._explicitlyDisabled = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _63 => _63.disabled]), () => ( false));
4239
4297
  }
4240
4298
  /**
4241
4299
  * Disable the cache at runtime. This is called automatically when
@@ -4506,6 +4564,9 @@ var BRAINTRUST_ATTACHMENT = BraintrustAttachmentReference.shape.type.value;
4506
4564
  var EXTERNAL_ATTACHMENT = ExternalAttachmentReference.shape.type.value;
4507
4565
  var LOGS3_OVERFLOW_REFERENCE_TYPE = "logs3_overflow";
4508
4566
  var BRAINTRUST_PARAMS = Object.keys(BraintrustModelParams.shape);
4567
+ var RESET_CONTEXT_MANAGER_STATE = Symbol.for(
4568
+ "braintrust.resetContextManagerState"
4569
+ );
4509
4570
  var DEFAULT_MAX_REQUEST_SIZE = 6 * 1024 * 1024;
4510
4571
  var parametersRowSchema = _v3.z.object({
4511
4572
  id: _v3.z.string().uuid(),
@@ -4568,13 +4629,18 @@ function applyMaskingToField(maskingFunction, data, fieldName) {
4568
4629
  return `ERROR: Failed to mask field '${fieldName}' - ${errorType}`;
4569
4630
  }
4570
4631
  }
4632
+ var BRAINTRUST_CURRENT_SPAN_STORE = Symbol.for(
4633
+ "braintrust.currentSpanStore"
4634
+ );
4571
4635
  var ContextManager = class {
4572
4636
  };
4573
4637
  var BraintrustContextManager = class extends ContextManager {
4574
4638
 
4639
+
4575
4640
  constructor() {
4576
4641
  super();
4577
4642
  this._currentSpan = isomorph_default.newAsyncLocalStorage();
4643
+ this[BRAINTRUST_CURRENT_SPAN_STORE] = this._currentSpan;
4578
4644
  }
4579
4645
  getParentSpanIds() {
4580
4646
  const currentSpan2 = this._currentSpan.getStore();
@@ -4625,7 +4691,7 @@ var NoopSpan = (_class7 = class {
4625
4691
  return this;
4626
4692
  }
4627
4693
  end(args) {
4628
- return _nullishCoalesce(_optionalChain([args, 'optionalAccess', _32 => _32.endTime]), () => ( getCurrentUnixTimestamp()));
4694
+ return _nullishCoalesce(_optionalChain([args, 'optionalAccess', _64 => _64.endTime]), () => ( getCurrentUnixTimestamp()));
4629
4695
  }
4630
4696
  async export() {
4631
4697
  return "";
@@ -4781,6 +4847,9 @@ var BraintrustState = (_class8 = class _BraintrustState {
4781
4847
  resetIdGenState() {
4782
4848
  this._idGenerator = null;
4783
4849
  }
4850
+ [RESET_CONTEXT_MANAGER_STATE]() {
4851
+ this._contextManager = null;
4852
+ }
4784
4853
  get idGenerator() {
4785
4854
  if (this._idGenerator === null) {
4786
4855
  this._idGenerator = getIdGenerator();
@@ -4887,8 +4956,8 @@ var BraintrustState = (_class8 = class _BraintrustState {
4887
4956
  setFetch(fetch2) {
4888
4957
  this.loginParams.fetch = fetch2;
4889
4958
  this.fetch = fetch2;
4890
- _optionalChain([this, 'access', _33 => _33._apiConn, 'optionalAccess', _34 => _34.setFetch, 'call', _35 => _35(fetch2)]);
4891
- _optionalChain([this, 'access', _36 => _36._appConn, 'optionalAccess', _37 => _37.setFetch, 'call', _38 => _38(fetch2)]);
4959
+ _optionalChain([this, 'access', _65 => _65._apiConn, 'optionalAccess', _66 => _66.setFetch, 'call', _67 => _67(fetch2)]);
4960
+ _optionalChain([this, 'access', _68 => _68._appConn, 'optionalAccess', _69 => _69.setFetch, 'call', _70 => _70(fetch2)]);
4892
4961
  }
4893
4962
  setMaskingFunction(maskingFunction) {
4894
4963
  this.bgLogger().setMaskingFunction(maskingFunction);
@@ -5590,8 +5659,8 @@ function _getOrgName(orgName) {
5590
5659
  return orgName || isomorph_default.getEnv("BRAINTRUST_ORG_NAME") || void 0;
5591
5660
  }
5592
5661
  function _getLinkBaseUrl(state, linkArgs) {
5593
- const appUrl = _getAppUrl(state.appUrl || _optionalChain([linkArgs, 'optionalAccess', _39 => _39.app_url]));
5594
- const orgName = _getOrgName(state.orgName || _optionalChain([linkArgs, 'optionalAccess', _40 => _40.org_name]));
5662
+ const appUrl = _getAppUrl(state.appUrl || _optionalChain([linkArgs, 'optionalAccess', _71 => _71.app_url]));
5663
+ const orgName = _getOrgName(state.orgName || _optionalChain([linkArgs, 'optionalAccess', _72 => _72.org_name]));
5595
5664
  if (!orgName) {
5596
5665
  return null;
5597
5666
  }
@@ -5601,9 +5670,9 @@ async function permalink(slug, opts) {
5601
5670
  if (slug === "") {
5602
5671
  return NOOP_SPAN_PERMALINK;
5603
5672
  }
5604
- const state = _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _41 => _41.state]), () => ( _globalState));
5673
+ const state = _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _73 => _73.state]), () => ( _globalState));
5605
5674
  const getOrgName = async () => {
5606
- if (_optionalChain([opts, 'optionalAccess', _42 => _42.orgName])) {
5675
+ if (_optionalChain([opts, 'optionalAccess', _74 => _74.orgName])) {
5607
5676
  return opts.orgName;
5608
5677
  }
5609
5678
  await state.login({});
@@ -5613,7 +5682,7 @@ async function permalink(slug, opts) {
5613
5682
  return state.orgName;
5614
5683
  };
5615
5684
  const getAppUrl = async () => {
5616
- if (_optionalChain([opts, 'optionalAccess', _43 => _43.appUrl])) {
5685
+ if (_optionalChain([opts, 'optionalAccess', _75 => _75.appUrl])) {
5617
5686
  return opts.appUrl;
5618
5687
  }
5619
5688
  await state.login({});
@@ -5748,7 +5817,7 @@ var Logger = (_class9 = class {
5748
5817
  * @returns The `id` of the logged event.
5749
5818
  */
5750
5819
  log(event, options) {
5751
- if (this.calledStartSpan && !_optionalChain([options, 'optionalAccess', _44 => _44.allowConcurrentWithSpans])) {
5820
+ if (this.calledStartSpan && !_optionalChain([options, 'optionalAccess', _76 => _76.allowConcurrentWithSpans])) {
5752
5821
  throw new Error(
5753
5822
  "Cannot run toplevel `log` method while using spans. To log to the span, call `logger.traced` and then log with `span.log`"
5754
5823
  );
@@ -5816,12 +5885,12 @@ var Logger = (_class9 = class {
5816
5885
  state: this.state,
5817
5886
  ...startSpanParentArgs({
5818
5887
  state: this.state,
5819
- parent: _optionalChain([args, 'optionalAccess', _45 => _45.parent]),
5888
+ parent: _optionalChain([args, 'optionalAccess', _77 => _77.parent]),
5820
5889
  parentObjectType: this.parentObjectType(),
5821
5890
  parentObjectId: this.lazyId,
5822
5891
  parentComputeObjectMetadataArgs: this.computeMetadataArgs,
5823
- parentSpanIds: _optionalChain([args, 'optionalAccess', _46 => _46.parentSpanIds]),
5824
- propagatedEvent: _optionalChain([args, 'optionalAccess', _47 => _47.propagatedEvent])
5892
+ parentSpanIds: _optionalChain([args, 'optionalAccess', _78 => _78.parentSpanIds]),
5893
+ propagatedEvent: _optionalChain([args, 'optionalAccess', _79 => _79.propagatedEvent])
5825
5894
  }),
5826
5895
  defaultRootType: "task" /* TASK */
5827
5896
  });
@@ -6156,7 +6225,7 @@ var HTTPBackgroundLogger = (_class10 = class _HTTPBackgroundLogger {
6156
6225
  this.queue.clear();
6157
6226
  return;
6158
6227
  }
6159
- const batchSize = _nullishCoalesce(_optionalChain([args, 'optionalAccess', _48 => _48.batchSize]), () => ( this.defaultBatchSize));
6228
+ const batchSize = _nullishCoalesce(_optionalChain([args, 'optionalAccess', _80 => _80.batchSize]), () => ( this.defaultBatchSize));
6160
6229
  const wrappedItems = this.queue.drain();
6161
6230
  if (wrappedItems.length === 0) {
6162
6231
  return;
@@ -6470,10 +6539,10 @@ Error: ${errorText}`;
6470
6539
  } catch (err) {
6471
6540
  if (err instanceof AggregateError) {
6472
6541
  for (const e of err.errors) {
6473
- _optionalChain([this, 'access', _49 => _49.onFlushError, 'optionalCall', _50 => _50(e)]);
6542
+ _optionalChain([this, 'access', _81 => _81.onFlushError, 'optionalCall', _82 => _82(e)]);
6474
6543
  }
6475
6544
  } else {
6476
- _optionalChain([this, 'access', _51 => _51.onFlushError, 'optionalCall', _52 => _52(err)]);
6545
+ _optionalChain([this, 'access', _83 => _83.onFlushError, 'optionalCall', _84 => _84(err)]);
6477
6546
  }
6478
6547
  this.activeFlushError = err;
6479
6548
  } finally {
@@ -6900,24 +6969,24 @@ async function loginToState(options = {}) {
6900
6969
  return state;
6901
6970
  }
6902
6971
  function currentExperiment(options) {
6903
- const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _53 => _53.state]), () => ( _globalState));
6972
+ const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _85 => _85.state]), () => ( _globalState));
6904
6973
  return state.currentExperiment;
6905
6974
  }
6906
6975
  function currentLogger(options) {
6907
- const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _54 => _54.state]), () => ( _globalState));
6908
- return castLogger(state.currentLogger, _optionalChain([options, 'optionalAccess', _55 => _55.asyncFlush]));
6976
+ const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _86 => _86.state]), () => ( _globalState));
6977
+ return castLogger(state.currentLogger, _optionalChain([options, 'optionalAccess', _87 => _87.asyncFlush]));
6909
6978
  }
6910
6979
  function currentSpan(options) {
6911
- const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _56 => _56.state]), () => ( _globalState));
6980
+ const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _88 => _88.state]), () => ( _globalState));
6912
6981
  return _nullishCoalesce(state.contextManager.getCurrentSpan(), () => ( NOOP_SPAN));
6913
6982
  }
6914
6983
  function getSpanParentObject(options) {
6915
- const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _57 => _57.state]), () => ( _globalState));
6984
+ const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _89 => _89.state]), () => ( _globalState));
6916
6985
  const parentSpan = currentSpan({ state });
6917
6986
  if (!Object.is(parentSpan, NOOP_SPAN)) {
6918
6987
  return parentSpan;
6919
6988
  }
6920
- const parentStr = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _58 => _58.parent]), () => ( state.currentParent.getStore()));
6989
+ const parentStr = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _90 => _90.parent]), () => ( state.currentParent.getStore()));
6921
6990
  if (parentStr) return getSpanComponentsClass().fromStr(parentStr);
6922
6991
  const experiment = currentExperiment();
6923
6992
  if (experiment) {
@@ -6946,7 +7015,7 @@ function traced(callback, args) {
6946
7015
  const { span, isSyncFlushLogger } = startSpanAndIsLogger(args);
6947
7016
  const ret = runCatchFinally(
6948
7017
  () => {
6949
- if (_nullishCoalesce(_optionalChain([args, 'optionalAccess', _59 => _59.setCurrent]), () => ( true))) {
7018
+ if (_nullishCoalesce(_optionalChain([args, 'optionalAccess', _91 => _91.setCurrent]), () => ( true))) {
6950
7019
  return withCurrent(span, callback);
6951
7020
  } else {
6952
7021
  return callback(span);
@@ -6958,7 +7027,7 @@ function traced(callback, args) {
6958
7027
  },
6959
7028
  () => span.end()
6960
7029
  );
6961
- if (_optionalChain([args, 'optionalAccess', _60 => _60.asyncFlush]) === void 0 || _optionalChain([args, 'optionalAccess', _61 => _61.asyncFlush])) {
7030
+ if (_optionalChain([args, 'optionalAccess', _92 => _92.asyncFlush]) === void 0 || _optionalChain([args, 'optionalAccess', _93 => _93.asyncFlush])) {
6962
7031
  return ret;
6963
7032
  } else {
6964
7033
  return (async () => {
@@ -6974,14 +7043,14 @@ function startSpan(args) {
6974
7043
  return startSpanAndIsLogger(args).span;
6975
7044
  }
6976
7045
  async function flush(options) {
6977
- const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _62 => _62.state]), () => ( _globalState));
7046
+ const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _94 => _94.state]), () => ( _globalState));
6978
7047
  return await state.bgLogger().flush();
6979
7048
  }
6980
7049
  function startSpanAndIsLogger(args) {
6981
- const state = _nullishCoalesce(_optionalChain([args, 'optionalAccess', _63 => _63.state]), () => ( _globalState));
7050
+ const state = _nullishCoalesce(_optionalChain([args, 'optionalAccess', _95 => _95.state]), () => ( _globalState));
6982
7051
  const parentObject = getSpanParentObject({
6983
- asyncFlush: _optionalChain([args, 'optionalAccess', _64 => _64.asyncFlush]),
6984
- parent: _optionalChain([args, 'optionalAccess', _65 => _65.parent]),
7052
+ asyncFlush: _optionalChain([args, 'optionalAccess', _96 => _96.asyncFlush]),
7053
+ parent: _optionalChain([args, 'optionalAccess', _97 => _97.parent]),
6985
7054
  state
6986
7055
  });
6987
7056
  if (parentObject instanceof SpanComponentsV3 || parentObject instanceof SpanComponentsV4) {
@@ -6998,14 +7067,14 @@ function startSpanAndIsLogger(args) {
6998
7067
  ),
6999
7068
  parentComputeObjectMetadataArgs: _nullishCoalesce(parentObject.data.compute_object_metadata_args, () => ( void 0)),
7000
7069
  parentSpanIds,
7001
- propagatedEvent: _nullishCoalesce(_optionalChain([args, 'optionalAccess', _66 => _66.propagatedEvent]), () => ( // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
7070
+ propagatedEvent: _nullishCoalesce(_optionalChain([args, 'optionalAccess', _98 => _98.propagatedEvent]), () => ( // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
7002
7071
  (_nullishCoalesce(parentObject.data.propagated_event, () => ( void 0)))))
7003
7072
  });
7004
7073
  return {
7005
7074
  span,
7006
7075
  isSyncFlushLogger: parentObject.data.object_type === 2 /* PROJECT_LOGS */ && // Since there's no parent logger here, we're free to choose the async flush
7007
7076
  // behavior, and therefore propagate along whatever we get from the arguments
7008
- _optionalChain([args, 'optionalAccess', _67 => _67.asyncFlush]) === false
7077
+ _optionalChain([args, 'optionalAccess', _99 => _99.asyncFlush]) === false
7009
7078
  };
7010
7079
  } else {
7011
7080
  const span = parentObject.startSpan(args);
@@ -7153,10 +7222,10 @@ function extractAttachments(event, attachments) {
7153
7222
  event[key] = value.reference;
7154
7223
  continue;
7155
7224
  }
7156
- if (_optionalChain([value, 'optionalAccess', _68 => _68.type]) === BRAINTRUST_ATTACHMENT && value.key && !value.uploader) {
7225
+ if (_optionalChain([value, 'optionalAccess', _100 => _100.type]) === BRAINTRUST_ATTACHMENT && value.key && !value.uploader) {
7157
7226
  continue;
7158
7227
  }
7159
- if (_optionalChain([value, 'optionalAccess', _69 => _69.reference, 'optionalAccess', _70 => _70.type]) === BRAINTRUST_ATTACHMENT && _optionalChain([value, 'optionalAccess', _71 => _71.uploader])) {
7228
+ if (_optionalChain([value, 'optionalAccess', _101 => _101.reference, 'optionalAccess', _102 => _102.type]) === BRAINTRUST_ATTACHMENT && _optionalChain([value, 'optionalAccess', _103 => _103.uploader])) {
7160
7229
  const attachment = new Attachment({
7161
7230
  data: value.dataDebugString,
7162
7231
  filename: value.reference.filename,
@@ -7240,7 +7309,7 @@ var ObjectFetcher = (_class11 = class {
7240
7309
  const state = await this.getState();
7241
7310
  const objectId = await this.id;
7242
7311
  const batchLimit = _nullishCoalesce(batchSize, () => ( DEFAULT_FETCH_BATCH_SIZE));
7243
- const internalLimit = _optionalChain([this, 'access', _72 => _72._internal_btql, 'optionalAccess', _73 => _73.limit]);
7312
+ const internalLimit = _optionalChain([this, 'access', _104 => _104._internal_btql, 'optionalAccess', _105 => _105.limit]);
7244
7313
  const limit = batchSize !== void 0 ? batchSize : _nullishCoalesce(internalLimit, () => ( batchLimit));
7245
7314
  const internalBtqlWithoutReservedQueryKeys = Object.fromEntries(
7246
7315
  Object.entries(_nullishCoalesce(this._internal_btql, () => ( {}))).filter(
@@ -7314,7 +7383,7 @@ var ObjectFetcher = (_class11 = class {
7314
7383
  }
7315
7384
  return;
7316
7385
  }
7317
- for await (const record of this.fetchRecordsFromApi(_optionalChain([options, 'optionalAccess', _74 => _74.batchSize]))) {
7386
+ for await (const record of this.fetchRecordsFromApi(_optionalChain([options, 'optionalAccess', _106 => _106.batchSize]))) {
7318
7387
  yield record;
7319
7388
  }
7320
7389
  }
@@ -7324,7 +7393,7 @@ var ObjectFetcher = (_class11 = class {
7324
7393
  async fetchedData(options) {
7325
7394
  if (this._fetchedData === void 0) {
7326
7395
  const data = [];
7327
- for await (const record of this.fetchRecordsFromApi(_optionalChain([options, 'optionalAccess', _75 => _75.batchSize]))) {
7396
+ for await (const record of this.fetchRecordsFromApi(_optionalChain([options, 'optionalAccess', _107 => _107.batchSize]))) {
7328
7397
  data.push(record);
7329
7398
  }
7330
7399
  this._fetchedData = data;
@@ -7419,7 +7488,7 @@ var Experiment2 = (_class12 = class extends ObjectFetcher {
7419
7488
  * @returns The `id` of the logged event.
7420
7489
  */
7421
7490
  log(event, options) {
7422
- if (this.calledStartSpan && !_optionalChain([options, 'optionalAccess', _76 => _76.allowConcurrentWithSpans])) {
7491
+ if (this.calledStartSpan && !_optionalChain([options, 'optionalAccess', _108 => _108.allowConcurrentWithSpans])) {
7423
7492
  throw new Error(
7424
7493
  "Cannot run toplevel `log` method while using spans. To log to the span, call `experiment.traced` and then log with `span.log`"
7425
7494
  );
@@ -7472,12 +7541,12 @@ var Experiment2 = (_class12 = class extends ObjectFetcher {
7472
7541
  state: this.state,
7473
7542
  ...startSpanParentArgs({
7474
7543
  state: this.state,
7475
- parent: _optionalChain([args, 'optionalAccess', _77 => _77.parent]),
7544
+ parent: _optionalChain([args, 'optionalAccess', _109 => _109.parent]),
7476
7545
  parentObjectType: this.parentObjectType(),
7477
7546
  parentObjectId: this.lazyId,
7478
7547
  parentComputeObjectMetadataArgs: void 0,
7479
7548
  parentSpanIds: void 0,
7480
- propagatedEvent: _optionalChain([args, 'optionalAccess', _78 => _78.propagatedEvent])
7549
+ propagatedEvent: _optionalChain([args, 'optionalAccess', _110 => _110.propagatedEvent])
7481
7550
  }),
7482
7551
  defaultRootType: "eval" /* EVAL */
7483
7552
  });
@@ -7821,7 +7890,7 @@ var SpanImpl = (_class13 = class _SpanImpl {
7821
7890
  ...serializableInternalData,
7822
7891
  [IS_MERGE_FIELD]: this.isMerge
7823
7892
  });
7824
- if (typeof _optionalChain([partialRecord, 'access', _79 => _79.metrics, 'optionalAccess', _80 => _80.end]) === "number") {
7893
+ if (typeof _optionalChain([partialRecord, 'access', _111 => _111.metrics, 'optionalAccess', _112 => _112.end]) === "number") {
7825
7894
  this.loggedEndTime = partialRecord.metrics.end;
7826
7895
  }
7827
7896
  if (this.parentObjectType === 1 /* EXPERIMENT */) {
@@ -7881,18 +7950,18 @@ var SpanImpl = (_class13 = class _SpanImpl {
7881
7950
  );
7882
7951
  }
7883
7952
  startSpan(args) {
7884
- const parentSpanIds = _optionalChain([args, 'optionalAccess', _81 => _81.parent]) ? void 0 : { spanId: this._spanId, rootSpanId: this._rootSpanId };
7953
+ const parentSpanIds = _optionalChain([args, 'optionalAccess', _113 => _113.parent]) ? void 0 : { spanId: this._spanId, rootSpanId: this._rootSpanId };
7885
7954
  return new _SpanImpl({
7886
7955
  state: this._state,
7887
7956
  ...args,
7888
7957
  ...startSpanParentArgs({
7889
7958
  state: this._state,
7890
- parent: _optionalChain([args, 'optionalAccess', _82 => _82.parent]),
7959
+ parent: _optionalChain([args, 'optionalAccess', _114 => _114.parent]),
7891
7960
  parentObjectType: this.parentObjectType,
7892
7961
  parentObjectId: this.parentObjectId,
7893
7962
  parentComputeObjectMetadataArgs: this.parentComputeObjectMetadataArgs,
7894
7963
  parentSpanIds,
7895
- propagatedEvent: _nullishCoalesce(_optionalChain([args, 'optionalAccess', _83 => _83.propagatedEvent]), () => ( this.propagatedEvent))
7964
+ propagatedEvent: _nullishCoalesce(_optionalChain([args, 'optionalAccess', _115 => _115.propagatedEvent]), () => ( this.propagatedEvent))
7896
7965
  })
7897
7966
  });
7898
7967
  }
@@ -7906,12 +7975,12 @@ var SpanImpl = (_class13 = class _SpanImpl {
7906
7975
  ...args,
7907
7976
  ...startSpanParentArgs({
7908
7977
  state: this._state,
7909
- parent: _optionalChain([args, 'optionalAccess', _84 => _84.parent]),
7978
+ parent: _optionalChain([args, 'optionalAccess', _116 => _116.parent]),
7910
7979
  parentObjectType: this.parentObjectType,
7911
7980
  parentObjectId: this.parentObjectId,
7912
7981
  parentComputeObjectMetadataArgs: this.parentComputeObjectMetadataArgs,
7913
7982
  parentSpanIds,
7914
- propagatedEvent: _nullishCoalesce(_optionalChain([args, 'optionalAccess', _85 => _85.propagatedEvent]), () => ( this.propagatedEvent))
7983
+ propagatedEvent: _nullishCoalesce(_optionalChain([args, 'optionalAccess', _117 => _117.propagatedEvent]), () => ( this.propagatedEvent))
7915
7984
  }),
7916
7985
  spanId
7917
7986
  });
@@ -7920,7 +7989,7 @@ var SpanImpl = (_class13 = class _SpanImpl {
7920
7989
  let endTime;
7921
7990
  let internalData = {};
7922
7991
  if (!this.loggedEndTime) {
7923
- endTime = _nullishCoalesce(_optionalChain([args, 'optionalAccess', _86 => _86.endTime]), () => ( getCurrentUnixTimestamp()));
7992
+ endTime = _nullishCoalesce(_optionalChain([args, 'optionalAccess', _118 => _118.endTime]), () => ( getCurrentUnixTimestamp()));
7924
7993
  internalData = { metrics: { end: endTime } };
7925
7994
  } else {
7926
7995
  endTime = this.loggedEndTime;
@@ -7971,8 +8040,8 @@ var SpanImpl = (_class13 = class _SpanImpl {
7971
8040
  const args = this.parentComputeObjectMetadataArgs;
7972
8041
  switch (this.parentObjectType) {
7973
8042
  case 2 /* PROJECT_LOGS */: {
7974
- const projectID = _optionalChain([args, 'optionalAccess', _87 => _87.project_id]) || this.parentObjectId.getSync().value;
7975
- const projectName = _optionalChain([args, 'optionalAccess', _88 => _88.project_name]);
8043
+ const projectID = _optionalChain([args, 'optionalAccess', _119 => _119.project_id]) || this.parentObjectId.getSync().value;
8044
+ const projectName = _optionalChain([args, 'optionalAccess', _120 => _120.project_name]);
7976
8045
  if (projectID) {
7977
8046
  return `${baseUrl}/object?object_type=project_logs&object_id=${projectID}&id=${this._id}`;
7978
8047
  } else if (projectName) {
@@ -7982,7 +8051,7 @@ var SpanImpl = (_class13 = class _SpanImpl {
7982
8051
  }
7983
8052
  }
7984
8053
  case 1 /* EXPERIMENT */: {
7985
- const expID = _optionalChain([args, 'optionalAccess', _89 => _89.experiment_id]) || _optionalChain([this, 'access', _90 => _90.parentObjectId, 'optionalAccess', _91 => _91.getSync, 'call', _92 => _92(), 'optionalAccess', _93 => _93.value]);
8054
+ const expID = _optionalChain([args, 'optionalAccess', _121 => _121.experiment_id]) || _optionalChain([this, 'access', _122 => _122.parentObjectId, 'optionalAccess', _123 => _123.getSync, 'call', _124 => _124(), 'optionalAccess', _125 => _125.value]);
7986
8055
  if (!expID) {
7987
8056
  return getErrPermlink("provide-experiment-id");
7988
8057
  } else {
@@ -8482,16 +8551,16 @@ var Prompt2 = (_class15 = class _Prompt {
8482
8551
  return "slug" in this.metadata ? this.metadata.slug : this.metadata.id;
8483
8552
  }
8484
8553
  get prompt() {
8485
- return _optionalChain([this, 'access', _94 => _94.getParsedPromptData, 'call', _95 => _95(), 'optionalAccess', _96 => _96.prompt]);
8554
+ return _optionalChain([this, 'access', _126 => _126.getParsedPromptData, 'call', _127 => _127(), 'optionalAccess', _128 => _128.prompt]);
8486
8555
  }
8487
8556
  get version() {
8488
8557
  return this.metadata[TRANSACTION_ID_FIELD];
8489
8558
  }
8490
8559
  get options() {
8491
- return _optionalChain([this, 'access', _97 => _97.getParsedPromptData, 'call', _98 => _98(), 'optionalAccess', _99 => _99.options]) || {};
8560
+ return _optionalChain([this, 'access', _129 => _129.getParsedPromptData, 'call', _130 => _130(), 'optionalAccess', _131 => _131.options]) || {};
8492
8561
  }
8493
8562
  get templateFormat() {
8494
- return _optionalChain([this, 'access', _100 => _100.getParsedPromptData, 'call', _101 => _101(), 'optionalAccess', _102 => _102.template_format]);
8563
+ return _optionalChain([this, 'access', _132 => _132.getParsedPromptData, 'call', _133 => _133(), 'optionalAccess', _134 => _134.template_format]);
8495
8564
  }
8496
8565
  get promptData() {
8497
8566
  return this.getParsedPromptData();
@@ -8653,7 +8722,7 @@ var Prompt2 = (_class15 = class _Prompt {
8653
8722
  return {
8654
8723
  type: "chat",
8655
8724
  messages,
8656
- ..._optionalChain([prompt, 'access', _103 => _103.tools, 'optionalAccess', _104 => _104.trim, 'call', _105 => _105()]) ? {
8725
+ ..._optionalChain([prompt, 'access', _135 => _135.tools, 'optionalAccess', _136 => _136.trim, 'call', _137 => _137()]) ? {
8657
8726
  tools: render(prompt.tools)
8658
8727
  } : void 0
8659
8728
  };
@@ -8869,7 +8938,7 @@ function getChannelSpanInfo(event) {
8869
8938
  if (isObject(event.span_info)) {
8870
8939
  return event.span_info;
8871
8940
  }
8872
- const firstArg = _optionalChain([event, 'access', _106 => _106.arguments, 'optionalAccess', _107 => _107[0]]);
8941
+ const firstArg = _optionalChain([event, 'access', _138 => _138.arguments, 'optionalAccess', _139 => _139[0]]);
8873
8942
  if (hasChannelSpanInfo(firstArg)) {
8874
8943
  return firstArg.span_info;
8875
8944
  }
@@ -8880,13 +8949,13 @@ function buildStartSpanArgs(config, event) {
8880
8949
  const spanAttributes = {
8881
8950
  type: config.type
8882
8951
  };
8883
- if (isObject(_optionalChain([spanInfo, 'optionalAccess', _108 => _108.spanAttributes]))) {
8952
+ if (isObject(_optionalChain([spanInfo, 'optionalAccess', _140 => _140.spanAttributes]))) {
8884
8953
  mergeDicts(spanAttributes, spanInfo.spanAttributes);
8885
8954
  }
8886
8955
  return {
8887
- name: typeof _optionalChain([spanInfo, 'optionalAccess', _109 => _109.name]) === "string" && spanInfo.name ? spanInfo.name : config.name,
8956
+ name: typeof _optionalChain([spanInfo, 'optionalAccess', _141 => _141.name]) === "string" && spanInfo.name ? spanInfo.name : config.name,
8888
8957
  spanAttributes,
8889
- spanInfoMetadata: isObject(_optionalChain([spanInfo, 'optionalAccess', _110 => _110.metadata])) ? spanInfo.metadata : void 0
8958
+ spanInfoMetadata: isObject(_optionalChain([spanInfo, 'optionalAccess', _142 => _142.metadata])) ? spanInfo.metadata : void 0
8890
8959
  };
8891
8960
  }
8892
8961
  function mergeInputMetadata(metadata, spanInfoMetadata) {
@@ -8976,7 +9045,7 @@ var BasePlugin = (_class17 = class {constructor() { _class17.prototype.__init62.
8976
9045
  try {
8977
9046
  const output = config.extractOutput(event.result, event);
8978
9047
  const metrics = config.extractMetrics(event.result, startTime, event);
8979
- const metadata = _optionalChain([config, 'access', _111 => _111.extractMetadata, 'optionalCall', _112 => _112(event.result, event)]);
9048
+ const metadata = _optionalChain([config, 'access', _143 => _143.extractMetadata, 'optionalCall', _144 => _144(event.result, event)]);
8980
9049
  span.log({
8981
9050
  output,
8982
9051
  ...metadata !== void 0 ? { metadata } : {},
@@ -9283,6 +9352,36 @@ function startSpanForEvent(config, event, channelName) {
9283
9352
  }
9284
9353
  return { span, startTime };
9285
9354
  }
9355
+ function ensureSpanStateForEvent(states, config, event, channelName) {
9356
+ const key = event;
9357
+ const existing = states.get(key);
9358
+ if (existing) {
9359
+ return existing;
9360
+ }
9361
+ const created = startSpanForEvent(config, event, channelName);
9362
+ states.set(key, created);
9363
+ return created;
9364
+ }
9365
+ function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelName) {
9366
+ const state = _internalGetGlobalState();
9367
+ const startChannel = tracingChannel2.start;
9368
+ const currentSpanStore = _optionalChain([state, 'optionalAccess', _145 => _145.contextManager]) ? state.contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
9369
+ if (!currentSpanStore || !startChannel) {
9370
+ return void 0;
9371
+ }
9372
+ startChannel.bindStore(
9373
+ currentSpanStore,
9374
+ (event) => ensureSpanStateForEvent(
9375
+ states,
9376
+ config,
9377
+ event,
9378
+ channelName
9379
+ ).span
9380
+ );
9381
+ return () => {
9382
+ startChannel.unbindStore(currentSpanStore);
9383
+ };
9384
+ }
9286
9385
  function logErrorAndEnd(states, event) {
9287
9386
  const spanData = states.get(event);
9288
9387
  if (!spanData) {
@@ -9298,15 +9397,19 @@ function traceAsyncChannel(channel2, config) {
9298
9397
  const tracingChannel2 = channel2.tracingChannel();
9299
9398
  const states = /* @__PURE__ */ new WeakMap();
9300
9399
  const channelName = channel2.channelName;
9400
+ const unbindCurrentSpanStore = bindCurrentSpanStoreToStart(
9401
+ tracingChannel2,
9402
+ states,
9403
+ config,
9404
+ channelName
9405
+ );
9301
9406
  const handlers = {
9302
9407
  start: (event) => {
9303
- states.set(
9408
+ ensureSpanStateForEvent(
9409
+ states,
9410
+ config,
9304
9411
  event,
9305
- startSpanForEvent(
9306
- config,
9307
- event,
9308
- channelName
9309
- )
9412
+ channelName
9310
9413
  );
9311
9414
  },
9312
9415
  asyncEnd: (event) => {
@@ -9326,7 +9429,7 @@ function traceAsyncChannel(channel2, config) {
9326
9429
  startTime,
9327
9430
  asyncEndEvent
9328
9431
  );
9329
- const metadata = _optionalChain([config, 'access', _113 => _113.extractMetadata, 'optionalCall', _114 => _114(
9432
+ const metadata = _optionalChain([config, 'access', _146 => _146.extractMetadata, 'optionalCall', _147 => _147(
9330
9433
  asyncEndEvent.result,
9331
9434
  asyncEndEvent
9332
9435
  )]);
@@ -9348,6 +9451,7 @@ function traceAsyncChannel(channel2, config) {
9348
9451
  };
9349
9452
  tracingChannel2.subscribe(handlers);
9350
9453
  return () => {
9454
+ _optionalChain([unbindCurrentSpanStore, 'optionalCall', _148 => _148()]);
9351
9455
  tracingChannel2.unsubscribe(handlers);
9352
9456
  };
9353
9457
  }
@@ -9355,15 +9459,19 @@ function traceStreamingChannel(channel2, config) {
9355
9459
  const tracingChannel2 = channel2.tracingChannel();
9356
9460
  const states = /* @__PURE__ */ new WeakMap();
9357
9461
  const channelName = channel2.channelName;
9462
+ const unbindCurrentSpanStore = bindCurrentSpanStoreToStart(
9463
+ tracingChannel2,
9464
+ states,
9465
+ config,
9466
+ channelName
9467
+ );
9358
9468
  const handlers = {
9359
9469
  start: (event) => {
9360
- states.set(
9470
+ ensureSpanStateForEvent(
9471
+ states,
9472
+ config,
9361
9473
  event,
9362
- startSpanForEvent(
9363
- config,
9364
- event,
9365
- channelName
9366
- )
9474
+ channelName
9367
9475
  );
9368
9476
  },
9369
9477
  asyncEnd: (event) => {
@@ -9437,7 +9545,7 @@ function traceStreamingChannel(channel2, config) {
9437
9545
  });
9438
9546
  return;
9439
9547
  }
9440
- if (_optionalChain([config, 'access', _115 => _115.patchResult, 'optionalCall', _116 => _116({
9548
+ if (_optionalChain([config, 'access', _149 => _149.patchResult, 'optionalCall', _150 => _150({
9441
9549
  channelName,
9442
9550
  endEvent: asyncEndEvent,
9443
9551
  result: asyncEndEvent.result,
@@ -9457,7 +9565,7 @@ function traceStreamingChannel(channel2, config) {
9457
9565
  startTime,
9458
9566
  asyncEndEvent
9459
9567
  );
9460
- const metadata = _optionalChain([config, 'access', _117 => _117.extractMetadata, 'optionalCall', _118 => _118(
9568
+ const metadata = _optionalChain([config, 'access', _151 => _151.extractMetadata, 'optionalCall', _152 => _152(
9461
9569
  asyncEndEvent.result,
9462
9570
  asyncEndEvent
9463
9571
  )]);
@@ -9479,6 +9587,7 @@ function traceStreamingChannel(channel2, config) {
9479
9587
  };
9480
9588
  tracingChannel2.subscribe(handlers);
9481
9589
  return () => {
9590
+ _optionalChain([unbindCurrentSpanStore, 'optionalCall', _153 => _153()]);
9482
9591
  tracingChannel2.unsubscribe(handlers);
9483
9592
  };
9484
9593
  }
@@ -9486,15 +9595,19 @@ function traceSyncStreamChannel(channel2, config) {
9486
9595
  const tracingChannel2 = channel2.tracingChannel();
9487
9596
  const states = /* @__PURE__ */ new WeakMap();
9488
9597
  const channelName = channel2.channelName;
9598
+ const unbindCurrentSpanStore = bindCurrentSpanStoreToStart(
9599
+ tracingChannel2,
9600
+ states,
9601
+ config,
9602
+ channelName
9603
+ );
9489
9604
  const handlers = {
9490
9605
  start: (event) => {
9491
- states.set(
9606
+ ensureSpanStateForEvent(
9607
+ states,
9608
+ config,
9492
9609
  event,
9493
- startSpanForEvent(
9494
- config,
9495
- event,
9496
- channelName
9497
- )
9610
+ channelName
9498
9611
  );
9499
9612
  },
9500
9613
  end: (event) => {
@@ -9504,7 +9617,7 @@ function traceSyncStreamChannel(channel2, config) {
9504
9617
  }
9505
9618
  const { span, startTime } = spanData;
9506
9619
  const endEvent = event;
9507
- if (_optionalChain([config, 'access', _119 => _119.patchResult, 'optionalCall', _120 => _120({
9620
+ if (_optionalChain([config, 'access', _154 => _154.patchResult, 'optionalCall', _155 => _155({
9508
9621
  channelName,
9509
9622
  endEvent,
9510
9623
  result: endEvent.result,
@@ -9583,6 +9696,7 @@ function traceSyncStreamChannel(channel2, config) {
9583
9696
  };
9584
9697
  tracingChannel2.subscribe(handlers);
9585
9698
  return () => {
9699
+ _optionalChain([unbindCurrentSpanStore, 'optionalCall', _156 => _156()]);
9586
9700
  tracingChannel2.unsubscribe(handlers);
9587
9701
  };
9588
9702
  }
@@ -9657,7 +9771,7 @@ function processInputAttachments(input) {
9657
9771
  let attachmentIndex = 0;
9658
9772
  const inferMediaTypeFromDataUrl = (value, fallback2) => {
9659
9773
  const mediaTypeMatch = value.match(/^data:([^;]+);/);
9660
- return _optionalChain([mediaTypeMatch, 'optionalAccess', _121 => _121[1]]) || fallback2;
9774
+ return _optionalChain([mediaTypeMatch, 'optionalAccess', _157 => _157[1]]) || fallback2;
9661
9775
  };
9662
9776
  const toAttachment = (value, mediaType, filename) => {
9663
9777
  const blob = convertDataToBlob(value, mediaType);
@@ -9907,11 +10021,11 @@ var OpenAIPlugin = class extends BasePlugin {
9907
10021
  };
9908
10022
  },
9909
10023
  extractOutput: (result) => {
9910
- return _optionalChain([result, 'optionalAccess', _122 => _122.choices]);
10024
+ return _optionalChain([result, 'optionalAccess', _158 => _158.choices]);
9911
10025
  },
9912
10026
  extractMetrics: (result, startTime, endEvent) => {
9913
10027
  const metrics = withCachedMetric(
9914
- parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _123 => _123.usage])),
10028
+ parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _159 => _159.usage])),
9915
10029
  result,
9916
10030
  endEvent
9917
10031
  );
@@ -9935,12 +10049,12 @@ var OpenAIPlugin = class extends BasePlugin {
9935
10049
  };
9936
10050
  },
9937
10051
  extractOutput: (result) => {
9938
- const embedding = _optionalChain([result, 'optionalAccess', _124 => _124.data, 'optionalAccess', _125 => _125[0], 'optionalAccess', _126 => _126.embedding]);
10052
+ const embedding = _optionalChain([result, 'optionalAccess', _160 => _160.data, 'optionalAccess', _161 => _161[0], 'optionalAccess', _162 => _162.embedding]);
9939
10053
  return Array.isArray(embedding) ? { embedding_length: embedding.length } : void 0;
9940
10054
  },
9941
10055
  extractMetrics: (result, _startTime, endEvent) => {
9942
10056
  return withCachedMetric(
9943
- parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _127 => _127.usage])),
10057
+ parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _163 => _163.usage])),
9944
10058
  result,
9945
10059
  endEvent
9946
10060
  );
@@ -9959,11 +10073,11 @@ var OpenAIPlugin = class extends BasePlugin {
9959
10073
  };
9960
10074
  },
9961
10075
  extractOutput: (result) => {
9962
- return _optionalChain([result, 'optionalAccess', _128 => _128.choices]);
10076
+ return _optionalChain([result, 'optionalAccess', _164 => _164.choices]);
9963
10077
  },
9964
10078
  extractMetrics: (result, startTime, endEvent) => {
9965
10079
  const metrics = withCachedMetric(
9966
- parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _129 => _129.usage])),
10080
+ parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _165 => _165.usage])),
9967
10081
  result,
9968
10082
  endEvent
9969
10083
  );
@@ -10000,11 +10114,11 @@ var OpenAIPlugin = class extends BasePlugin {
10000
10114
  };
10001
10115
  },
10002
10116
  extractOutput: (result) => {
10003
- return _optionalChain([result, 'optionalAccess', _130 => _130.results]);
10117
+ return _optionalChain([result, 'optionalAccess', _166 => _166.results]);
10004
10118
  },
10005
10119
  extractMetrics: (result, _startTime, endEvent) => {
10006
10120
  return withCachedMetric(
10007
- parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _131 => _131.usage])),
10121
+ parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _167 => _167.usage])),
10008
10122
  result,
10009
10123
  endEvent
10010
10124
  );
@@ -10023,7 +10137,7 @@ var OpenAIPlugin = class extends BasePlugin {
10023
10137
  };
10024
10138
  },
10025
10139
  extractOutput: (result) => {
10026
- return processImagesInOutput(_optionalChain([result, 'optionalAccess', _132 => _132.output]));
10140
+ return processImagesInOutput(_optionalChain([result, 'optionalAccess', _168 => _168.output]));
10027
10141
  },
10028
10142
  extractMetadata: (result) => {
10029
10143
  if (!result) {
@@ -10034,7 +10148,7 @@ var OpenAIPlugin = class extends BasePlugin {
10034
10148
  },
10035
10149
  extractMetrics: (result, startTime, endEvent) => {
10036
10150
  const metrics = withCachedMetric(
10037
- parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _133 => _133.usage])),
10151
+ parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _169 => _169.usage])),
10038
10152
  result,
10039
10153
  endEvent
10040
10154
  );
@@ -10087,7 +10201,7 @@ var OpenAIPlugin = class extends BasePlugin {
10087
10201
  };
10088
10202
  },
10089
10203
  extractOutput: (result) => {
10090
- return processImagesInOutput(_optionalChain([result, 'optionalAccess', _134 => _134.output]));
10204
+ return processImagesInOutput(_optionalChain([result, 'optionalAccess', _170 => _170.output]));
10091
10205
  },
10092
10206
  extractMetadata: (result) => {
10093
10207
  if (!result) {
@@ -10098,7 +10212,7 @@ var OpenAIPlugin = class extends BasePlugin {
10098
10212
  },
10099
10213
  extractMetrics: (result, startTime, endEvent) => {
10100
10214
  const metrics = withCachedMetric(
10101
- parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _135 => _135.usage])),
10215
+ parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _171 => _171.usage])),
10102
10216
  result,
10103
10217
  endEvent
10104
10218
  );
@@ -10194,7 +10308,7 @@ function aggregateChatCompletionChunks(chunks, streamResult, endEvent) {
10194
10308
  ...parseMetricsFromUsage(chunk.usage)
10195
10309
  };
10196
10310
  }
10197
- const delta = _optionalChain([chunk, 'access', _136 => _136.choices, 'optionalAccess', _137 => _137[0], 'optionalAccess', _138 => _138.delta]);
10311
+ const delta = _optionalChain([chunk, 'access', _172 => _172.choices, 'optionalAccess', _173 => _173[0], 'optionalAccess', _174 => _174.delta]);
10198
10312
  if (!delta) {
10199
10313
  continue;
10200
10314
  }
@@ -10252,14 +10366,14 @@ function aggregateResponseStreamEvents(chunks, _streamResult, endEvent) {
10252
10366
  continue;
10253
10367
  }
10254
10368
  const response = chunk.response;
10255
- if (_optionalChain([response, 'optionalAccess', _139 => _139.output]) !== void 0) {
10369
+ if (_optionalChain([response, 'optionalAccess', _175 => _175.output]) !== void 0) {
10256
10370
  output = processImagesInOutput(response.output);
10257
10371
  }
10258
10372
  const { usage: _usage, output: _output, ...rest } = response || {};
10259
10373
  if (Object.keys(rest).length > 0) {
10260
10374
  metadata = rest;
10261
10375
  }
10262
- metrics = parseMetricsFromUsage(_optionalChain([response, 'optionalAccess', _140 => _140.usage]));
10376
+ metrics = parseMetricsFromUsage(_optionalChain([response, 'optionalAccess', _176 => _176.usage]));
10263
10377
  }
10264
10378
  return {
10265
10379
  output,
@@ -10325,7 +10439,7 @@ var AnthropicPlugin = class extends BasePlugin {
10325
10439
  return message ? { role: message.role, content: message.content } : null;
10326
10440
  },
10327
10441
  extractMetrics: (message, startTime) => {
10328
- const metrics = parseMetricsFromUsage2(_optionalChain([message, 'optionalAccess', _141 => _141.usage]));
10442
+ const metrics = parseMetricsFromUsage2(_optionalChain([message, 'optionalAccess', _177 => _177.usage]));
10329
10443
  if (startTime) {
10330
10444
  metrics.time_to_first_token = getCurrentUnixTimestamp() - startTime;
10331
10445
  }
@@ -10340,7 +10454,7 @@ var AnthropicPlugin = class extends BasePlugin {
10340
10454
  const metadata = {};
10341
10455
  const metas = ["stop_reason", "stop_sequence"];
10342
10456
  for (const m of metas) {
10343
- if (_optionalChain([message, 'optionalAccess', _142 => _142[m]]) !== void 0) {
10457
+ if (_optionalChain([message, 'optionalAccess', _178 => _178[m]]) !== void 0) {
10344
10458
  metadata[m] = message[m];
10345
10459
  }
10346
10460
  }
@@ -10381,15 +10495,15 @@ function aggregateAnthropicStreamChunks(chunks) {
10381
10495
  let metrics = {};
10382
10496
  let metadata = {};
10383
10497
  for (const event of chunks) {
10384
- switch (_optionalChain([event, 'optionalAccess', _143 => _143.type])) {
10498
+ switch (_optionalChain([event, 'optionalAccess', _179 => _179.type])) {
10385
10499
  case "message_start":
10386
- if (_optionalChain([event, 'access', _144 => _144.message, 'optionalAccess', _145 => _145.usage])) {
10500
+ if (_optionalChain([event, 'access', _180 => _180.message, 'optionalAccess', _181 => _181.usage])) {
10387
10501
  const initialMetrics = parseMetricsFromUsage2(event.message.usage);
10388
10502
  metrics = { ...metrics, ...initialMetrics };
10389
10503
  }
10390
10504
  break;
10391
10505
  case "content_block_delta":
10392
- if (_optionalChain([event, 'access', _146 => _146.delta, 'optionalAccess', _147 => _147.type]) === "text_delta") {
10506
+ if (_optionalChain([event, 'access', _182 => _182.delta, 'optionalAccess', _183 => _183.type]) === "text_delta") {
10393
10507
  const text = event.delta.text;
10394
10508
  if (text) {
10395
10509
  deltas.push(text);
@@ -10846,7 +10960,7 @@ function extractTopLevelAISDKMetrics(result, event, startTime) {
10846
10960
  return metrics;
10847
10961
  }
10848
10962
  function hasModelChildTracing(event) {
10849
- return _optionalChain([event, 'optionalAccess', _148 => _148.__braintrust_ai_sdk_model_wrapped]) === true;
10963
+ return _optionalChain([event, 'optionalAccess', _184 => _184.__braintrust_ai_sdk_model_wrapped]) === true;
10850
10964
  }
10851
10965
  function extractMetadataFromParams(params, self) {
10852
10966
  const metadata = {
@@ -10855,7 +10969,7 @@ function extractMetadataFromParams(params, self) {
10855
10969
  sdk_language: "typescript"
10856
10970
  }
10857
10971
  };
10858
- const agentModel = self && typeof self === "object" && "model" in self && self.model ? self.model : self && typeof self === "object" && "settings" in self && _optionalChain([self, 'access', _149 => _149.settings, 'optionalAccess', _150 => _150.model]) ? _optionalChain([self, 'access', _151 => _151.settings, 'optionalAccess', _152 => _152.model]) : void 0;
10972
+ const agentModel = self && typeof self === "object" && "model" in self && self.model ? self.model : self && typeof self === "object" && "settings" in self && _optionalChain([self, 'access', _185 => _185.settings, 'optionalAccess', _186 => _186.model]) ? _optionalChain([self, 'access', _187 => _187.settings, 'optionalAccess', _188 => _188.model]) : void 0;
10859
10973
  const { model, provider } = serializeModelWithProvider(
10860
10974
  _nullishCoalesce(params.model, () => ( agentModel))
10861
10975
  );
@@ -10957,9 +11071,9 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths) {
10957
11071
  case "raw":
10958
11072
  if (chunk.rawValue) {
10959
11073
  const rawVal = chunk.rawValue;
10960
- if (_optionalChain([rawVal, 'access', _153 => _153.delta, 'optionalAccess', _154 => _154.content])) {
11074
+ if (_optionalChain([rawVal, 'access', _189 => _189.delta, 'optionalAccess', _190 => _190.content])) {
10961
11075
  text += rawVal.delta.content;
10962
- } else if (_optionalChain([rawVal, 'access', _155 => _155.choices, 'optionalAccess', _156 => _156[0], 'optionalAccess', _157 => _157.delta, 'optionalAccess', _158 => _158.content])) {
11076
+ } else if (_optionalChain([rawVal, 'access', _191 => _191.choices, 'optionalAccess', _192 => _192[0], 'optionalAccess', _193 => _193.delta, 'optionalAccess', _194 => _194.content])) {
10963
11077
  text += rawVal.choices[0].delta.content;
10964
11078
  } else if (typeof rawVal.text === "string") {
10965
11079
  text += rawVal.text;
@@ -11096,14 +11210,14 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths) {
11096
11210
  return {
11097
11211
  cleanup: cleanup.length > 0 ? () => {
11098
11212
  while (cleanup.length > 0) {
11099
- _optionalChain([cleanup, 'access', _159 => _159.pop, 'call', _160 => _160(), 'optionalCall', _161 => _161()]);
11213
+ _optionalChain([cleanup, 'access', _195 => _195.pop, 'call', _196 => _196(), 'optionalCall', _197 => _197()]);
11100
11214
  }
11101
11215
  } : void 0,
11102
11216
  modelWrapped
11103
11217
  };
11104
11218
  }
11105
11219
  function finalizeAISDKChildTracing(event) {
11106
- const cleanup = _optionalChain([event, 'optionalAccess', _162 => _162.__braintrust_ai_sdk_cleanup]);
11220
+ const cleanup = _optionalChain([event, 'optionalAccess', _198 => _198.__braintrust_ai_sdk_cleanup]);
11107
11221
  if (event && typeof cleanup === "function") {
11108
11222
  cleanup();
11109
11223
  delete event.__braintrust_ai_sdk_cleanup;
@@ -11195,10 +11309,10 @@ function buildAISDKChildMetadata(model) {
11195
11309
  function buildResolvedMetadataPayload(result) {
11196
11310
  const gatewayInfo = extractGatewayRoutingInfo(result);
11197
11311
  const metadata = {};
11198
- if (_optionalChain([gatewayInfo, 'optionalAccess', _163 => _163.provider])) {
11312
+ if (_optionalChain([gatewayInfo, 'optionalAccess', _199 => _199.provider])) {
11199
11313
  metadata.provider = gatewayInfo.provider;
11200
11314
  }
11201
- if (_optionalChain([gatewayInfo, 'optionalAccess', _164 => _164.model])) {
11315
+ if (_optionalChain([gatewayInfo, 'optionalAccess', _200 => _200.model])) {
11202
11316
  metadata.model = gatewayInfo.model;
11203
11317
  }
11204
11318
  if (result.finishReason !== void 0) {
@@ -11233,7 +11347,7 @@ function processAISDKOutput(output, denyOutputPaths) {
11233
11347
  }
11234
11348
  function extractTokenMetrics(result) {
11235
11349
  const metrics = {};
11236
- let usage = _optionalChain([result, 'optionalAccess', _165 => _165.totalUsage]) || _optionalChain([result, 'optionalAccess', _166 => _166.usage]);
11350
+ let usage = _optionalChain([result, 'optionalAccess', _201 => _201.totalUsage]) || _optionalChain([result, 'optionalAccess', _202 => _202.usage]);
11237
11351
  if (!usage && result) {
11238
11352
  try {
11239
11353
  if ("totalUsage" in result && typeof result.totalUsage !== "function") {
@@ -11248,7 +11362,7 @@ function extractTokenMetrics(result) {
11248
11362
  return metrics;
11249
11363
  }
11250
11364
  const promptTokens = firstNumber(
11251
- _optionalChain([usage, 'access', _167 => _167.inputTokens, 'optionalAccess', _168 => _168.total]),
11365
+ _optionalChain([usage, 'access', _203 => _203.inputTokens, 'optionalAccess', _204 => _204.total]),
11252
11366
  usage.inputTokens,
11253
11367
  usage.promptTokens,
11254
11368
  usage.prompt_tokens
@@ -11257,7 +11371,7 @@ function extractTokenMetrics(result) {
11257
11371
  metrics.prompt_tokens = promptTokens;
11258
11372
  }
11259
11373
  const completionTokens = firstNumber(
11260
- _optionalChain([usage, 'access', _169 => _169.outputTokens, 'optionalAccess', _170 => _170.total]),
11374
+ _optionalChain([usage, 'access', _205 => _205.outputTokens, 'optionalAccess', _206 => _206.total]),
11261
11375
  usage.outputTokens,
11262
11376
  usage.completionTokens,
11263
11377
  usage.completion_tokens
@@ -11343,7 +11457,7 @@ function extractSerializableOutputFields(output) {
11343
11457
  ];
11344
11458
  for (const name of directFieldNames) {
11345
11459
  try {
11346
- const value = _optionalChain([output, 'optionalAccess', _171 => _171[name]]);
11460
+ const value = _optionalChain([output, 'optionalAccess', _207 => _207[name]]);
11347
11461
  if (isSerializableOutputValue(value)) {
11348
11462
  serialized[name] = value;
11349
11463
  }
@@ -11371,8 +11485,8 @@ function isSerializableOutputValue(value) {
11371
11485
  return true;
11372
11486
  }
11373
11487
  function serializeModelWithProvider(model) {
11374
- const modelId = typeof model === "string" ? model : _optionalChain([model, 'optionalAccess', _172 => _172.modelId]);
11375
- const explicitProvider = typeof model === "object" ? _optionalChain([model, 'optionalAccess', _173 => _173.provider]) : void 0;
11488
+ const modelId = typeof model === "string" ? model : _optionalChain([model, 'optionalAccess', _208 => _208.modelId]);
11489
+ const explicitProvider = typeof model === "object" ? _optionalChain([model, 'optionalAccess', _209 => _209.provider]) : void 0;
11376
11490
  if (!modelId) {
11377
11491
  return { model: modelId, provider: explicitProvider };
11378
11492
  }
@@ -11396,8 +11510,8 @@ function parseGatewayModelString(modelString) {
11396
11510
  return { model: modelString };
11397
11511
  }
11398
11512
  function extractGatewayRoutingInfo(result) {
11399
- if (_optionalChain([result, 'optionalAccess', _174 => _174.steps]) && Array.isArray(result.steps) && result.steps.length > 0) {
11400
- const routing2 = _optionalChain([result, 'access', _175 => _175.steps, 'access', _176 => _176[0], 'optionalAccess', _177 => _177.providerMetadata, 'optionalAccess', _178 => _178.gateway, 'optionalAccess', _179 => _179.routing]);
11513
+ if (_optionalChain([result, 'optionalAccess', _210 => _210.steps]) && Array.isArray(result.steps) && result.steps.length > 0) {
11514
+ const routing2 = _optionalChain([result, 'access', _211 => _211.steps, 'access', _212 => _212[0], 'optionalAccess', _213 => _213.providerMetadata, 'optionalAccess', _214 => _214.gateway, 'optionalAccess', _215 => _215.routing]);
11401
11515
  if (routing2) {
11402
11516
  return {
11403
11517
  provider: routing2.resolvedProvider || routing2.finalProvider,
@@ -11405,7 +11519,7 @@ function extractGatewayRoutingInfo(result) {
11405
11519
  };
11406
11520
  }
11407
11521
  }
11408
- const routing = _optionalChain([result, 'optionalAccess', _180 => _180.providerMetadata, 'optionalAccess', _181 => _181.gateway, 'optionalAccess', _182 => _182.routing]);
11522
+ const routing = _optionalChain([result, 'optionalAccess', _216 => _216.providerMetadata, 'optionalAccess', _217 => _217.gateway, 'optionalAccess', _218 => _218.routing]);
11409
11523
  if (routing) {
11410
11524
  return {
11411
11525
  provider: routing.resolvedProvider || routing.finalProvider,
@@ -11415,12 +11529,12 @@ function extractGatewayRoutingInfo(result) {
11415
11529
  return null;
11416
11530
  }
11417
11531
  function extractCostFromResult(result) {
11418
- if (_optionalChain([result, 'optionalAccess', _183 => _183.steps]) && Array.isArray(result.steps) && result.steps.length > 0) {
11532
+ if (_optionalChain([result, 'optionalAccess', _219 => _219.steps]) && Array.isArray(result.steps) && result.steps.length > 0) {
11419
11533
  let totalCost = 0;
11420
11534
  let foundCost = false;
11421
11535
  for (const step of result.steps) {
11422
- const gateway2 = _optionalChain([step, 'optionalAccess', _184 => _184.providerMetadata, 'optionalAccess', _185 => _185.gateway]);
11423
- const stepCost = parseGatewayCost(_optionalChain([gateway2, 'optionalAccess', _186 => _186.cost])) || parseGatewayCost(_optionalChain([gateway2, 'optionalAccess', _187 => _187.marketCost]));
11536
+ const gateway2 = _optionalChain([step, 'optionalAccess', _220 => _220.providerMetadata, 'optionalAccess', _221 => _221.gateway]);
11537
+ const stepCost = parseGatewayCost(_optionalChain([gateway2, 'optionalAccess', _222 => _222.cost])) || parseGatewayCost(_optionalChain([gateway2, 'optionalAccess', _223 => _223.marketCost]));
11424
11538
  if (stepCost !== void 0 && stepCost > 0) {
11425
11539
  totalCost += stepCost;
11426
11540
  foundCost = true;
@@ -11430,8 +11544,8 @@ function extractCostFromResult(result) {
11430
11544
  return totalCost;
11431
11545
  }
11432
11546
  }
11433
- const gateway = _optionalChain([result, 'optionalAccess', _188 => _188.providerMetadata, 'optionalAccess', _189 => _189.gateway]);
11434
- const directCost = parseGatewayCost(_optionalChain([gateway, 'optionalAccess', _190 => _190.cost])) || parseGatewayCost(_optionalChain([gateway, 'optionalAccess', _191 => _191.marketCost]));
11547
+ const gateway = _optionalChain([result, 'optionalAccess', _224 => _224.providerMetadata, 'optionalAccess', _225 => _225.gateway]);
11548
+ const directCost = parseGatewayCost(_optionalChain([gateway, 'optionalAccess', _226 => _226.cost])) || parseGatewayCost(_optionalChain([gateway, 'optionalAccess', _227 => _227.marketCost]));
11435
11549
  if (directCost !== void 0 && directCost > 0) {
11436
11550
  return directCost;
11437
11551
  }
@@ -11583,7 +11697,7 @@ function extractUsageFromMessage(message) {
11583
11697
  const metrics = {};
11584
11698
  let usage;
11585
11699
  if (message.type === "assistant") {
11586
- usage = _optionalChain([message, 'access', _192 => _192.message, 'optionalAccess', _193 => _193.usage]);
11700
+ usage = _optionalChain([message, 'access', _228 => _228.message, 'optionalAccess', _229 => _229.usage]);
11587
11701
  } else if (message.type === "result") {
11588
11702
  usage = message.usage;
11589
11703
  }
@@ -11623,14 +11737,14 @@ function buildLLMInput(prompt, conversationHistory) {
11623
11737
  async function createLLMSpanForMessages(messages, prompt, conversationHistory, options, startTime, parentSpan) {
11624
11738
  if (messages.length === 0) return void 0;
11625
11739
  const lastMessage = messages[messages.length - 1];
11626
- if (lastMessage.type !== "assistant" || !_optionalChain([lastMessage, 'access', _194 => _194.message, 'optionalAccess', _195 => _195.usage])) {
11740
+ if (lastMessage.type !== "assistant" || !_optionalChain([lastMessage, 'access', _230 => _230.message, 'optionalAccess', _231 => _231.usage])) {
11627
11741
  return void 0;
11628
11742
  }
11629
11743
  const model = lastMessage.message.model || options.model;
11630
11744
  const usage = extractUsageFromMessage(lastMessage);
11631
11745
  const input = buildLLMInput(prompt, conversationHistory);
11632
11746
  const outputs = messages.map(
11633
- (m) => _optionalChain([m, 'access', _196 => _196.message, 'optionalAccess', _197 => _197.content]) && _optionalChain([m, 'access', _198 => _198.message, 'optionalAccess', _199 => _199.role]) ? { content: m.message.content, role: m.message.role } : void 0
11747
+ (m) => _optionalChain([m, 'access', _232 => _232.message, 'optionalAccess', _233 => _233.content]) && _optionalChain([m, 'access', _234 => _234.message, 'optionalAccess', _235 => _235.role]) ? { content: m.message.content, role: m.message.role } : void 0
11634
11748
  ).filter(
11635
11749
  (c) => c !== void 0
11636
11750
  );
@@ -11649,7 +11763,7 @@ async function createLLMSpanForMessages(messages, prompt, conversationHistory, o
11649
11763
  metrics: usage
11650
11764
  });
11651
11765
  await span.end();
11652
- return _optionalChain([lastMessage, 'access', _200 => _200.message, 'optionalAccess', _201 => _201.content]) && _optionalChain([lastMessage, 'access', _202 => _202.message, 'optionalAccess', _203 => _203.role]) ? { content: lastMessage.message.content, role: lastMessage.message.role } : void 0;
11766
+ return _optionalChain([lastMessage, 'access', _236 => _236.message, 'optionalAccess', _237 => _237.content]) && _optionalChain([lastMessage, 'access', _238 => _238.message, 'optionalAccess', _239 => _239.role]) ? { content: lastMessage.message.content, role: lastMessage.message.role } : void 0;
11653
11767
  }
11654
11768
  var ClaudeAgentSDKPlugin = class extends BasePlugin {
11655
11769
  onEnable() {
@@ -11672,8 +11786,8 @@ var ClaudeAgentSDKPlugin = class extends BasePlugin {
11672
11786
  const handlers = {
11673
11787
  start: (event) => {
11674
11788
  const params = event.arguments[0];
11675
- const prompt = _optionalChain([params, 'optionalAccess', _204 => _204.prompt]);
11676
- const options = _nullishCoalesce(_optionalChain([params, 'optionalAccess', _205 => _205.options]), () => ( {}));
11789
+ const prompt = _optionalChain([params, 'optionalAccess', _240 => _240.prompt]);
11790
+ const options = _nullishCoalesce(_optionalChain([params, 'optionalAccess', _241 => _241.options]), () => ( {}));
11677
11791
  const span = startSpan({
11678
11792
  name: "Claude Agent",
11679
11793
  spanAttributes: {
@@ -11718,9 +11832,9 @@ var ClaudeAgentSDKPlugin = class extends BasePlugin {
11718
11832
  onChunk: async (message) => {
11719
11833
  const currentTime = getCurrentUnixTimestamp();
11720
11834
  const params = event.arguments[0];
11721
- const prompt = _optionalChain([params, 'optionalAccess', _206 => _206.prompt]);
11722
- const options = _nullishCoalesce(_optionalChain([params, 'optionalAccess', _207 => _207.options]), () => ( {}));
11723
- const messageId = _optionalChain([message, 'access', _208 => _208.message, 'optionalAccess', _209 => _209.id]);
11835
+ const prompt = _optionalChain([params, 'optionalAccess', _242 => _242.prompt]);
11836
+ const options = _nullishCoalesce(_optionalChain([params, 'optionalAccess', _243 => _243.options]), () => ( {}));
11837
+ const messageId = _optionalChain([message, 'access', _244 => _244.message, 'optionalAccess', _245 => _245.id]);
11724
11838
  if (messageId && messageId !== spanData.currentMessageId) {
11725
11839
  if (spanData.currentMessages.length > 0) {
11726
11840
  const finalMessage = await createLLMSpanForMessages(
@@ -11735,7 +11849,7 @@ var ClaudeAgentSDKPlugin = class extends BasePlugin {
11735
11849
  spanData.conversationHistory.push(finalMessage);
11736
11850
  }
11737
11851
  const lastMessage = spanData.currentMessages[spanData.currentMessages.length - 1];
11738
- if (_optionalChain([lastMessage, 'optionalAccess', _210 => _210.message, 'optionalAccess', _211 => _211.usage])) {
11852
+ if (_optionalChain([lastMessage, 'optionalAccess', _246 => _246.message, 'optionalAccess', _247 => _247.usage])) {
11739
11853
  const outputTokens = getNumberProperty(
11740
11854
  lastMessage.message.usage,
11741
11855
  "output_tokens"
@@ -11747,14 +11861,14 @@ var ClaudeAgentSDKPlugin = class extends BasePlugin {
11747
11861
  spanData.currentMessageId = messageId;
11748
11862
  spanData.currentMessageStartTime = currentTime;
11749
11863
  }
11750
- if (message.type === "assistant" && _optionalChain([message, 'access', _212 => _212.message, 'optionalAccess', _213 => _213.usage])) {
11864
+ if (message.type === "assistant" && _optionalChain([message, 'access', _248 => _248.message, 'optionalAccess', _249 => _249.usage])) {
11751
11865
  spanData.currentMessages.push(message);
11752
11866
  }
11753
11867
  if (message.type === "result" && message.usage) {
11754
11868
  const finalUsageMetrics = extractUsageFromMessage(message);
11755
11869
  if (spanData.currentMessages.length > 0 && finalUsageMetrics.completion_tokens !== void 0) {
11756
11870
  const lastMessage = spanData.currentMessages[spanData.currentMessages.length - 1];
11757
- if (_optionalChain([lastMessage, 'optionalAccess', _214 => _214.message, 'optionalAccess', _215 => _215.usage])) {
11871
+ if (_optionalChain([lastMessage, 'optionalAccess', _250 => _250.message, 'optionalAccess', _251 => _251.usage])) {
11758
11872
  const adjustedTokens = finalUsageMetrics.completion_tokens - spanData.accumulatedOutputTokens;
11759
11873
  if (adjustedTokens >= 0) {
11760
11874
  lastMessage.message.usage.output_tokens = adjustedTokens;
@@ -11778,8 +11892,8 @@ var ClaudeAgentSDKPlugin = class extends BasePlugin {
11778
11892
  onComplete: async () => {
11779
11893
  try {
11780
11894
  const params = event.arguments[0];
11781
- const prompt = _optionalChain([params, 'optionalAccess', _216 => _216.prompt]);
11782
- const options = _nullishCoalesce(_optionalChain([params, 'optionalAccess', _217 => _217.options]), () => ( {}));
11895
+ const prompt = _optionalChain([params, 'optionalAccess', _252 => _252.prompt]);
11896
+ const options = _nullishCoalesce(_optionalChain([params, 'optionalAccess', _253 => _253.options]), () => ( {}));
11783
11897
  if (spanData.currentMessages.length > 0) {
11784
11898
  const finalMessage = await createLLMSpanForMessages(
11785
11899
  spanData.currentMessages,
@@ -11986,7 +12100,7 @@ function serializePart(part) {
11986
12100
  return part;
11987
12101
  }
11988
12102
  function serializeTools(params) {
11989
- if (!_optionalChain([params, 'access', _218 => _218.config, 'optionalAccess', _219 => _219.tools])) {
12103
+ if (!_optionalChain([params, 'access', _254 => _254.config, 'optionalAccess', _255 => _255.tools])) {
11990
12104
  return null;
11991
12105
  }
11992
12106
  try {
@@ -12023,7 +12137,7 @@ function extractGenerateContentMetrics(response, startTime) {
12023
12137
  const end = getCurrentUnixTimestamp();
12024
12138
  metrics.duration = end - startTime;
12025
12139
  }
12026
- if (_optionalChain([response, 'optionalAccess', _220 => _220.usageMetadata])) {
12140
+ if (_optionalChain([response, 'optionalAccess', _256 => _256.usageMetadata])) {
12027
12141
  populateUsageMetrics(metrics, response.usageMetadata);
12028
12142
  }
12029
12143
  return metrics;
@@ -12071,7 +12185,7 @@ function aggregateGenerateContentChunks(chunks, startTime) {
12071
12185
  }
12072
12186
  if (chunk.candidates && Array.isArray(chunk.candidates)) {
12073
12187
  for (const candidate of chunk.candidates) {
12074
- if (_optionalChain([candidate, 'access', _221 => _221.content, 'optionalAccess', _222 => _222.parts])) {
12188
+ if (_optionalChain([candidate, 'access', _257 => _257.content, 'optionalAccess', _258 => _258.parts])) {
12075
12189
  for (const part of candidate.content.parts) {
12076
12190
  if (part.text !== void 0) {
12077
12191
  if (part.thought) {
@@ -12102,7 +12216,7 @@ function aggregateGenerateContentChunks(chunks, startTime) {
12102
12216
  parts.push({ text });
12103
12217
  }
12104
12218
  parts.push(...otherParts);
12105
- if (parts.length > 0 && _optionalChain([lastResponse, 'optionalAccess', _223 => _223.candidates])) {
12219
+ if (parts.length > 0 && _optionalChain([lastResponse, 'optionalAccess', _259 => _259.candidates])) {
12106
12220
  const candidates = [];
12107
12221
  for (const candidate of lastResponse.candidates) {
12108
12222
  const candidateDict = {
@@ -12144,6 +12258,1023 @@ function tryToDict(obj) {
12144
12258
  return null;
12145
12259
  }
12146
12260
 
12261
+ // src/instrumentation/plugins/openrouter-channels.ts
12262
+ var openRouterChannels = defineChannels("@openrouter/sdk", {
12263
+ chatSend: channel({
12264
+ channelName: "chat.send",
12265
+ kind: "async"
12266
+ }),
12267
+ embeddingsGenerate: channel({
12268
+ channelName: "embeddings.generate",
12269
+ kind: "async"
12270
+ }),
12271
+ betaResponsesSend: channel({
12272
+ channelName: "beta.responses.send",
12273
+ kind: "async"
12274
+ }),
12275
+ callModel: channel({
12276
+ channelName: "callModel",
12277
+ kind: "sync-stream"
12278
+ }),
12279
+ toolExecute: channel({
12280
+ channelName: "tool.execute",
12281
+ kind: "async"
12282
+ })
12283
+ });
12284
+
12285
+ // src/openrouter-utils.ts
12286
+ var TOKEN_NAME_MAP2 = {
12287
+ promptTokens: "prompt_tokens",
12288
+ inputTokens: "prompt_tokens",
12289
+ completionTokens: "completion_tokens",
12290
+ outputTokens: "completion_tokens",
12291
+ totalTokens: "tokens",
12292
+ prompt_tokens: "prompt_tokens",
12293
+ input_tokens: "prompt_tokens",
12294
+ completion_tokens: "completion_tokens",
12295
+ output_tokens: "completion_tokens",
12296
+ total_tokens: "tokens"
12297
+ };
12298
+ var TOKEN_DETAIL_PREFIX_MAP = {
12299
+ promptTokensDetails: "prompt",
12300
+ inputTokensDetails: "prompt",
12301
+ completionTokensDetails: "completion",
12302
+ outputTokensDetails: "completion",
12303
+ costDetails: "cost",
12304
+ prompt_tokens_details: "prompt",
12305
+ input_tokens_details: "prompt",
12306
+ completion_tokens_details: "completion",
12307
+ output_tokens_details: "completion",
12308
+ cost_details: "cost"
12309
+ };
12310
+ function camelToSnake(value) {
12311
+ return value.replace(/[A-Z]/g, (match) => `_${match.toLowerCase()}`);
12312
+ }
12313
+ function parseOpenRouterMetricsFromUsage(usage) {
12314
+ if (!isObject(usage)) {
12315
+ return {};
12316
+ }
12317
+ const metrics = {};
12318
+ for (const [name, value] of Object.entries(usage)) {
12319
+ if (typeof value === "number") {
12320
+ metrics[TOKEN_NAME_MAP2[name] || camelToSnake(name)] = value;
12321
+ continue;
12322
+ }
12323
+ if (!isObject(value)) {
12324
+ continue;
12325
+ }
12326
+ const prefix = TOKEN_DETAIL_PREFIX_MAP[name];
12327
+ if (!prefix) {
12328
+ continue;
12329
+ }
12330
+ for (const [nestedName, nestedValue] of Object.entries(value)) {
12331
+ if (typeof nestedValue !== "number") {
12332
+ continue;
12333
+ }
12334
+ metrics[`${prefix}_${camelToSnake(nestedName)}`] = nestedValue;
12335
+ }
12336
+ }
12337
+ return metrics;
12338
+ }
12339
+ function extractOpenRouterUsageMetadata(usage) {
12340
+ if (!isObject(usage)) {
12341
+ return void 0;
12342
+ }
12343
+ const metadata = {};
12344
+ if (typeof usage.isByok === "boolean") {
12345
+ metadata.is_byok = usage.isByok;
12346
+ } else if (typeof usage.is_byok === "boolean") {
12347
+ metadata.is_byok = usage.is_byok;
12348
+ }
12349
+ return Object.keys(metadata).length > 0 ? metadata : void 0;
12350
+ }
12351
+
12352
+ // src/openrouter-logging.ts
12353
+ var OMITTED_OPENROUTER_KEYS = /* @__PURE__ */ new Set([
12354
+ "execute",
12355
+ "render",
12356
+ "nextTurnParams",
12357
+ "requireApproval"
12358
+ ]);
12359
+ function parseOpenRouterModelString(model) {
12360
+ if (typeof model !== "string") {
12361
+ return { model };
12362
+ }
12363
+ const slashIndex = model.indexOf("/");
12364
+ if (slashIndex > 0 && slashIndex < model.length - 1) {
12365
+ return {
12366
+ provider: model.substring(0, slashIndex),
12367
+ model: model.substring(slashIndex + 1)
12368
+ };
12369
+ }
12370
+ return { model };
12371
+ }
12372
+ function isZodSchema2(value) {
12373
+ return value != null && typeof value === "object" && "_def" in value && typeof value._def === "object";
12374
+ }
12375
+ function serializeZodSchema2(schema) {
12376
+ try {
12377
+ return zodToJsonSchema(schema);
12378
+ } catch (e27) {
12379
+ return {
12380
+ type: "object",
12381
+ description: "Zod schema (conversion failed)"
12382
+ };
12383
+ }
12384
+ }
12385
+ function serializeOpenRouterTool(tool) {
12386
+ if (!isObject(tool)) {
12387
+ return tool;
12388
+ }
12389
+ const serialized = {};
12390
+ for (const [key, value] of Object.entries(tool)) {
12391
+ if (OMITTED_OPENROUTER_KEYS.has(key)) {
12392
+ continue;
12393
+ }
12394
+ if (key === "function" && isObject(value)) {
12395
+ serialized.function = sanitizeOpenRouterLoggedValue(value);
12396
+ continue;
12397
+ }
12398
+ serialized[key] = sanitizeOpenRouterLoggedValue(value);
12399
+ }
12400
+ return serialized;
12401
+ }
12402
+ function serializeOpenRouterToolsForLogging(tools) {
12403
+ if (!Array.isArray(tools)) {
12404
+ return void 0;
12405
+ }
12406
+ return tools.map((tool) => serializeOpenRouterTool(tool));
12407
+ }
12408
+ function sanitizeOpenRouterLoggedValue(value) {
12409
+ if (isZodSchema2(value)) {
12410
+ return serializeZodSchema2(value);
12411
+ }
12412
+ if (typeof value === "function") {
12413
+ return "[Function]";
12414
+ }
12415
+ if (Array.isArray(value)) {
12416
+ return value.map((entry) => sanitizeOpenRouterLoggedValue(entry));
12417
+ }
12418
+ if (!isObject(value)) {
12419
+ return value;
12420
+ }
12421
+ const sanitized = {};
12422
+ for (const [key, entry] of Object.entries(value)) {
12423
+ if (OMITTED_OPENROUTER_KEYS.has(key)) {
12424
+ continue;
12425
+ }
12426
+ if (key === "tools" && Array.isArray(entry)) {
12427
+ sanitized.tools = serializeOpenRouterToolsForLogging(entry);
12428
+ continue;
12429
+ }
12430
+ sanitized[key] = sanitizeOpenRouterLoggedValue(entry);
12431
+ }
12432
+ return sanitized;
12433
+ }
12434
+ function buildOpenRouterMetadata(metadata, httpReferer, xTitle) {
12435
+ const sanitized = sanitizeOpenRouterLoggedValue(metadata);
12436
+ const metadataRecord = isObject(sanitized) ? sanitized : {};
12437
+ const { model, provider: providerRouting, ...rest } = metadataRecord;
12438
+ const normalizedModel = parseOpenRouterModelString(model);
12439
+ return {
12440
+ ...rest,
12441
+ ...normalizedModel.model !== void 0 ? { model: normalizedModel.model } : {},
12442
+ ...providerRouting !== void 0 ? { providerRouting } : {},
12443
+ ...httpReferer !== void 0 ? { httpReferer } : {},
12444
+ ...xTitle !== void 0 ? { xTitle } : {},
12445
+ provider: normalizedModel.provider || "openrouter"
12446
+ };
12447
+ }
12448
+ function buildOpenRouterEmbeddingMetadata(metadata, httpReferer, xTitle) {
12449
+ const normalized = buildOpenRouterMetadata(metadata, httpReferer, xTitle);
12450
+ return typeof normalized.model === "string" ? {
12451
+ ...normalized,
12452
+ embedding_model: normalized.model
12453
+ } : normalized;
12454
+ }
12455
+ function extractOpenRouterCallModelInput(request) {
12456
+ return isObject(request) && "input" in request ? sanitizeOpenRouterLoggedValue(request.input) : void 0;
12457
+ }
12458
+ function extractOpenRouterCallModelMetadata(request) {
12459
+ if (!isObject(request)) {
12460
+ return { provider: "openrouter" };
12461
+ }
12462
+ const { input: _input, ...metadata } = request;
12463
+ return buildOpenRouterMetadata(metadata, void 0, void 0);
12464
+ }
12465
+ function extractOpenRouterResponseMetadata(result) {
12466
+ if (!isObject(result)) {
12467
+ return void 0;
12468
+ }
12469
+ const { output: _output, data: _data, usage, ...metadata } = result;
12470
+ const sanitized = sanitizeOpenRouterLoggedValue(metadata);
12471
+ const metadataRecord = isObject(sanitized) ? sanitized : {};
12472
+ const { model, provider, ...rest } = metadataRecord;
12473
+ const normalizedModel = parseOpenRouterModelString(model);
12474
+ const normalizedProvider = (typeof provider === "string" ? provider : void 0) || normalizedModel.provider;
12475
+ const usageMetadata = extractOpenRouterUsageMetadata(usage);
12476
+ const combined = {
12477
+ ...rest,
12478
+ ...normalizedModel.model !== void 0 ? { model: normalizedModel.model } : {},
12479
+ ...usageMetadata || {},
12480
+ ...normalizedProvider !== void 0 ? { provider: normalizedProvider } : {}
12481
+ };
12482
+ return Object.keys(combined).length > 0 ? combined : void 0;
12483
+ }
12484
+ function extractOpenRouterResponseOutput(response, fallbackOutput) {
12485
+ if (isObject(response) && "output" in response && response.output !== void 0) {
12486
+ return sanitizeOpenRouterLoggedValue(response.output);
12487
+ }
12488
+ if (fallbackOutput !== void 0) {
12489
+ return sanitizeOpenRouterLoggedValue(fallbackOutput);
12490
+ }
12491
+ return void 0;
12492
+ }
12493
+
12494
+ // src/openrouter-tool-wrapping.ts
12495
+ var OPENROUTER_WRAPPED_TOOL = Symbol("braintrust.openrouter.wrappedTool");
12496
+ var OPENROUTER_WRAPPED_CALL_MODEL_RESULT = Symbol(
12497
+ "braintrust.openrouter.wrappedCallModelResult"
12498
+ );
12499
+ var OPENROUTER_CALL_MODEL_STREAM_METHODS = [
12500
+ "getFullResponsesStream",
12501
+ "getItemsStream",
12502
+ "getNewMessagesStream",
12503
+ "getReasoningStream",
12504
+ "getTextStream",
12505
+ "getToolCallsStream",
12506
+ "getToolStream"
12507
+ ];
12508
+ var OPENROUTER_CALL_MODEL_CONTEXT_METHODS = [
12509
+ "cancel",
12510
+ "getPendingToolCalls",
12511
+ "getState",
12512
+ "getToolCalls",
12513
+ "requiresApproval"
12514
+ ];
12515
+ function patchOpenRouterCallModelRequestTools(request) {
12516
+ if (!Array.isArray(request.tools) || request.tools.length === 0) {
12517
+ return void 0;
12518
+ }
12519
+ const originalTools = request.tools;
12520
+ const wrappedTools = originalTools.map((tool) => wrapOpenRouterTool(tool));
12521
+ const didPatch = wrappedTools.some(
12522
+ (tool, index) => tool !== originalTools[index]
12523
+ );
12524
+ if (!didPatch) {
12525
+ return void 0;
12526
+ }
12527
+ request.tools = wrappedTools;
12528
+ return () => {
12529
+ request.tools = originalTools;
12530
+ };
12531
+ }
12532
+ function patchOpenRouterCallModelResult(span, result, request) {
12533
+ if (!isObject(result) || isWrappedCallModelResult(result)) {
12534
+ return false;
12535
+ }
12536
+ const resultLike = result;
12537
+ const hasInstrumentableMethod = typeof resultLike.getResponse === "function" || typeof resultLike.getText === "function" || OPENROUTER_CALL_MODEL_STREAM_METHODS.some(
12538
+ (methodName) => typeof resultLike[methodName] === "function"
12539
+ );
12540
+ if (!hasInstrumentableMethod) {
12541
+ return false;
12542
+ }
12543
+ Object.defineProperty(resultLike, OPENROUTER_WRAPPED_CALL_MODEL_RESULT, {
12544
+ value: true,
12545
+ enumerable: false,
12546
+ configurable: false
12547
+ });
12548
+ const originalGetResponse = typeof resultLike.getResponse === "function" ? resultLike.getResponse.bind(resultLike) : void 0;
12549
+ const originalGetInitialResponse = typeof resultLike.getInitialResponse === "function" ? resultLike.getInitialResponse.bind(resultLike) : void 0;
12550
+ const originalMakeFollowupRequest = typeof resultLike.makeFollowupRequest === "function" ? resultLike.makeFollowupRequest.bind(resultLike) : void 0;
12551
+ let ended = false;
12552
+ let tracedTurnCount = 0;
12553
+ const endSpanWithResult = async (response, fallbackOutput) => {
12554
+ if (ended) {
12555
+ return;
12556
+ }
12557
+ ended = true;
12558
+ const finalResponse = getFinalOpenRouterCallModelResponse(
12559
+ resultLike,
12560
+ response
12561
+ );
12562
+ if (finalResponse) {
12563
+ const rounds = getOpenRouterCallModelRounds(resultLike);
12564
+ const metadata = extractOpenRouterCallModelResultMetadata(
12565
+ finalResponse,
12566
+ rounds.length + 1
12567
+ );
12568
+ span.log({
12569
+ output: extractOpenRouterResponseOutput(finalResponse, fallbackOutput),
12570
+ ...metadata ? { metadata } : {},
12571
+ metrics: aggregateOpenRouterCallModelMetrics(rounds, finalResponse)
12572
+ });
12573
+ span.end();
12574
+ return;
12575
+ }
12576
+ if (fallbackOutput !== void 0) {
12577
+ span.log({
12578
+ output: fallbackOutput
12579
+ });
12580
+ }
12581
+ span.end();
12582
+ };
12583
+ const endSpanWithError = (error) => {
12584
+ if (ended) {
12585
+ return;
12586
+ }
12587
+ ended = true;
12588
+ span.log({
12589
+ error: normalizeError(error).message
12590
+ });
12591
+ span.end();
12592
+ };
12593
+ const finalizeFromResponse = async (fallbackOutput) => {
12594
+ if (!originalGetResponse) {
12595
+ await endSpanWithResult(void 0, fallbackOutput);
12596
+ return;
12597
+ }
12598
+ try {
12599
+ await endSpanWithResult(await originalGetResponse(), fallbackOutput);
12600
+ } catch (e28) {
12601
+ await endSpanWithResult(void 0, fallbackOutput);
12602
+ }
12603
+ };
12604
+ if (originalGetResponse) {
12605
+ resultLike.getResponse = async (...args) => {
12606
+ return await withCurrent(span, async () => {
12607
+ try {
12608
+ const response = await originalGetResponse(...args);
12609
+ await endSpanWithResult(response);
12610
+ return response;
12611
+ } catch (error) {
12612
+ endSpanWithError(error);
12613
+ throw error;
12614
+ }
12615
+ });
12616
+ };
12617
+ }
12618
+ if (typeof resultLike.getText === "function") {
12619
+ const originalGetText = resultLike.getText.bind(resultLike);
12620
+ resultLike.getText = async (...args) => {
12621
+ return await withCurrent(span, async () => {
12622
+ try {
12623
+ const text = await originalGetText(...args);
12624
+ await finalizeFromResponse(text);
12625
+ return text;
12626
+ } catch (error) {
12627
+ endSpanWithError(error);
12628
+ throw error;
12629
+ }
12630
+ });
12631
+ };
12632
+ }
12633
+ for (const methodName of OPENROUTER_CALL_MODEL_CONTEXT_METHODS) {
12634
+ if (typeof resultLike[methodName] !== "function") {
12635
+ continue;
12636
+ }
12637
+ const originalMethod = resultLike[methodName];
12638
+ resultLike[methodName] = async (...args) => {
12639
+ return await withCurrent(span, async () => {
12640
+ return await originalMethod.apply(resultLike, args);
12641
+ });
12642
+ };
12643
+ }
12644
+ for (const methodName of OPENROUTER_CALL_MODEL_STREAM_METHODS) {
12645
+ if (typeof resultLike[methodName] !== "function") {
12646
+ continue;
12647
+ }
12648
+ const originalMethod = resultLike[methodName];
12649
+ resultLike[methodName] = (...args) => {
12650
+ const stream = withCurrent(
12651
+ span,
12652
+ () => originalMethod.apply(resultLike, args)
12653
+ );
12654
+ if (!isAsyncIterable2(stream)) {
12655
+ return stream;
12656
+ }
12657
+ return wrapAsyncIterableWithSpan({
12658
+ finalize: finalizeFromResponse,
12659
+ iteratorFactory: () => stream[Symbol.asyncIterator](),
12660
+ onError: endSpanWithError,
12661
+ span
12662
+ });
12663
+ };
12664
+ }
12665
+ if (originalGetInitialResponse) {
12666
+ let initialTurnTraced = false;
12667
+ resultLike.getInitialResponse = async (...args) => {
12668
+ if (initialTurnTraced) {
12669
+ return await withCurrent(span, async () => {
12670
+ return await originalGetInitialResponse(...args);
12671
+ });
12672
+ }
12673
+ initialTurnTraced = true;
12674
+ const resolvedRequest = getOpenRouterResolvedRequest(resultLike, request);
12675
+ const childSpan = startOpenRouterCallModelTurnSpan({
12676
+ request: resolvedRequest,
12677
+ step: tracedTurnCount + 1,
12678
+ stepType: tracedTurnCount === 0 ? "initial" : "continue"
12679
+ });
12680
+ return await withCurrent(childSpan, async () => {
12681
+ try {
12682
+ const response = await originalGetInitialResponse(...args);
12683
+ tracedTurnCount++;
12684
+ finishOpenRouterCallModelTurnSpan({
12685
+ response,
12686
+ step: tracedTurnCount,
12687
+ stepType: tracedTurnCount === 1 ? "initial" : "continue",
12688
+ span: childSpan
12689
+ });
12690
+ return response;
12691
+ } catch (error) {
12692
+ childSpan.log({
12693
+ error: normalizeError(error).message
12694
+ });
12695
+ childSpan.end();
12696
+ throw error;
12697
+ }
12698
+ });
12699
+ };
12700
+ }
12701
+ if (originalMakeFollowupRequest) {
12702
+ resultLike.makeFollowupRequest = async (...args) => {
12703
+ const currentResponse = args[0];
12704
+ const toolResults = Array.isArray(args[1]) ? args[1] : [];
12705
+ const resolvedRequest = getOpenRouterResolvedRequest(resultLike, request);
12706
+ const followupRequest = buildOpenRouterFollowupRequest(
12707
+ resolvedRequest,
12708
+ currentResponse,
12709
+ toolResults
12710
+ );
12711
+ const childSpan = startOpenRouterCallModelTurnSpan({
12712
+ request: followupRequest,
12713
+ step: tracedTurnCount + 1,
12714
+ stepType: "continue"
12715
+ });
12716
+ return await withCurrent(childSpan, async () => {
12717
+ try {
12718
+ const response = await originalMakeFollowupRequest(...args);
12719
+ tracedTurnCount++;
12720
+ finishOpenRouterCallModelTurnSpan({
12721
+ response,
12722
+ step: tracedTurnCount,
12723
+ stepType: "continue",
12724
+ span: childSpan
12725
+ });
12726
+ return response;
12727
+ } catch (error) {
12728
+ childSpan.log({
12729
+ error: normalizeError(error).message
12730
+ });
12731
+ childSpan.end();
12732
+ throw error;
12733
+ }
12734
+ });
12735
+ };
12736
+ }
12737
+ return true;
12738
+ }
12739
+ function wrapOpenRouterTool(tool) {
12740
+ if (isWrappedTool(tool) || !tool.function || typeof tool.function !== "object" || typeof tool.function.execute !== "function") {
12741
+ return tool;
12742
+ }
12743
+ const toolName = tool.function.name || "tool";
12744
+ const originalExecute = tool.function.execute;
12745
+ const wrappedTool = {
12746
+ ...tool,
12747
+ function: {
12748
+ ...tool.function,
12749
+ execute(...args) {
12750
+ return traceToolExecution({
12751
+ args,
12752
+ execute: () => Reflect.apply(originalExecute, this, args),
12753
+ toolCallId: getToolCallId(args[1]),
12754
+ toolName
12755
+ });
12756
+ }
12757
+ }
12758
+ };
12759
+ Object.defineProperty(wrappedTool, OPENROUTER_WRAPPED_TOOL, {
12760
+ value: true,
12761
+ enumerable: false,
12762
+ configurable: false
12763
+ });
12764
+ return wrappedTool;
12765
+ }
12766
+ function isWrappedTool(tool) {
12767
+ return Boolean(tool[OPENROUTER_WRAPPED_TOOL]);
12768
+ }
12769
+ function isWrappedCallModelResult(value) {
12770
+ return Boolean(
12771
+ isObject(value) && value[OPENROUTER_WRAPPED_CALL_MODEL_RESULT]
12772
+ );
12773
+ }
12774
+ function traceToolExecution(args) {
12775
+ const tracingChannel2 = openRouterChannels.toolExecute.tracingChannel();
12776
+ const input = args.args.length > 0 ? args.args[0] : void 0;
12777
+ const event = {
12778
+ arguments: [input],
12779
+ span_info: {
12780
+ name: args.toolName
12781
+ },
12782
+ toolCallId: args.toolCallId,
12783
+ toolName: args.toolName
12784
+ };
12785
+ tracingChannel2.start.publish(event);
12786
+ try {
12787
+ const result = args.execute();
12788
+ return publishToolResult(tracingChannel2, event, result);
12789
+ } catch (error) {
12790
+ event.error = normalizeError(error);
12791
+ tracingChannel2.error.publish(event);
12792
+ throw error;
12793
+ }
12794
+ }
12795
+ function publishToolResult(tracingChannel2, event, result) {
12796
+ if (isPromiseLike(result)) {
12797
+ return result.then(
12798
+ (resolved) => {
12799
+ event.result = resolved;
12800
+ tracingChannel2.asyncEnd.publish(event);
12801
+ return resolved;
12802
+ },
12803
+ (error) => {
12804
+ event.error = normalizeError(error);
12805
+ tracingChannel2.error.publish(event);
12806
+ throw error;
12807
+ }
12808
+ );
12809
+ }
12810
+ event.result = result;
12811
+ tracingChannel2.asyncEnd.publish(event);
12812
+ return result;
12813
+ }
12814
+ function getToolCallId(context) {
12815
+ const toolContext = context;
12816
+ return typeof _optionalChain([toolContext, 'optionalAccess', _260 => _260.toolCall, 'optionalAccess', _261 => _261.id]) === "string" ? toolContext.toolCall.id : void 0;
12817
+ }
12818
+ function extractOpenRouterCallModelResultMetadata(response, turnCount) {
12819
+ const combined = {
12820
+ ...extractOpenRouterResponseMetadata(response) || {},
12821
+ ...turnCount !== void 0 ? { turn_count: turnCount } : {}
12822
+ };
12823
+ return Object.keys(combined).length > 0 ? combined : void 0;
12824
+ }
12825
+ function getFinalOpenRouterCallModelResponse(result, response) {
12826
+ if (isObject(response)) {
12827
+ return response;
12828
+ }
12829
+ return isObject(result.finalResponse) ? result.finalResponse : void 0;
12830
+ }
12831
+ function getOpenRouterCallModelRounds(result) {
12832
+ if (!Array.isArray(result.allToolExecutionRounds)) {
12833
+ return [];
12834
+ }
12835
+ return result.allToolExecutionRounds.filter((round) => isObject(round)).map((round) => ({
12836
+ response: isObject(round.response) ? round.response : void 0,
12837
+ round: typeof round.round === "number" ? round.round : void 0,
12838
+ toolResults: Array.isArray(round.toolResults) ? round.toolResults : []
12839
+ })).filter((round) => round.response !== void 0);
12840
+ }
12841
+ function aggregateOpenRouterCallModelMetrics(rounds, finalResponse) {
12842
+ const metrics = {};
12843
+ const responses = [
12844
+ ...rounds.map((round) => round.response).filter(isObject),
12845
+ finalResponse
12846
+ ];
12847
+ for (const response of responses) {
12848
+ const responseMetrics = parseOpenRouterMetricsFromUsage(response.usage);
12849
+ for (const [name, value] of Object.entries(responseMetrics)) {
12850
+ metrics[name] = (metrics[name] || 0) + value;
12851
+ }
12852
+ }
12853
+ return metrics;
12854
+ }
12855
+ function buildNextOpenRouterCallModelInput(currentInput, response, toolResults) {
12856
+ const normalizedInput = Array.isArray(currentInput) ? [...currentInput] : currentInput === void 0 ? [] : [currentInput];
12857
+ const responseOutput = Array.isArray(response.output) ? response.output : response.output === void 0 ? [] : [response.output];
12858
+ return [...normalizedInput, ...responseOutput, ...toolResults].map(
12859
+ (entry) => sanitizeOpenRouterLoggedValue(entry)
12860
+ );
12861
+ }
12862
+ function startOpenRouterCallModelTurnSpan(args) {
12863
+ const requestRecord = isObject(args.request) ? args.request : void 0;
12864
+ const metadata = requestRecord ? extractOpenRouterCallModelMetadata(requestRecord) : { provider: "openrouter" };
12865
+ if (isObject(metadata) && "tools" in metadata) {
12866
+ delete metadata.tools;
12867
+ }
12868
+ return startSpan({
12869
+ name: "openrouter.beta.responses.send",
12870
+ spanAttributes: {
12871
+ type: "llm" /* LLM */
12872
+ },
12873
+ event: {
12874
+ input: requestRecord ? extractOpenRouterCallModelInput(requestRecord) : void 0,
12875
+ metadata: {
12876
+ ...metadata,
12877
+ step: args.step,
12878
+ step_type: args.stepType
12879
+ }
12880
+ }
12881
+ });
12882
+ }
12883
+ function finishOpenRouterCallModelTurnSpan(args) {
12884
+ if (!isObject(args.response)) {
12885
+ args.span.end();
12886
+ return;
12887
+ }
12888
+ args.span.log({
12889
+ output: extractOpenRouterResponseOutput(args.response),
12890
+ ...extractOpenRouterResponseMetadata(args.response) ? {
12891
+ metadata: {
12892
+ ...extractOpenRouterResponseMetadata(args.response),
12893
+ ...args.step !== void 0 ? { step: args.step } : {},
12894
+ ...args.stepType ? { step_type: args.stepType } : {}
12895
+ }
12896
+ } : {},
12897
+ metrics: parseOpenRouterMetricsFromUsage(args.response.usage)
12898
+ });
12899
+ args.span.end();
12900
+ }
12901
+ function getOpenRouterResolvedRequest(result, request) {
12902
+ if (isObject(result.resolvedRequest)) {
12903
+ return result.resolvedRequest;
12904
+ }
12905
+ return request;
12906
+ }
12907
+ function buildOpenRouterFollowupRequest(request, currentResponse, toolResults) {
12908
+ if (!request) {
12909
+ return void 0;
12910
+ }
12911
+ return {
12912
+ ...request,
12913
+ input: buildNextOpenRouterCallModelInput(
12914
+ extractOpenRouterCallModelInput(request),
12915
+ isObject(currentResponse) ? currentResponse : {},
12916
+ toolResults
12917
+ ),
12918
+ stream: false
12919
+ };
12920
+ }
12921
+ function wrapAsyncIterableWithSpan(args) {
12922
+ return {
12923
+ [Symbol.asyncIterator]() {
12924
+ const iterator = args.iteratorFactory();
12925
+ return {
12926
+ next(value) {
12927
+ return withCurrent(
12928
+ args.span,
12929
+ () => value === void 0 ? iterator.next() : iterator.next(value)
12930
+ ).then(
12931
+ async (result) => {
12932
+ if (result.done) {
12933
+ await args.finalize();
12934
+ }
12935
+ return result;
12936
+ },
12937
+ (error) => {
12938
+ args.onError(error);
12939
+ throw error;
12940
+ }
12941
+ );
12942
+ },
12943
+ return(value) {
12944
+ if (typeof iterator.return !== "function") {
12945
+ return args.finalize().then(() => ({
12946
+ done: true,
12947
+ value
12948
+ }));
12949
+ }
12950
+ return withCurrent(args.span, () => iterator.return(value)).then(
12951
+ async (result) => {
12952
+ await args.finalize();
12953
+ return result;
12954
+ },
12955
+ (error) => {
12956
+ args.onError(error);
12957
+ throw error;
12958
+ }
12959
+ );
12960
+ },
12961
+ throw(error) {
12962
+ args.onError(error);
12963
+ if (typeof iterator.throw !== "function") {
12964
+ return Promise.reject(error);
12965
+ }
12966
+ return withCurrent(args.span, () => iterator.throw(error));
12967
+ },
12968
+ [Symbol.asyncIterator]() {
12969
+ return this;
12970
+ }
12971
+ };
12972
+ }
12973
+ };
12974
+ }
12975
+ function isAsyncIterable2(value) {
12976
+ return !!value && (typeof value === "object" || typeof value === "function") && Symbol.asyncIterator in value && typeof value[Symbol.asyncIterator] === "function";
12977
+ }
12978
+ function isPromiseLike(value) {
12979
+ return !!value && (typeof value === "object" || typeof value === "function") && "then" in value && typeof value.then === "function";
12980
+ }
12981
+ function normalizeError(error) {
12982
+ return error instanceof Error ? error : new Error(String(error));
12983
+ }
12984
+
12985
+ // src/instrumentation/plugins/openrouter-plugin.ts
12986
+ var OpenRouterPlugin = class extends BasePlugin {
12987
+ onEnable() {
12988
+ this.subscribeToOpenRouterChannels();
12989
+ }
12990
+ onDisable() {
12991
+ this.unsubscribers = unsubscribeAll(this.unsubscribers);
12992
+ }
12993
+ subscribeToOpenRouterChannels() {
12994
+ this.unsubscribers.push(
12995
+ traceStreamingChannel(openRouterChannels.chatSend, {
12996
+ name: "openrouter.chat.send",
12997
+ type: "llm" /* LLM */,
12998
+ extractInput: (args) => {
12999
+ const request = getOpenRouterRequestArg(args);
13000
+ const chatGenerationParams = isObject(_optionalChain([request, 'optionalAccess', _262 => _262.chatGenerationParams])) ? request.chatGenerationParams : {};
13001
+ const httpReferer = _optionalChain([request, 'optionalAccess', _263 => _263.httpReferer]);
13002
+ const xTitle = _optionalChain([request, 'optionalAccess', _264 => _264.xTitle]);
13003
+ const { messages, ...metadata } = chatGenerationParams;
13004
+ return {
13005
+ input: messages,
13006
+ metadata: buildOpenRouterMetadata(metadata, httpReferer, xTitle)
13007
+ };
13008
+ },
13009
+ extractOutput: (result) => {
13010
+ return isObject(result) ? result.choices : void 0;
13011
+ },
13012
+ extractMetrics: (result, startTime) => {
13013
+ const metrics = parseOpenRouterMetricsFromUsage(_optionalChain([result, 'optionalAccess', _265 => _265.usage]));
13014
+ if (startTime) {
13015
+ metrics.time_to_first_token = getCurrentUnixTimestamp() - startTime;
13016
+ }
13017
+ return metrics;
13018
+ },
13019
+ aggregateChunks: aggregateOpenRouterChatChunks
13020
+ })
13021
+ );
13022
+ this.unsubscribers.push(
13023
+ traceAsyncChannel(openRouterChannels.embeddingsGenerate, {
13024
+ name: "openrouter.embeddings.generate",
13025
+ type: "llm" /* LLM */,
13026
+ extractInput: (args) => {
13027
+ const request = getOpenRouterRequestArg(args);
13028
+ const requestBody = isObject(_optionalChain([request, 'optionalAccess', _266 => _266.requestBody])) ? request.requestBody : {};
13029
+ const httpReferer = _optionalChain([request, 'optionalAccess', _267 => _267.httpReferer]);
13030
+ const xTitle = _optionalChain([request, 'optionalAccess', _268 => _268.xTitle]);
13031
+ const { input, ...metadata } = requestBody;
13032
+ return {
13033
+ input,
13034
+ metadata: buildOpenRouterEmbeddingMetadata(
13035
+ metadata,
13036
+ httpReferer,
13037
+ xTitle
13038
+ )
13039
+ };
13040
+ },
13041
+ extractOutput: (result) => {
13042
+ if (!isObject(result)) {
13043
+ return void 0;
13044
+ }
13045
+ const embedding = _optionalChain([result, 'access', _269 => _269.data, 'optionalAccess', _270 => _270[0], 'optionalAccess', _271 => _271.embedding]);
13046
+ return Array.isArray(embedding) ? { embedding_length: embedding.length } : void 0;
13047
+ },
13048
+ extractMetadata: (result) => {
13049
+ if (!isObject(result)) {
13050
+ return void 0;
13051
+ }
13052
+ return extractOpenRouterResponseMetadata(result);
13053
+ },
13054
+ extractMetrics: (result) => {
13055
+ return isObject(result) ? parseOpenRouterMetricsFromUsage(result.usage) : {};
13056
+ }
13057
+ })
13058
+ );
13059
+ this.unsubscribers.push(
13060
+ traceStreamingChannel(openRouterChannels.betaResponsesSend, {
13061
+ name: "openrouter.beta.responses.send",
13062
+ type: "llm" /* LLM */,
13063
+ extractInput: (args) => {
13064
+ const request = getOpenRouterRequestArg(args);
13065
+ const openResponsesRequest = isObject(_optionalChain([request, 'optionalAccess', _272 => _272.openResponsesRequest])) ? request.openResponsesRequest : {};
13066
+ const httpReferer = _optionalChain([request, 'optionalAccess', _273 => _273.httpReferer]);
13067
+ const xTitle = _optionalChain([request, 'optionalAccess', _274 => _274.xTitle]);
13068
+ const { input, ...metadata } = openResponsesRequest;
13069
+ return {
13070
+ input,
13071
+ metadata: buildOpenRouterMetadata(metadata, httpReferer, xTitle)
13072
+ };
13073
+ },
13074
+ extractOutput: (result) => extractOpenRouterResponseOutput(result),
13075
+ extractMetadata: (result) => extractOpenRouterResponseMetadata(result),
13076
+ extractMetrics: (result, startTime) => {
13077
+ const metrics = parseOpenRouterMetricsFromUsage(_optionalChain([result, 'optionalAccess', _275 => _275.usage]));
13078
+ if (startTime) {
13079
+ metrics.time_to_first_token = getCurrentUnixTimestamp() - startTime;
13080
+ }
13081
+ return metrics;
13082
+ },
13083
+ aggregateChunks: aggregateOpenRouterResponseStreamEvents
13084
+ })
13085
+ );
13086
+ this.unsubscribers.push(
13087
+ traceSyncStreamChannel(openRouterChannels.callModel, {
13088
+ name: "openrouter.callModel",
13089
+ type: "llm" /* LLM */,
13090
+ extractInput: (args) => {
13091
+ const request = getOpenRouterCallModelRequestArg(args);
13092
+ return {
13093
+ input: request ? extractOpenRouterCallModelInput(request) : void 0,
13094
+ metadata: request ? extractOpenRouterCallModelMetadata(request) : { provider: "openrouter" }
13095
+ };
13096
+ },
13097
+ patchResult: ({ endEvent, result, span }) => {
13098
+ return patchOpenRouterCallModelResult(
13099
+ span,
13100
+ result,
13101
+ getOpenRouterCallModelRequestArg(endEvent.arguments)
13102
+ );
13103
+ }
13104
+ })
13105
+ );
13106
+ this.unsubscribers.push(
13107
+ traceStreamingChannel(openRouterChannels.toolExecute, {
13108
+ name: "openrouter.tool",
13109
+ type: "tool" /* TOOL */,
13110
+ extractInput: (args, event) => ({
13111
+ input: args[0],
13112
+ metadata: {
13113
+ provider: "openrouter",
13114
+ tool_name: event.toolName,
13115
+ ...event.toolCallId ? { tool_call_id: event.toolCallId } : {}
13116
+ }
13117
+ }),
13118
+ extractOutput: (result) => result,
13119
+ extractMetrics: () => ({}),
13120
+ aggregateChunks: (chunks) => ({
13121
+ output: chunks.length > 0 ? chunks[chunks.length - 1] : void 0,
13122
+ metrics: {}
13123
+ })
13124
+ })
13125
+ );
13126
+ const callModelChannel = openRouterChannels.callModel.tracingChannel();
13127
+ const callModelHandlers = {
13128
+ start: (event) => {
13129
+ const request = getOpenRouterCallModelRequestArg(event.arguments);
13130
+ if (!request) {
13131
+ return;
13132
+ }
13133
+ patchOpenRouterCallModelRequestTools(request);
13134
+ }
13135
+ };
13136
+ callModelChannel.subscribe(callModelHandlers);
13137
+ this.unsubscribers.push(() => {
13138
+ callModelChannel.unsubscribe(callModelHandlers);
13139
+ });
13140
+ }
13141
+ };
13142
+ function normalizeArgs(args) {
13143
+ if (Array.isArray(args)) {
13144
+ return args;
13145
+ }
13146
+ if (isArrayLike(args)) {
13147
+ return Array.from(args);
13148
+ }
13149
+ return [args];
13150
+ }
13151
+ function isArrayLike(value) {
13152
+ return isObject(value) && "length" in value && typeof value.length === "number" && Number.isInteger(value.length) && value.length >= 0;
13153
+ }
13154
+ function getOpenRouterRequestArg(args) {
13155
+ const normalizedArgs = normalizeArgs(args);
13156
+ const keyedCandidate = normalizedArgs.find(
13157
+ (arg) => isObject(arg) && ("chatGenerationParams" in arg || "requestBody" in arg || "openResponsesRequest" in arg)
13158
+ );
13159
+ if (isObject(keyedCandidate)) {
13160
+ return keyedCandidate;
13161
+ }
13162
+ const firstObjectArg = normalizedArgs.find((arg) => isObject(arg));
13163
+ return isObject(firstObjectArg) ? firstObjectArg : void 0;
13164
+ }
13165
+ function getOpenRouterCallModelRequestArg(args) {
13166
+ const firstObjectArg = normalizeArgs(args).find((arg) => isObject(arg));
13167
+ return isObject(firstObjectArg) ? firstObjectArg : void 0;
13168
+ }
13169
+ function aggregateOpenRouterChatChunks(chunks) {
13170
+ let role;
13171
+ let content = "";
13172
+ let toolCalls;
13173
+ let finishReason;
13174
+ let metrics = {};
13175
+ for (const chunk of chunks) {
13176
+ metrics = {
13177
+ ...metrics,
13178
+ ...parseOpenRouterMetricsFromUsage(_optionalChain([chunk, 'optionalAccess', _276 => _276.usage]))
13179
+ };
13180
+ const choice = _optionalChain([chunk, 'optionalAccess', _277 => _277.choices, 'optionalAccess', _278 => _278[0]]);
13181
+ const delta = _optionalChain([choice, 'optionalAccess', _279 => _279.delta]);
13182
+ if (!delta) {
13183
+ if (_optionalChain([choice, 'optionalAccess', _280 => _280.finish_reason]) !== void 0) {
13184
+ finishReason = choice.finish_reason;
13185
+ }
13186
+ continue;
13187
+ }
13188
+ if (!role && delta.role) {
13189
+ role = delta.role;
13190
+ }
13191
+ if (typeof delta.content === "string") {
13192
+ content += delta.content;
13193
+ }
13194
+ const choiceFinishReason = _nullishCoalesce(_nullishCoalesce(_optionalChain([choice, 'optionalAccess', _281 => _281.finishReason]), () => ( _optionalChain([choice, 'optionalAccess', _282 => _282.finish_reason]))), () => ( void 0));
13195
+ const deltaFinishReason = _nullishCoalesce(_nullishCoalesce(delta.finishReason, () => ( delta.finish_reason)), () => ( void 0));
13196
+ if (choiceFinishReason !== void 0) {
13197
+ finishReason = choiceFinishReason;
13198
+ } else if (deltaFinishReason !== void 0) {
13199
+ finishReason = deltaFinishReason;
13200
+ }
13201
+ const toolCallDeltas = Array.isArray(delta.toolCalls) ? delta.toolCalls : Array.isArray(delta.tool_calls) ? delta.tool_calls : void 0;
13202
+ if (!toolCallDeltas) {
13203
+ continue;
13204
+ }
13205
+ for (const toolDelta of toolCallDeltas) {
13206
+ if (!_optionalChain([toolDelta, 'optionalAccess', _283 => _283.function])) {
13207
+ continue;
13208
+ }
13209
+ const toolIndex = _nullishCoalesce(toolDelta.index, () => ( 0));
13210
+ const existingToolCall = _optionalChain([toolCalls, 'optionalAccess', _284 => _284[toolIndex]]);
13211
+ if (!existingToolCall || toolDelta.id && existingToolCall.id !== void 0 && existingToolCall.id !== toolDelta.id) {
13212
+ const nextToolCalls = [...toolCalls || []];
13213
+ nextToolCalls[toolIndex] = {
13214
+ index: toolIndex,
13215
+ id: toolDelta.id,
13216
+ type: toolDelta.type,
13217
+ function: {
13218
+ name: toolDelta.function.name,
13219
+ arguments: toolDelta.function.arguments || ""
13220
+ }
13221
+ };
13222
+ toolCalls = nextToolCalls;
13223
+ continue;
13224
+ }
13225
+ const current = existingToolCall;
13226
+ if (toolDelta.id && !current.id) {
13227
+ current.id = toolDelta.id;
13228
+ }
13229
+ if (toolDelta.type && !current.type) {
13230
+ current.type = toolDelta.type;
13231
+ }
13232
+ if (toolDelta.function.name && !current.function.name) {
13233
+ current.function.name = toolDelta.function.name;
13234
+ }
13235
+ current.function.arguments += toolDelta.function.arguments || "";
13236
+ }
13237
+ }
13238
+ return {
13239
+ output: [
13240
+ {
13241
+ index: 0,
13242
+ message: {
13243
+ role,
13244
+ content: content || void 0,
13245
+ ...toolCalls ? { tool_calls: toolCalls } : {}
13246
+ },
13247
+ logprobs: null,
13248
+ finish_reason: finishReason
13249
+ }
13250
+ ],
13251
+ metrics
13252
+ };
13253
+ }
13254
+ function aggregateOpenRouterResponseStreamEvents(chunks) {
13255
+ let finalResponse;
13256
+ for (const chunk of chunks) {
13257
+ const response = _optionalChain([chunk, 'optionalAccess', _285 => _285.response]);
13258
+ if (!response) {
13259
+ continue;
13260
+ }
13261
+ if (chunk.type === "response.completed" || chunk.type === "response.incomplete" || chunk.type === "response.failed") {
13262
+ finalResponse = response;
13263
+ }
13264
+ }
13265
+ if (!finalResponse) {
13266
+ return {
13267
+ output: void 0,
13268
+ metrics: {}
13269
+ };
13270
+ }
13271
+ return {
13272
+ output: extractOpenRouterResponseOutput(finalResponse),
13273
+ metrics: parseOpenRouterMetricsFromUsage(finalResponse.usage),
13274
+ ...extractOpenRouterResponseMetadata(finalResponse) ? { metadata: extractOpenRouterResponseMetadata(finalResponse) } : {}
13275
+ };
13276
+ }
13277
+
12147
13278
  // src/instrumentation/braintrust-plugin.ts
12148
13279
  var BraintrustPlugin = (_class18 = class extends BasePlugin {
12149
13280
 
@@ -12152,8 +13283,9 @@ var BraintrustPlugin = (_class18 = class extends BasePlugin {
12152
13283
  __init66() {this.aiSDKPlugin = null}
12153
13284
  __init67() {this.claudeAgentSDKPlugin = null}
12154
13285
  __init68() {this.googleGenAIPlugin = null}
13286
+ __init69() {this.openRouterPlugin = null}
12155
13287
  constructor(config = {}) {
12156
- super();_class18.prototype.__init64.call(this);_class18.prototype.__init65.call(this);_class18.prototype.__init66.call(this);_class18.prototype.__init67.call(this);_class18.prototype.__init68.call(this);;
13288
+ super();_class18.prototype.__init64.call(this);_class18.prototype.__init65.call(this);_class18.prototype.__init66.call(this);_class18.prototype.__init67.call(this);_class18.prototype.__init68.call(this);_class18.prototype.__init69.call(this);;
12157
13289
  this.config = config;
12158
13290
  }
12159
13291
  onEnable() {
@@ -12178,6 +13310,10 @@ var BraintrustPlugin = (_class18 = class extends BasePlugin {
12178
13310
  this.googleGenAIPlugin = new GoogleGenAIPlugin();
12179
13311
  this.googleGenAIPlugin.enable();
12180
13312
  }
13313
+ if (integrations.openrouter !== false) {
13314
+ this.openRouterPlugin = new OpenRouterPlugin();
13315
+ this.openRouterPlugin.enable();
13316
+ }
12181
13317
  }
12182
13318
  onDisable() {
12183
13319
  if (this.openaiPlugin) {
@@ -12200,14 +13336,18 @@ var BraintrustPlugin = (_class18 = class extends BasePlugin {
12200
13336
  this.googleGenAIPlugin.disable();
12201
13337
  this.googleGenAIPlugin = null;
12202
13338
  }
13339
+ if (this.openRouterPlugin) {
13340
+ this.openRouterPlugin.disable();
13341
+ this.openRouterPlugin = null;
13342
+ }
12203
13343
  }
12204
13344
  }, _class18);
12205
13345
 
12206
13346
  // src/instrumentation/registry.ts
12207
- var PluginRegistry = (_class19 = class {constructor() { _class19.prototype.__init69.call(this);_class19.prototype.__init70.call(this);_class19.prototype.__init71.call(this); }
12208
- __init69() {this.braintrustPlugin = null}
12209
- __init70() {this.config = {}}
12210
- __init71() {this.enabled = false}
13347
+ var PluginRegistry = (_class19 = class {constructor() { _class19.prototype.__init70.call(this);_class19.prototype.__init71.call(this);_class19.prototype.__init72.call(this); }
13348
+ __init70() {this.braintrustPlugin = null}
13349
+ __init71() {this.config = {}}
13350
+ __init72() {this.enabled = false}
12211
13351
  /**
12212
13352
  * Configure which integrations should be enabled.
12213
13353
  * This must be called before any SDK imports to take effect.
@@ -12271,7 +13411,8 @@ var PluginRegistry = (_class19 = class {constructor() { _class19.prototype.__ini
12271
13411
  vercel: true,
12272
13412
  aisdk: true,
12273
13413
  google: true,
12274
- claudeAgentSDK: true
13414
+ claudeAgentSDK: true,
13415
+ openrouter: true
12275
13416
  };
12276
13417
  }
12277
13418
  /**
@@ -12301,6 +13442,7 @@ function configureNode() {
12301
13442
  isomorph_default.getCallerLocation = getCallerLocation;
12302
13443
  isomorph_default.newAsyncLocalStorage = () => new (0, _nodeasync_hooks.AsyncLocalStorage)();
12303
13444
  isomorph_default.newTracingChannel = (nameOrChannels) => diagnostics_channel.tracingChannel(nameOrChannels);
13445
+ patchTracingChannel(diagnostics_channel.tracingChannel);
12304
13446
  isomorph_default.processOn = (event, handler) => {
12305
13447
  process.on(event, handler);
12306
13448
  };
@@ -12405,7 +13547,7 @@ function isAsync(fn) {
12405
13547
  function isAsyncGenerator2(fn) {
12406
13548
  return fn[Symbol.toStringTag] === "AsyncGenerator";
12407
13549
  }
12408
- function isAsyncIterable2(obj) {
13550
+ function isAsyncIterable3(obj) {
12409
13551
  return typeof obj[Symbol.asyncIterator] === "function";
12410
13552
  }
12411
13553
  function wrapAsync(asyncFn) {
@@ -12455,7 +13597,7 @@ function _asyncMap(eachfn, arr, iteratee, callback) {
12455
13597
  callback(err, results);
12456
13598
  });
12457
13599
  }
12458
- function isArrayLike(value) {
13600
+ function isArrayLike2(value) {
12459
13601
  return value && typeof value.length === "number" && value.length >= 0 && value.length % 1 === 0;
12460
13602
  }
12461
13603
  var breakLoop = {};
@@ -12503,7 +13645,7 @@ function createObjectIterator(obj) {
12503
13645
  };
12504
13646
  }
12505
13647
  function createIterator(coll) {
12506
- if (isArrayLike(coll)) {
13648
+ if (isArrayLike2(coll)) {
12507
13649
  return createArrayIterator(coll);
12508
13650
  }
12509
13651
  var iterator = getIterator(coll);
@@ -12577,7 +13719,7 @@ var eachOfLimit$2 = (limit) => {
12577
13719
  if (isAsyncGenerator2(obj)) {
12578
13720
  return asyncEachOfLimit(obj, limit, iteratee, callback);
12579
13721
  }
12580
- if (isAsyncIterable2(obj)) {
13722
+ if (isAsyncIterable3(obj)) {
12581
13723
  return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback);
12582
13724
  }
12583
13725
  var nextElem = createIterator(obj);
@@ -12649,7 +13791,7 @@ function eachOfGeneric(coll, iteratee, callback) {
12649
13791
  return eachOfLimit$1(coll, Infinity, iteratee, callback);
12650
13792
  }
12651
13793
  function eachOf(coll, iteratee, callback) {
12652
- var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric;
13794
+ var eachOfImplementation = isArrayLike2(coll) ? eachOfArrayLike : eachOfGeneric;
12653
13795
  return eachOfImplementation(coll, wrapAsync(iteratee), callback);
12654
13796
  }
12655
13797
  var eachOf$1 = awaitify(eachOf, 3);
@@ -13164,7 +14306,7 @@ function filterGeneric(eachfn, coll, iteratee, callback) {
13164
14306
  });
13165
14307
  }
13166
14308
  function _filter(eachfn, coll, iteratee, callback) {
13167
- var filter2 = isArrayLike(coll) ? filterArray : filterGeneric;
14309
+ var filter2 = isArrayLike2(coll) ? filterArray : filterGeneric;
13168
14310
  return filter2(eachfn, coll, wrapAsync(iteratee), callback);
13169
14311
  }
13170
14312
  function filter(coll, iteratee, callback) {
@@ -13239,7 +14381,7 @@ if (hasNextTick) {
13239
14381
  }
13240
14382
  var nextTick = wrap(_defer);
13241
14383
  var _parallel = awaitify((eachfn, tasks, callback) => {
13242
- var results = isArrayLike(tasks) ? [] : {};
14384
+ var results = isArrayLike2(tasks) ? [] : {};
13243
14385
  eachfn(tasks, (task, key, taskCb) => {
13244
14386
  wrapAsync(task)((err, ...result) => {
13245
14387
  if (result.length < 2) {
@@ -13506,10 +14648,10 @@ var SpanFetcher = class _SpanFetcher extends ObjectFetcher {
13506
14648
  }
13507
14649
  };
13508
14650
  var CachedSpanFetcher = (_class20 = class {
13509
- __init72() {this.spanCache = /* @__PURE__ */ new Map()}
13510
- __init73() {this.allFetched = false}
14651
+ __init73() {this.spanCache = /* @__PURE__ */ new Map()}
14652
+ __init74() {this.allFetched = false}
13511
14653
 
13512
- constructor(objectTypeOrFetchFn, objectId, rootSpanId, getState) {;_class20.prototype.__init72.call(this);_class20.prototype.__init73.call(this);
14654
+ constructor(objectTypeOrFetchFn, objectId, rootSpanId, getState) {;_class20.prototype.__init73.call(this);_class20.prototype.__init74.call(this);
13513
14655
  if (typeof objectTypeOrFetchFn === "function") {
13514
14656
  this.fetchFn = objectTypeOrFetchFn;
13515
14657
  } else {
@@ -13524,7 +14666,7 @@ var CachedSpanFetcher = (_class20 = class {
13524
14666
  spanType
13525
14667
  );
13526
14668
  const rows = await fetcher.fetchedData();
13527
- return rows.filter((row) => _optionalChain([row, 'access', _224 => _224.span_attributes, 'optionalAccess', _225 => _225.purpose]) !== "scorer").map((row) => ({
14669
+ return rows.filter((row) => _optionalChain([row, 'access', _286 => _286.span_attributes, 'optionalAccess', _287 => _287.purpose]) !== "scorer").map((row) => ({
13528
14670
  input: row.input,
13529
14671
  output: row.output,
13530
14672
  metadata: row.metadata,
@@ -13558,7 +14700,7 @@ var CachedSpanFetcher = (_class20 = class {
13558
14700
  async fetchSpans(spanType) {
13559
14701
  const spans = await this.fetchFn(spanType);
13560
14702
  for (const span of spans) {
13561
- const type = _nullishCoalesce(_optionalChain([span, 'access', _226 => _226.span_attributes, 'optionalAccess', _227 => _227.type]), () => ( ""));
14703
+ const type = _nullishCoalesce(_optionalChain([span, 'access', _288 => _288.span_attributes, 'optionalAccess', _289 => _289.type]), () => ( ""));
13562
14704
  const existing = _nullishCoalesce(this.spanCache.get(type), () => ( []));
13563
14705
  existing.push(span);
13564
14706
  this.spanCache.set(type, existing);
@@ -13582,17 +14724,17 @@ var LocalTrace = (_class21 = class {
13582
14724
 
13583
14725
 
13584
14726
 
13585
- __init74() {this.spansFlushed = false}
13586
- __init75() {this.spansFlushPromise = null}
14727
+ __init75() {this.spansFlushed = false}
14728
+ __init76() {this.spansFlushPromise = null}
13587
14729
 
13588
- __init76() {this.threadCache = /* @__PURE__ */ new Map()}
14730
+ __init77() {this.threadCache = /* @__PURE__ */ new Map()}
13589
14731
  constructor({
13590
14732
  objectType,
13591
14733
  objectId,
13592
14734
  rootSpanId,
13593
14735
  ensureSpansFlushed,
13594
14736
  state
13595
- }) {;_class21.prototype.__init74.call(this);_class21.prototype.__init75.call(this);_class21.prototype.__init76.call(this);
14737
+ }) {;_class21.prototype.__init75.call(this);_class21.prototype.__init76.call(this);_class21.prototype.__init77.call(this);
13596
14738
  this.objectType = objectType;
13597
14739
  this.objectId = objectId;
13598
14740
  this.rootSpanId = rootSpanId;
@@ -13638,11 +14780,11 @@ var LocalTrace = (_class21 = class {
13638
14780
  const cachedSpans = this.state.spanCache.getByRootSpanId(this.rootSpanId);
13639
14781
  if (cachedSpans && cachedSpans.length > 0) {
13640
14782
  let spans = cachedSpans.filter(
13641
- (span) => _optionalChain([span, 'access', _228 => _228.span_attributes, 'optionalAccess', _229 => _229.purpose]) !== "scorer"
14783
+ (span) => _optionalChain([span, 'access', _290 => _290.span_attributes, 'optionalAccess', _291 => _291.purpose]) !== "scorer"
13642
14784
  );
13643
14785
  if (spanType && spanType.length > 0) {
13644
14786
  spans = spans.filter(
13645
- (span) => spanType.includes(_nullishCoalesce(_optionalChain([span, 'access', _230 => _230.span_attributes, 'optionalAccess', _231 => _231.type]), () => ( "")))
14787
+ (span) => spanType.includes(_nullishCoalesce(_optionalChain([span, 'access', _292 => _292.span_attributes, 'optionalAccess', _293 => _293.type]), () => ( "")))
13646
14788
  );
13647
14789
  }
13648
14790
  return spans.map((span) => ({
@@ -13661,7 +14803,7 @@ var LocalTrace = (_class21 = class {
13661
14803
  * Calls the API with the project_default preprocessor (which falls back to "thread").
13662
14804
  */
13663
14805
  async getThread(options) {
13664
- const cacheKey = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _232 => _232.preprocessor]), () => ( "project_default"));
14806
+ const cacheKey = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _294 => _294.preprocessor]), () => ( "project_default"));
13665
14807
  if (!this.threadCache.has(cacheKey)) {
13666
14808
  const promise = this.fetchThread(options);
13667
14809
  this.threadCache.set(cacheKey, promise);
@@ -13672,7 +14814,7 @@ var LocalTrace = (_class21 = class {
13672
14814
  await this.ensureSpansReady();
13673
14815
  await this.state.login({});
13674
14816
  const result = await invoke({
13675
- globalFunction: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _233 => _233.preprocessor]), () => ( "project_default")),
14817
+ globalFunction: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _295 => _295.preprocessor]), () => ( "project_default")),
13676
14818
  functionType: "preprocessor",
13677
14819
  input: {
13678
14820
  trace_ref: {
@@ -13848,10 +14990,10 @@ function validateParametersWithJsonSchema(parameters, schema) {
13848
14990
  const ajv = new (0, _ajv2.default)({ coerceTypes: true, useDefaults: true, strict: false });
13849
14991
  const validate = ajv.compile(schema);
13850
14992
  if (!validate(parameters)) {
13851
- const errorMessages = _optionalChain([validate, 'access', _234 => _234.errors, 'optionalAccess', _235 => _235.map, 'call', _236 => _236((err) => {
14993
+ const errorMessages = _optionalChain([validate, 'access', _296 => _296.errors, 'optionalAccess', _297 => _297.map, 'call', _298 => _298((err) => {
13852
14994
  const path2 = err.instancePath || "root";
13853
14995
  return `${path2}: ${err.message}`;
13854
- }), 'access', _237 => _237.join, 'call', _238 => _238(", ")]);
14996
+ }), 'access', _299 => _299.join, 'call', _300 => _300(", ")]);
13855
14997
  throw Error(`Invalid parameters: ${errorMessages}`);
13856
14998
  }
13857
14999
  return parameters;
@@ -13920,7 +15062,7 @@ function callEvaluatorData(data) {
13920
15062
  baseExperiment
13921
15063
  };
13922
15064
  }
13923
- function isAsyncIterable3(value) {
15065
+ function isAsyncIterable4(value) {
13924
15066
  return typeof value === "object" && value !== null && Symbol.asyncIterator in value && typeof value[Symbol.asyncIterator] === "function";
13925
15067
  }
13926
15068
  function isIterable(value) {
@@ -14089,7 +15231,7 @@ async function runEvaluator(experiment, evaluator, progressReporter, filters, st
14089
15231
  }
14090
15232
  async function runEvaluatorInternal(experiment, evaluator, progressReporter, filters, stream, parameters, collectResults, enableCache) {
14091
15233
  if (enableCache) {
14092
- _optionalChain([(_nullishCoalesce(evaluator.state, () => ( _internalGetGlobalState()))), 'optionalAccess', _239 => _239.spanCache, 'optionalAccess', _240 => _240.start, 'call', _241 => _241()]);
15234
+ _optionalChain([(_nullishCoalesce(evaluator.state, () => ( _internalGetGlobalState()))), 'optionalAccess', _301 => _301.spanCache, 'optionalAccess', _302 => _302.start, 'call', _303 => _303()]);
14093
15235
  }
14094
15236
  try {
14095
15237
  if (typeof evaluator.data === "string") {
@@ -14125,7 +15267,7 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
14125
15267
  }
14126
15268
  const resolvedDataResult = dataResult instanceof Promise ? await dataResult : dataResult;
14127
15269
  const dataIterable = (() => {
14128
- if (isAsyncIterable3(resolvedDataResult)) {
15270
+ if (isAsyncIterable4(resolvedDataResult)) {
14129
15271
  return resolvedDataResult;
14130
15272
  }
14131
15273
  if (Array.isArray(resolvedDataResult) || isIterable(resolvedDataResult)) {
@@ -14144,7 +15286,7 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
14144
15286
  const experimentIdPromise = experiment ? (async () => {
14145
15287
  try {
14146
15288
  return await experiment.id;
14147
- } catch (e27) {
15289
+ } catch (e29) {
14148
15290
  return void 0;
14149
15291
  }
14150
15292
  })() : void 0;
@@ -14200,7 +15342,7 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
14200
15342
  objectType: parentComponents ? spanObjectTypeV3ToTypedString(
14201
15343
  parentComponents.data.object_type
14202
15344
  ) : "experiment",
14203
- objectId: await _asyncNullishCoalesce(await _asyncOptionalChain([parentComponents, 'optionalAccess', async _242 => _242.data, 'access', async _243 => _243.object_id]), async () => ( (experimentIdPromise ? await _asyncNullishCoalesce(await experimentIdPromise, async () => ( "")) : ""))),
15345
+ objectId: await _asyncNullishCoalesce(await _asyncOptionalChain([parentComponents, 'optionalAccess', async _304 => _304.data, 'access', async _305 => _305.object_id]), async () => ( (experimentIdPromise ? await _asyncNullishCoalesce(await experimentIdPromise, async () => ( "")) : ""))),
14204
15346
  rootSpanId: rootSpan.rootSpanId,
14205
15347
  ensureSpansFlushed,
14206
15348
  state
@@ -14226,10 +15368,10 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
14226
15368
  span,
14227
15369
  parameters: _nullishCoalesce(parameters, () => ( {})),
14228
15370
  reportProgress: (event) => {
14229
- _optionalChain([stream, 'optionalCall', _244 => _244({
15371
+ _optionalChain([stream, 'optionalCall', _306 => _306({
14230
15372
  ...event,
14231
15373
  id: rootSpan.id,
14232
- origin: _optionalChain([baseEvent, 'access', _245 => _245.event, 'optionalAccess', _246 => _246.origin]),
15374
+ origin: _optionalChain([baseEvent, 'access', _307 => _307.event, 'optionalAccess', _308 => _308.origin]),
14233
15375
  name: evaluator.evalName,
14234
15376
  object_type: "task"
14235
15377
  })]);
@@ -14393,7 +15535,7 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
14393
15535
  metadata,
14394
15536
  scores: mergedScores,
14395
15537
  error,
14396
- origin: _optionalChain([baseEvent, 'access', _247 => _247.event, 'optionalAccess', _248 => _248.origin])
15538
+ origin: _optionalChain([baseEvent, 'access', _309 => _309.event, 'optionalAccess', _310 => _310.origin])
14397
15539
  });
14398
15540
  }
14399
15541
  };
@@ -14428,7 +15570,7 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
14428
15570
  break;
14429
15571
  }
14430
15572
  scheduledTrials++;
14431
- _optionalChain([progressReporter, 'access', _249 => _249.setTotal, 'optionalCall', _250 => _250(evaluator.evalName, scheduledTrials)]);
15573
+ _optionalChain([progressReporter, 'access', _311 => _311.setTotal, 'optionalCall', _312 => _312(evaluator.evalName, scheduledTrials)]);
14432
15574
  q.pushAsync({ datum, trialIndex }).catch((e) => {
14433
15575
  if (queueErrors.length < 5) {
14434
15576
  queueErrors.push(e);
@@ -14513,9 +15655,9 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
14513
15655
  );
14514
15656
  } finally {
14515
15657
  if (enableCache) {
14516
- const spanCache = _optionalChain([(_nullishCoalesce(evaluator.state, () => ( _internalGetGlobalState()))), 'optionalAccess', _251 => _251.spanCache]);
14517
- _optionalChain([spanCache, 'optionalAccess', _252 => _252.dispose, 'call', _253 => _253()]);
14518
- _optionalChain([spanCache, 'optionalAccess', _254 => _254.stop, 'call', _255 => _255()]);
15658
+ const spanCache = _optionalChain([(_nullishCoalesce(evaluator.state, () => ( _internalGetGlobalState()))), 'optionalAccess', _313 => _313.spanCache]);
15659
+ _optionalChain([spanCache, 'optionalAccess', _314 => _314.dispose, 'call', _315 => _315()]);
15660
+ _optionalChain([spanCache, 'optionalAccess', _316 => _316.stop, 'call', _317 => _317()]);
14519
15661
  }
14520
15662
  }
14521
15663
  }
@@ -14752,7 +15894,7 @@ async function cachedLogin(options) {
14752
15894
  }
14753
15895
  function makeCheckAuthorized(allowedOrgName) {
14754
15896
  return async (req, _res, next) => {
14755
- if (!_optionalChain([req, 'access', _256 => _256.ctx, 'optionalAccess', _257 => _257.token])) {
15897
+ if (!_optionalChain([req, 'access', _318 => _318.ctx, 'optionalAccess', _319 => _319.token])) {
14756
15898
  return next(_httperrors2.default.call(void 0, 401, "Unauthorized"));
14757
15899
  }
14758
15900
  try {
@@ -14765,7 +15907,7 @@ function makeCheckAuthorized(allowedOrgName) {
14765
15907
  return next(_httperrors2.default.call(void 0, 403, errorMessage));
14766
15908
  }
14767
15909
  const state = await cachedLogin({
14768
- apiKey: _optionalChain([req, 'access', _258 => _258.ctx, 'optionalAccess', _259 => _259.token]),
15910
+ apiKey: _optionalChain([req, 'access', _320 => _320.ctx, 'optionalAccess', _321 => _321.token]),
14769
15911
  orgName
14770
15912
  });
14771
15913
  req.ctx.state = state;
@@ -14962,10 +16104,10 @@ var Project2 = (_class22 = class {
14962
16104
 
14963
16105
 
14964
16106
 
14965
- __init77() {this._publishableCodeFunctions = []}
14966
- __init78() {this._publishablePrompts = []}
14967
- __init79() {this._publishableParameters = []}
14968
- constructor(args) {;_class22.prototype.__init77.call(this);_class22.prototype.__init78.call(this);_class22.prototype.__init79.call(this);
16107
+ __init78() {this._publishableCodeFunctions = []}
16108
+ __init79() {this._publishablePrompts = []}
16109
+ __init80() {this._publishableParameters = []}
16110
+ constructor(args) {;_class22.prototype.__init78.call(this);_class22.prototype.__init79.call(this);_class22.prototype.__init80.call(this);
14969
16111
  _initializeSpanContext();
14970
16112
  this.name = "name" in args ? args.name : void 0;
14971
16113
  this.id = "id" in args ? args.id : void 0;
@@ -15019,10 +16161,10 @@ var Project2 = (_class22 = class {
15019
16161
  }
15020
16162
  }, _class22);
15021
16163
  var ToolBuilder = (_class23 = class {
15022
- constructor(project) {;_class23.prototype.__init80.call(this);
16164
+ constructor(project) {;_class23.prototype.__init81.call(this);
15023
16165
  this.project = project;
15024
16166
  }
15025
- __init80() {this.taskCounter = 0}
16167
+ __init81() {this.taskCounter = 0}
15026
16168
  // This type definition is just a catch all so that the implementation can be
15027
16169
  // less specific than the two more specific declarations above.
15028
16170
  create(opts) {
@@ -15049,10 +16191,10 @@ var ToolBuilder = (_class23 = class {
15049
16191
  }
15050
16192
  }, _class23);
15051
16193
  var ScorerBuilder = (_class24 = class {
15052
- constructor(project) {;_class24.prototype.__init81.call(this);
16194
+ constructor(project) {;_class24.prototype.__init82.call(this);
15053
16195
  this.project = project;
15054
16196
  }
15055
- __init81() {this.taskCounter = 0}
16197
+ __init82() {this.taskCounter = 0}
15056
16198
  create(opts) {
15057
16199
  this.taskCounter++;
15058
16200
  let resolvedName = opts.name;
@@ -15407,9 +16549,9 @@ function serializeRemoteEvalParametersContainer(parameters) {
15407
16549
  source: null
15408
16550
  };
15409
16551
  }
15410
- var ProjectNameIdMap = (_class25 = class {constructor() { _class25.prototype.__init82.call(this);_class25.prototype.__init83.call(this); }
15411
- __init82() {this.nameToId = {}}
15412
- __init83() {this.idToName = {}}
16552
+ var ProjectNameIdMap = (_class25 = class {constructor() { _class25.prototype.__init83.call(this);_class25.prototype.__init84.call(this); }
16553
+ __init83() {this.nameToId = {}}
16554
+ __init84() {this.idToName = {}}
15413
16555
  async getId(projectName) {
15414
16556
  if (!(projectName in this.nameToId)) {
15415
16557
  const response = await _internalGetGlobalState().appConn().post_json("api/project/register", {
@@ -15514,7 +16656,7 @@ function runDevServer(evaluators, opts) {
15514
16656
  scores,
15515
16657
  stream
15516
16658
  } = evalBodySchema.parse(req.body);
15517
- if (!_optionalChain([req, 'access', _260 => _260.ctx, 'optionalAccess', _261 => _261.state])) {
16659
+ if (!_optionalChain([req, 'access', _322 => _322.ctx, 'optionalAccess', _323 => _323.state])) {
15518
16660
  res.status(500).json({ error: "Braintrust state not initialized in request" });
15519
16661
  return;
15520
16662
  }
@@ -15565,12 +16707,12 @@ function runDevServer(evaluators, opts) {
15565
16707
  ...evaluator,
15566
16708
  data: evalData.data,
15567
16709
  scores: evaluator.scores.concat(
15568
- _nullishCoalesce(_optionalChain([scores, 'optionalAccess', _262 => _262.map, 'call', _263 => _263(
16710
+ _nullishCoalesce(_optionalChain([scores, 'optionalAccess', _324 => _324.map, 'call', _325 => _325(
15569
16711
  (score) => makeScorer(
15570
16712
  state,
15571
16713
  score.name,
15572
16714
  score.function_id,
15573
- _optionalChain([req, 'access', _264 => _264.ctx, 'optionalAccess', _265 => _265.projectId])
16715
+ _optionalChain([req, 'access', _326 => _326.ctx, 'optionalAccess', _327 => _327.projectId])
15574
16716
  )
15575
16717
  )]), () => ( []))
15576
16718
  ),