braintrust 0.3.7 → 0.4.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.
package/dist/index.js CHANGED
@@ -1528,7 +1528,7 @@ var init_BatchSpanProcessor = _chunkCDBUTZMHjs.__esm.call(void 0, {
1528
1528
  });
1529
1529
 
1530
1530
  // ../../node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.0.1_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/sdk-trace-base/build/esm/platform/node/RandomIdGenerator.js
1531
- function getIdGenerator(bytes) {
1531
+ function getIdGenerator2(bytes) {
1532
1532
  return function generateId() {
1533
1533
  for (let i = 0; i < bytes / 4; i++) {
1534
1534
  SHARED_BUFFER.writeUInt32BE(Math.random() * 2 ** 32 >>> 0, i * 4);
@@ -1554,12 +1554,12 @@ var init_RandomIdGenerator = _chunkCDBUTZMHjs.__esm.call(void 0, {
1554
1554
  * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex
1555
1555
  * characters corresponding to 128 bits.
1556
1556
  */
1557
- __init17() {this.generateTraceId = getIdGenerator(TRACE_ID_BYTES)}
1557
+ __init17() {this.generateTraceId = getIdGenerator2(TRACE_ID_BYTES)}
1558
1558
  /**
1559
1559
  * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex
1560
1560
  * characters corresponding to 64 bits.
1561
1561
  */
1562
- __init18() {this.generateSpanId = getIdGenerator(SPAN_ID_BYTES)}
1562
+ __init18() {this.generateSpanId = getIdGenerator2(SPAN_ID_BYTES)}
1563
1563
  }, _class5);
1564
1564
  SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES);
1565
1565
  }
@@ -3498,6 +3498,44 @@ var Queue = (_class11 = class {
3498
3498
  }
3499
3499
  }, _class11);
3500
3500
 
3501
+ // src/id-gen.ts
3502
+
3503
+ function generateHexId(bytes) {
3504
+ let result = "";
3505
+ for (let i = 0; i < bytes; i++) {
3506
+ result += Math.floor(Math.random() * 256).toString(16).padStart(2, "0");
3507
+ }
3508
+ return result;
3509
+ }
3510
+ var IDGenerator = class {
3511
+ };
3512
+ var UUIDGenerator = class extends IDGenerator {
3513
+ getSpanId() {
3514
+ return _uuid.v4.call(void 0, );
3515
+ }
3516
+ getTraceId() {
3517
+ return _uuid.v4.call(void 0, );
3518
+ }
3519
+ shareRootSpanId() {
3520
+ return true;
3521
+ }
3522
+ };
3523
+ var OTELIDGenerator = class extends IDGenerator {
3524
+ getSpanId() {
3525
+ return generateHexId(8);
3526
+ }
3527
+ getTraceId() {
3528
+ return generateHexId(16);
3529
+ }
3530
+ shareRootSpanId() {
3531
+ return false;
3532
+ }
3533
+ };
3534
+ function getIdGenerator() {
3535
+ const useOtel = typeof process !== "undefined" && _optionalChain([process, 'access', _74 => _74.env, 'optionalAccess', _75 => _75.BRAINTRUST_OTEL_COMPAT, 'optionalAccess', _76 => _76.toLowerCase, 'call', _77 => _77()]) === "true";
3536
+ return useOtel ? new OTELIDGenerator() : new UUIDGenerator();
3537
+ }
3538
+
3501
3539
  // util/db_fields.ts
3502
3540
  var TRANSACTION_ID_FIELD = "_xact_id";
3503
3541
  var IS_MERGE_FIELD = "_is_merge";
@@ -3648,7 +3686,7 @@ var SpanComponentsV1 = class _SpanComponentsV1 {
3648
3686
  return {
3649
3687
  objectType: this.objectType,
3650
3688
  objectId: this.objectId,
3651
- rowIds: _optionalChain([this, 'access', _74 => _74.rowIds, 'optionalAccess', _75 => _75.toObject, 'call', _76 => _76()])
3689
+ rowIds: _optionalChain([this, 'access', _78 => _78.rowIds, 'optionalAccess', _79 => _79.toObject, 'call', _80 => _80()])
3652
3690
  };
3653
3691
  }
3654
3692
  };
@@ -3862,7 +3900,7 @@ var SpanComponentsV2 = class _SpanComponentsV2 {
3862
3900
  objectType: this.objectType,
3863
3901
  objectId: this.objectId,
3864
3902
  computeObjectMetadataArgs: this.computeObjectMetadataArgs,
3865
- rowIds: _optionalChain([this, 'access', _77 => _77.rowIds, 'optionalAccess', _78 => _78.toObject, 'call', _79 => _79()])
3903
+ rowIds: _optionalChain([this, 'access', _81 => _81.rowIds, 'optionalAccess', _82 => _82.toObject, 'call', _83 => _83()])
3866
3904
  };
3867
3905
  }
3868
3906
  };
@@ -4194,14 +4232,14 @@ function depthFirstSearch(args) {
4194
4232
  while (events.length) {
4195
4233
  const { eventType, vertex, extras } = events.pop();
4196
4234
  if (eventType === "last") {
4197
- _optionalChain([lastVisitF, 'optionalCall', _80 => _80(vertex)]);
4235
+ _optionalChain([lastVisitF, 'optionalCall', _84 => _84(vertex)]);
4198
4236
  continue;
4199
4237
  }
4200
4238
  if (firstVisitedVertices.has(vertex)) {
4201
4239
  continue;
4202
4240
  }
4203
4241
  firstVisitedVertices.add(vertex);
4204
- _optionalChain([firstVisitF, 'optionalCall', _81 => _81(vertex, { parentVertex: extras.parentVertex })]);
4242
+ _optionalChain([firstVisitF, 'optionalCall', _85 => _85(vertex, { parentVertex: extras.parentVertex })]);
4205
4243
  events.push({ eventType: "last", vertex, extras: {} });
4206
4244
  mapAt(graph, vertex).forEach((child) => {
4207
4245
  events.push({
@@ -4223,7 +4261,7 @@ function undirectedConnectedComponents(graph) {
4223
4261
  let labelCounter = 0;
4224
4262
  const vertexLabels = /* @__PURE__ */ new Map();
4225
4263
  const firstVisitF = (vertex, args) => {
4226
- const label = _optionalChain([args, 'optionalAccess', _82 => _82.parentVertex]) !== void 0 ? mapAt(vertexLabels, _optionalChain([args, 'optionalAccess', _83 => _83.parentVertex])) : labelCounter++;
4264
+ const label = _optionalChain([args, 'optionalAccess', _86 => _86.parentVertex]) !== void 0 ? mapAt(vertexLabels, _optionalChain([args, 'optionalAccess', _87 => _87.parentVertex])) : labelCounter++;
4227
4265
  vertexLabels.set(vertex, label);
4228
4266
  };
4229
4267
  depthFirstSearch({ graph: directedGraph, firstVisitF });
@@ -4445,6 +4483,41 @@ function _urljoin(...parts) {
4445
4483
  ).filter((x) => x.trim() !== "").join("/");
4446
4484
  }
4447
4485
 
4486
+ // util/span_identifier_v4.ts
4487
+
4488
+ var ENCODING_VERSION_NUMBER_V4 = 4;
4489
+ var INVALID_ENCODING_ERRMSG_V4 = `SpanComponents string is not properly encoded. This library only supports encoding versions up to ${ENCODING_VERSION_NUMBER_V4}. Please make sure the SDK library used to decode the SpanComponents is at least as new as any library used to encode it.`;
4490
+ var spanComponentsV4Schema = _v3.z.object({
4491
+ object_type: spanObjectTypeV3EnumSchema,
4492
+ propagated_event: _v3.z.record(_v3.z.unknown()).nullish()
4493
+ }).and(
4494
+ _v3.z.union([
4495
+ // Must provide one or the other.
4496
+ _v3.z.object({
4497
+ object_id: _v3.z.string().nullish(),
4498
+ compute_object_metadata_args: _v3.z.optional(_v3.z.null())
4499
+ }),
4500
+ _v3.z.object({
4501
+ object_id: _v3.z.optional(_v3.z.null()),
4502
+ compute_object_metadata_args: _v3.z.record(_v3.z.unknown())
4503
+ })
4504
+ ])
4505
+ ).and(
4506
+ _v3.z.union([
4507
+ // Either all of these must be provided or none.
4508
+ _v3.z.object({
4509
+ row_id: _v3.z.string(),
4510
+ span_id: _v3.z.string(),
4511
+ root_span_id: _v3.z.string()
4512
+ }),
4513
+ _v3.z.object({
4514
+ row_id: _v3.z.optional(_v3.z.null()),
4515
+ span_id: _v3.z.optional(_v3.z.null()),
4516
+ root_span_id: _v3.z.optional(_v3.z.null())
4517
+ })
4518
+ ])
4519
+ );
4520
+
4448
4521
  // util/git_fields.ts
4449
4522
  function mergeGitMetadataSettings(s1, s2) {
4450
4523
  if (s1.collect === "all") {
@@ -6460,7 +6533,7 @@ var NoopSpan = (_class14 = class {
6460
6533
  return this;
6461
6534
  }
6462
6535
  end(args) {
6463
- return _nullishCoalesce(_optionalChain([args, 'optionalAccess', _84 => _84.endTime]), () => ( getCurrentUnixTimestamp()));
6536
+ return _nullishCoalesce(_optionalChain([args, 'optionalAccess', _88 => _88.endTime]), () => ( getCurrentUnixTimestamp()));
6464
6537
  }
6465
6538
  async export() {
6466
6539
  return "";
@@ -6484,6 +6557,20 @@ var NoopSpan = (_class14 = class {
6484
6557
  state() {
6485
6558
  return _internalGetGlobalState();
6486
6559
  }
6560
+ // Custom inspect for Node.js console.log
6561
+ [Symbol.for("nodejs.util.inspect.custom")]() {
6562
+ return `NoopSpan {
6563
+ kind: '${this.kind}',
6564
+ id: '${this.id}',
6565
+ spanId: '${this.spanId}',
6566
+ rootSpanId: '${this.rootSpanId}',
6567
+ spanParents: ${JSON.stringify(this.spanParents)}
6568
+ }`;
6569
+ }
6570
+ // Custom toString
6571
+ toString() {
6572
+ return `NoopSpan(id=${this.id}, spanId=${this.spanId})`;
6573
+ }
6487
6574
  }, _class14);
6488
6575
  var NOOP_SPAN = new NoopSpan();
6489
6576
  var NOOP_SPAN_PERMALINK = "https://braintrust.dev/noop-span";
@@ -6499,7 +6586,7 @@ var loginSchema = _zod.z.strictObject({
6499
6586
  });
6500
6587
  var stateNonce = 0;
6501
6588
  var BraintrustState = (_class15 = class _BraintrustState {
6502
- constructor(loginParams) {;_class15.prototype.__init31.call(this);_class15.prototype.__init32.call(this);_class15.prototype.__init33.call(this);_class15.prototype.__init34.call(this);_class15.prototype.__init35.call(this);_class15.prototype.__init36.call(this);_class15.prototype.__init37.call(this);_class15.prototype.__init38.call(this);_class15.prototype.__init39.call(this);_class15.prototype.__init40.call(this);_class15.prototype.__init41.call(this);_class15.prototype.__init42.call(this);_class15.prototype.__init43.call(this);
6589
+ constructor(loginParams) {;_class15.prototype.__init31.call(this);_class15.prototype.__init32.call(this);_class15.prototype.__init33.call(this);_class15.prototype.__init34.call(this);_class15.prototype.__init35.call(this);_class15.prototype.__init36.call(this);_class15.prototype.__init37.call(this);_class15.prototype.__init38.call(this);_class15.prototype.__init39.call(this);_class15.prototype.__init40.call(this);_class15.prototype.__init41.call(this);_class15.prototype.__init42.call(this);_class15.prototype.__init43.call(this);_class15.prototype.__init44.call(this);
6503
6590
  this.loginParams = loginParams;
6504
6591
  this.id = `${(/* @__PURE__ */ new Date()).toLocaleString()}-${stateNonce++}`;
6505
6592
  this.currentExperiment = void 0;
@@ -6553,6 +6640,7 @@ var BraintrustState = (_class15 = class _BraintrustState {
6553
6640
  __init42() {this._apiConn = null}
6554
6641
  __init43() {this._proxyConn = null}
6555
6642
 
6643
+ __init44() {this._idGenerator = null}
6556
6644
  resetLoginInfo() {
6557
6645
  this.appUrl = null;
6558
6646
  this.appPublicUrl = null;
@@ -6567,6 +6655,15 @@ var BraintrustState = (_class15 = class _BraintrustState {
6567
6655
  this._apiConn = null;
6568
6656
  this._proxyConn = null;
6569
6657
  }
6658
+ resetIdGenState() {
6659
+ this._idGenerator = null;
6660
+ }
6661
+ get idGenerator() {
6662
+ if (this._idGenerator === null) {
6663
+ this._idGenerator = getIdGenerator();
6664
+ }
6665
+ return this._idGenerator;
6666
+ }
6570
6667
  copyLoginInfo(other) {
6571
6668
  this.appUrl = other.appUrl;
6572
6669
  this.appPublicUrl = other.appPublicUrl;
@@ -6634,8 +6731,8 @@ var BraintrustState = (_class15 = class _BraintrustState {
6634
6731
  setFetch(fetch2) {
6635
6732
  this.loginParams.fetch = fetch2;
6636
6733
  this.fetch = fetch2;
6637
- _optionalChain([this, 'access', _85 => _85._apiConn, 'optionalAccess', _86 => _86.setFetch, 'call', _87 => _87(fetch2)]);
6638
- _optionalChain([this, 'access', _88 => _88._appConn, 'optionalAccess', _89 => _89.setFetch, 'call', _90 => _90(fetch2)]);
6734
+ _optionalChain([this, 'access', _89 => _89._apiConn, 'optionalAccess', _90 => _90.setFetch, 'call', _91 => _91(fetch2)]);
6735
+ _optionalChain([this, 'access', _92 => _92._appConn, 'optionalAccess', _93 => _93.setFetch, 'call', _94 => _94(fetch2)]);
6639
6736
  }
6640
6737
  setMaskingFunction(maskingFunction) {
6641
6738
  this.bgLogger().setMaskingFunction(maskingFunction);
@@ -6704,6 +6801,37 @@ var BraintrustState = (_class15 = class _BraintrustState {
6704
6801
  enforceQueueSizeLimit(enforce) {
6705
6802
  this._bgLogger.get().enforceQueueSizeLimit(enforce);
6706
6803
  }
6804
+ // Custom serialization to avoid logging sensitive data
6805
+ toJSON() {
6806
+ return {
6807
+ id: this.id,
6808
+ orgId: this.orgId,
6809
+ orgName: this.orgName,
6810
+ appUrl: this.appUrl,
6811
+ appPublicUrl: this.appPublicUrl,
6812
+ apiUrl: this.apiUrl,
6813
+ proxyUrl: this.proxyUrl,
6814
+ loggedIn: this.loggedIn
6815
+ // Explicitly exclude loginToken, _apiConn, _appConn, _proxyConn and other sensitive fields
6816
+ };
6817
+ }
6818
+ // Custom inspect for Node.js console.log
6819
+ [Symbol.for("nodejs.util.inspect.custom")]() {
6820
+ return `BraintrustState {
6821
+ id: '${this.id}',
6822
+ orgId: ${this.orgId ? `'${this.orgId}'` : "null"},
6823
+ orgName: ${this.orgName ? `'${this.orgName}'` : "null"},
6824
+ appUrl: ${this.appUrl ? `'${this.appUrl}'` : "null"},
6825
+ apiUrl: ${this.apiUrl ? `'${this.apiUrl}'` : "null"},
6826
+ proxyUrl: ${this.proxyUrl ? `'${this.proxyUrl}'` : "null"},
6827
+ loggedIn: ${this.loggedIn},
6828
+ loginToken: '[REDACTED]'
6829
+ }`;
6830
+ }
6831
+ // Custom toString
6832
+ toString() {
6833
+ return `BraintrustState(id=${this.id}, org=${this.orgName || "none"}, loggedIn=${this.loggedIn})`;
6834
+ }
6707
6835
  }, _class15);
6708
6836
  var _globalState;
6709
6837
  function useTestBackgroundLogger() {
@@ -6716,7 +6844,7 @@ function useTestBackgroundLogger() {
6716
6844
  return logger;
6717
6845
  }
6718
6846
  function clearTestBackgroundLogger() {
6719
- _optionalChain([_internalGetGlobalState, 'call', _91 => _91(), 'optionalAccess', _92 => _92.setOverrideBgLogger, 'call', _93 => _93(null)]);
6847
+ _optionalChain([_internalGetGlobalState, 'call', _95 => _95(), 'optionalAccess', _96 => _96.setOverrideBgLogger, 'call', _97 => _97(null)]);
6720
6848
  }
6721
6849
  function initTestExperiment(experimentName, projectName) {
6722
6850
  setInitialTestState();
@@ -6871,6 +6999,17 @@ var HTTPConnection = class _HTTPConnection {
6871
6999
  });
6872
7000
  return await resp.json();
6873
7001
  }
7002
+ // Custom inspect for Node.js console.log
7003
+ [Symbol.for("nodejs.util.inspect.custom")]() {
7004
+ return `HTTPConnection {
7005
+ base_url: '${this.base_url}',
7006
+ token: '[REDACTED]'
7007
+ }`;
7008
+ }
7009
+ // Custom toString
7010
+ toString() {
7011
+ return `HTTPConnection(${this.base_url})`;
7012
+ }
6874
7013
  };
6875
7014
  var BaseAttachment = class {
6876
7015
 
@@ -7378,9 +7517,9 @@ async function permalink(slug, opts) {
7378
7517
  if (slug === "") {
7379
7518
  return NOOP_SPAN_PERMALINK;
7380
7519
  }
7381
- const state = _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _94 => _94.state]), () => ( _globalState));
7520
+ const state = _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _98 => _98.state]), () => ( _globalState));
7382
7521
  const getOrgName = async () => {
7383
- if (_optionalChain([opts, 'optionalAccess', _95 => _95.orgName])) {
7522
+ if (_optionalChain([opts, 'optionalAccess', _99 => _99.orgName])) {
7384
7523
  return opts.orgName;
7385
7524
  }
7386
7525
  await state.login({});
@@ -7390,7 +7529,7 @@ async function permalink(slug, opts) {
7390
7529
  return state.orgName;
7391
7530
  };
7392
7531
  const getAppUrl = async () => {
7393
- if (_optionalChain([opts, 'optionalAccess', _96 => _96.appUrl])) {
7532
+ if (_optionalChain([opts, 'optionalAccess', _100 => _100.appUrl])) {
7394
7533
  return opts.appUrl;
7395
7534
  }
7396
7535
  await state.login({});
@@ -7477,8 +7616,8 @@ var Logger = (_class16 = class {
7477
7616
 
7478
7617
 
7479
7618
  // For type identification.
7480
- __init44() {this.kind = "logger"}
7481
- constructor(state, lazyMetadata, logOptions = {}) {;_class16.prototype.__init44.call(this);
7619
+ __init45() {this.kind = "logger"}
7620
+ constructor(state, lazyMetadata, logOptions = {}) {;_class16.prototype.__init45.call(this);
7482
7621
  this.lazyMetadata = lazyMetadata;
7483
7622
  this._asyncFlush = logOptions.asyncFlush;
7484
7623
  this.computeMetadataArgs = logOptions.computeMetadataArgs;
@@ -7520,7 +7659,7 @@ var Logger = (_class16 = class {
7520
7659
  * @returns The `id` of the logged event.
7521
7660
  */
7522
7661
  log(event, options) {
7523
- if (this.calledStartSpan && !_optionalChain([options, 'optionalAccess', _97 => _97.allowConcurrentWithSpans])) {
7662
+ if (this.calledStartSpan && !_optionalChain([options, 'optionalAccess', _101 => _101.allowConcurrentWithSpans])) {
7524
7663
  throw new Error(
7525
7664
  "Cannot run toplevel `log` method while using spans. To log to the span, call `logger.traced` and then log with `span.log`"
7526
7665
  );
@@ -7588,12 +7727,12 @@ var Logger = (_class16 = class {
7588
7727
  state: this.state,
7589
7728
  ...startSpanParentArgs({
7590
7729
  state: this.state,
7591
- parent: _optionalChain([args, 'optionalAccess', _98 => _98.parent]),
7730
+ parent: _optionalChain([args, 'optionalAccess', _102 => _102.parent]),
7592
7731
  parentObjectType: this.parentObjectType(),
7593
7732
  parentObjectId: this.lazyId,
7594
7733
  parentComputeObjectMetadataArgs: this.computeMetadataArgs,
7595
- parentSpanIds: _optionalChain([args, 'optionalAccess', _99 => _99.parentSpanIds]),
7596
- propagatedEvent: _optionalChain([args, 'optionalAccess', _100 => _100.propagatedEvent])
7734
+ parentSpanIds: _optionalChain([args, 'optionalAccess', _103 => _103.parentSpanIds]),
7735
+ propagatedEvent: _optionalChain([args, 'optionalAccess', _104 => _104.propagatedEvent])
7597
7736
  }),
7598
7737
  defaultRootType: "task" /* TASK */
7599
7738
  });
@@ -7667,9 +7806,9 @@ function constructLogs3Data(items) {
7667
7806
  function now() {
7668
7807
  return (/* @__PURE__ */ new Date()).getTime();
7669
7808
  }
7670
- var TestBackgroundLogger = (_class17 = class {constructor() { _class17.prototype.__init45.call(this);_class17.prototype.__init46.call(this); }
7671
- __init45() {this.items = []}
7672
- __init46() {this.maskingFunction = null}
7809
+ var TestBackgroundLogger = (_class17 = class {constructor() { _class17.prototype.__init46.call(this);_class17.prototype.__init47.call(this); }
7810
+ __init46() {this.items = []}
7811
+ __init47() {this.maskingFunction = null}
7673
7812
  log(items) {
7674
7813
  this.items.push(items);
7675
7814
  }
@@ -7723,26 +7862,26 @@ var BACKGROUND_LOGGER_BASE_SLEEP_TIME_S = 1;
7723
7862
  var HTTPBackgroundLogger = (_class18 = class _HTTPBackgroundLogger {
7724
7863
 
7725
7864
 
7726
- __init47() {this.activeFlush = Promise.resolve()}
7727
- __init48() {this.activeFlushResolved = true}
7728
- __init49() {this.activeFlushError = void 0}
7865
+ __init48() {this.activeFlush = Promise.resolve()}
7866
+ __init49() {this.activeFlushResolved = true}
7867
+ __init50() {this.activeFlushError = void 0}
7729
7868
 
7730
- __init50() {this.maskingFunction = null}
7731
- __init51() {this.syncFlush = false}
7869
+ __init51() {this.maskingFunction = null}
7870
+ __init52() {this.syncFlush = false}
7732
7871
  // 6 MB for the AWS lambda gateway (from our own testing).
7733
- __init52() {this.maxRequestSize = 6 * 1024 * 1024}
7734
- __init53() {this.defaultBatchSize = 100}
7735
- __init54() {this.numTries = 3}
7736
- __init55() {this.queueDropExceedingMaxsize = DEFAULT_QUEUE_SIZE}
7737
- __init56() {this.queueDropLoggingPeriod = 60}
7738
- __init57() {this.failedPublishPayloadsDir = void 0}
7739
- __init58() {this.allPublishPayloadsDir = void 0}
7740
- __init59() {this._disabled = false}
7741
- __init60() {this.queueDropLoggingState = {
7872
+ __init53() {this.maxRequestSize = 6 * 1024 * 1024}
7873
+ __init54() {this.defaultBatchSize = 100}
7874
+ __init55() {this.numTries = 3}
7875
+ __init56() {this.queueDropExceedingMaxsize = DEFAULT_QUEUE_SIZE}
7876
+ __init57() {this.queueDropLoggingPeriod = 60}
7877
+ __init58() {this.failedPublishPayloadsDir = void 0}
7878
+ __init59() {this.allPublishPayloadsDir = void 0}
7879
+ __init60() {this._disabled = false}
7880
+ __init61() {this.queueDropLoggingState = {
7742
7881
  numDropped: 0,
7743
7882
  lastLoggedTimestamp: 0
7744
7883
  }}
7745
- constructor(apiConn, opts) {;_class18.prototype.__init47.call(this);_class18.prototype.__init48.call(this);_class18.prototype.__init49.call(this);_class18.prototype.__init50.call(this);_class18.prototype.__init51.call(this);_class18.prototype.__init52.call(this);_class18.prototype.__init53.call(this);_class18.prototype.__init54.call(this);_class18.prototype.__init55.call(this);_class18.prototype.__init56.call(this);_class18.prototype.__init57.call(this);_class18.prototype.__init58.call(this);_class18.prototype.__init59.call(this);_class18.prototype.__init60.call(this);
7884
+ constructor(apiConn, opts) {;_class18.prototype.__init48.call(this);_class18.prototype.__init49.call(this);_class18.prototype.__init50.call(this);_class18.prototype.__init51.call(this);_class18.prototype.__init52.call(this);_class18.prototype.__init53.call(this);_class18.prototype.__init54.call(this);_class18.prototype.__init55.call(this);_class18.prototype.__init56.call(this);_class18.prototype.__init57.call(this);_class18.prototype.__init58.call(this);_class18.prototype.__init59.call(this);_class18.prototype.__init60.call(this);_class18.prototype.__init61.call(this);
7746
7885
  opts = _nullishCoalesce(opts, () => ( {}));
7747
7886
  this.apiConn = apiConn;
7748
7887
  const syncFlushEnv = Number(isomorph_default.getEnv("BRAINTRUST_SYNC_FLUSH"));
@@ -7831,7 +7970,7 @@ var HTTPBackgroundLogger = (_class18 = class _HTTPBackgroundLogger {
7831
7970
  this.queue.clear();
7832
7971
  return;
7833
7972
  }
7834
- const batchSize = _nullishCoalesce(_optionalChain([args, 'optionalAccess', _101 => _101.batchSize]), () => ( this.defaultBatchSize));
7973
+ const batchSize = _nullishCoalesce(_optionalChain([args, 'optionalAccess', _105 => _105.batchSize]), () => ( this.defaultBatchSize));
7835
7974
  const wrappedItems = this.queue.drain();
7836
7975
  const [allItems, attachments] = await this.unwrapLazyValues(wrappedItems);
7837
7976
  if (allItems.length === 0) {
@@ -8080,10 +8219,10 @@ Error: ${errorText}`;
8080
8219
  } catch (err) {
8081
8220
  if (err instanceof AggregateError) {
8082
8221
  for (const e of err.errors) {
8083
- _optionalChain([this, 'access', _102 => _102.onFlushError, 'optionalCall', _103 => _103(e)]);
8222
+ _optionalChain([this, 'access', _106 => _106.onFlushError, 'optionalCall', _107 => _107(e)]);
8084
8223
  }
8085
8224
  } else {
8086
- _optionalChain([this, 'access', _104 => _104.onFlushError, 'optionalCall', _105 => _105(err)]);
8225
+ _optionalChain([this, 'access', _108 => _108.onFlushError, 'optionalCall', _109 => _109(err)]);
8087
8226
  }
8088
8227
  this.activeFlushError = err;
8089
8228
  } finally {
@@ -8696,24 +8835,24 @@ async function summarize(options = {}) {
8696
8835
  return await e.summarize(options);
8697
8836
  }
8698
8837
  function currentExperiment(options) {
8699
- const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _106 => _106.state]), () => ( _globalState));
8838
+ const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _110 => _110.state]), () => ( _globalState));
8700
8839
  return state.currentExperiment;
8701
8840
  }
8702
8841
  function currentLogger(options) {
8703
- const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _107 => _107.state]), () => ( _globalState));
8704
- return castLogger(state.currentLogger, _optionalChain([options, 'optionalAccess', _108 => _108.asyncFlush]));
8842
+ const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _111 => _111.state]), () => ( _globalState));
8843
+ return castLogger(state.currentLogger, _optionalChain([options, 'optionalAccess', _112 => _112.asyncFlush]));
8705
8844
  }
8706
8845
  function currentSpan(options) {
8707
- const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _109 => _109.state]), () => ( _globalState));
8846
+ const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _113 => _113.state]), () => ( _globalState));
8708
8847
  return _nullishCoalesce(state.currentSpan.getStore(), () => ( NOOP_SPAN));
8709
8848
  }
8710
8849
  function getSpanParentObject(options) {
8711
- const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _110 => _110.state]), () => ( _globalState));
8850
+ const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _114 => _114.state]), () => ( _globalState));
8712
8851
  const parentSpan = currentSpan({ state });
8713
8852
  if (!Object.is(parentSpan, NOOP_SPAN)) {
8714
8853
  return parentSpan;
8715
8854
  }
8716
- const parentStr = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _111 => _111.parent]), () => ( state.currentParent.getStore()));
8855
+ const parentStr = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _115 => _115.parent]), () => ( state.currentParent.getStore()));
8717
8856
  if (parentStr) return SpanComponentsV3.fromStr(parentStr);
8718
8857
  const experiment = currentExperiment();
8719
8858
  if (experiment) {
@@ -8742,7 +8881,7 @@ function traced(callback, args) {
8742
8881
  const { span, isSyncFlushLogger } = startSpanAndIsLogger(args);
8743
8882
  const ret = runCatchFinally(
8744
8883
  () => {
8745
- if (_nullishCoalesce(_optionalChain([args, 'optionalAccess', _112 => _112.setCurrent]), () => ( true))) {
8884
+ if (_nullishCoalesce(_optionalChain([args, 'optionalAccess', _116 => _116.setCurrent]), () => ( true))) {
8746
8885
  return withCurrent(span, callback);
8747
8886
  } else {
8748
8887
  return callback(span);
@@ -8754,7 +8893,7 @@ function traced(callback, args) {
8754
8893
  },
8755
8894
  () => span.end()
8756
8895
  );
8757
- if (_optionalChain([args, 'optionalAccess', _113 => _113.asyncFlush]) === void 0 || _optionalChain([args, 'optionalAccess', _114 => _114.asyncFlush])) {
8896
+ if (_optionalChain([args, 'optionalAccess', _117 => _117.asyncFlush]) === void 0 || _optionalChain([args, 'optionalAccess', _118 => _118.asyncFlush])) {
8758
8897
  return ret;
8759
8898
  } else {
8760
8899
  return (async () => {
@@ -8878,14 +9017,14 @@ function wrapTraced(fn, args) {
8878
9017
  };
8879
9018
  const hasExplicitInput = args && args.event && "input" in args.event && args.event.input !== void 0;
8880
9019
  const hasExplicitOutput = args && args.event && args.event.output !== void 0;
8881
- const noTraceIO = _optionalChain([args, 'optionalAccess', _115 => _115.noTraceIO]) || hasExplicitInput || hasExplicitOutput;
9020
+ const noTraceIO = _optionalChain([args, 'optionalAccess', _119 => _119.noTraceIO]) || hasExplicitInput || hasExplicitOutput;
8882
9021
  if (isGeneratorFunction(fn)) {
8883
9022
  return wrapTracedSyncGenerator(fn, spanArgs, !!noTraceIO);
8884
9023
  }
8885
9024
  if (isAsyncGeneratorFunction(fn)) {
8886
9025
  return wrapTracedAsyncGenerator(fn, spanArgs, !!noTraceIO);
8887
9026
  }
8888
- if (_optionalChain([args, 'optionalAccess', _116 => _116.asyncFlush])) {
9027
+ if (_optionalChain([args, 'optionalAccess', _120 => _120.asyncFlush])) {
8889
9028
  return (...fnArgs) => traced((span) => {
8890
9029
  if (!hasExplicitInput) {
8891
9030
  span.log({ input: fnArgs });
@@ -8923,17 +9062,17 @@ function startSpan(args) {
8923
9062
  return startSpanAndIsLogger(args).span;
8924
9063
  }
8925
9064
  async function flush(options) {
8926
- const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _117 => _117.state]), () => ( _globalState));
9065
+ const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _121 => _121.state]), () => ( _globalState));
8927
9066
  return await state.bgLogger().flush();
8928
9067
  }
8929
9068
  function setFetch(fetch2) {
8930
9069
  _globalState.setFetch(fetch2);
8931
9070
  }
8932
9071
  function startSpanAndIsLogger(args) {
8933
- const state = _nullishCoalesce(_optionalChain([args, 'optionalAccess', _118 => _118.state]), () => ( _globalState));
9072
+ const state = _nullishCoalesce(_optionalChain([args, 'optionalAccess', _122 => _122.state]), () => ( _globalState));
8934
9073
  const parentObject = getSpanParentObject({
8935
- asyncFlush: _optionalChain([args, 'optionalAccess', _119 => _119.asyncFlush]),
8936
- parent: _optionalChain([args, 'optionalAccess', _120 => _120.parent]),
9074
+ asyncFlush: _optionalChain([args, 'optionalAccess', _123 => _123.asyncFlush]),
9075
+ parent: _optionalChain([args, 'optionalAccess', _124 => _124.parent]),
8937
9076
  state
8938
9077
  });
8939
9078
  if (parentObject instanceof SpanComponentsV3) {
@@ -8950,14 +9089,14 @@ function startSpanAndIsLogger(args) {
8950
9089
  ),
8951
9090
  parentComputeObjectMetadataArgs: _nullishCoalesce(parentObject.data.compute_object_metadata_args, () => ( void 0)),
8952
9091
  parentSpanIds,
8953
- propagatedEvent: _nullishCoalesce(_optionalChain([args, 'optionalAccess', _121 => _121.propagatedEvent]), () => ( // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
9092
+ propagatedEvent: _nullishCoalesce(_optionalChain([args, 'optionalAccess', _125 => _125.propagatedEvent]), () => ( // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
8954
9093
  (_nullishCoalesce(parentObject.data.propagated_event, () => ( void 0)))))
8955
9094
  });
8956
9095
  return {
8957
9096
  span,
8958
9097
  isSyncFlushLogger: parentObject.data.object_type === 2 /* PROJECT_LOGS */ && // Since there's no parent logger here, we're free to choose the async flush
8959
9098
  // behavior, and therefore propagate along whatever we get from the arguments
8960
- _optionalChain([args, 'optionalAccess', _122 => _122.asyncFlush]) === false
9099
+ _optionalChain([args, 'optionalAccess', _126 => _126.asyncFlush]) === false
8961
9100
  };
8962
9101
  } else {
8963
9102
  const span = parentObject.startSpan(args);
@@ -9146,10 +9285,10 @@ function extractAttachments(event, attachments) {
9146
9285
  event[key] = value.reference;
9147
9286
  continue;
9148
9287
  }
9149
- if (_optionalChain([value, 'optionalAccess', _123 => _123.type]) === BRAINTRUST_ATTACHMENT && value.key && !value.uploader) {
9288
+ if (_optionalChain([value, 'optionalAccess', _127 => _127.type]) === BRAINTRUST_ATTACHMENT && value.key && !value.uploader) {
9150
9289
  continue;
9151
9290
  }
9152
- if (_optionalChain([value, 'optionalAccess', _124 => _124.reference, 'optionalAccess', _125 => _125.type]) === BRAINTRUST_ATTACHMENT && _optionalChain([value, 'optionalAccess', _126 => _126.uploader])) {
9291
+ if (_optionalChain([value, 'optionalAccess', _128 => _128.reference, 'optionalAccess', _129 => _129.type]) === BRAINTRUST_ATTACHMENT && _optionalChain([value, 'optionalAccess', _130 => _130.uploader])) {
9153
9292
  const attachment = new Attachment({
9154
9293
  data: value.dataDebugString,
9155
9294
  filename: value.reference.filename,
@@ -9216,13 +9355,13 @@ function validateAndSanitizeExperimentLogFullArgs(event, hasDataset) {
9216
9355
  var INTERNAL_BTQL_LIMIT = 1e3;
9217
9356
  var MAX_BTQL_ITERATIONS = 1e4;
9218
9357
  var ObjectFetcher = (_class19 = class {
9219
- constructor(objectType, pinnedVersion, mutateRecord, _internal_btql) {;_class19.prototype.__init61.call(this);
9358
+ constructor(objectType, pinnedVersion, mutateRecord, _internal_btql) {;_class19.prototype.__init62.call(this);
9220
9359
  this.objectType = objectType;
9221
9360
  this.pinnedVersion = pinnedVersion;
9222
9361
  this.mutateRecord = mutateRecord;
9223
9362
  this._internal_btql = _internal_btql;
9224
9363
  }
9225
- __init61() {this._fetchedData = void 0}
9364
+ __init62() {this._fetchedData = void 0}
9226
9365
  get id() {
9227
9366
  throw new Error("ObjectFetcher subclasses must have an 'id' attribute");
9228
9367
  }
@@ -9287,7 +9426,7 @@ var ObjectFetcher = (_class19 = class {
9287
9426
  throw new Error("Too many BTQL iterations");
9288
9427
  }
9289
9428
  }
9290
- this._fetchedData = this.mutateRecord ? _optionalChain([data, 'optionalAccess', _127 => _127.map, 'call', _128 => _128(this.mutateRecord)]) : data;
9429
+ this._fetchedData = this.mutateRecord ? _optionalChain([data, 'optionalAccess', _131 => _131.map, 'call', _132 => _132(this.mutateRecord)]) : data;
9291
9430
  }
9292
9431
  return this._fetchedData || [];
9293
9432
  }
@@ -9318,9 +9457,9 @@ var Experiment2 = (_class20 = class extends ObjectFetcher {
9318
9457
 
9319
9458
 
9320
9459
  // For type identification.
9321
- __init62() {this.kind = "experiment"}
9460
+ __init63() {this.kind = "experiment"}
9322
9461
  constructor(state, lazyMetadata, dataset) {
9323
- super("experiment", void 0, (r) => enrichAttachments(r, state));_class20.prototype.__init62.call(this);;
9462
+ super("experiment", void 0, (r) => enrichAttachments(r, state));_class20.prototype.__init63.call(this);;
9324
9463
  this.lazyMetadata = lazyMetadata;
9325
9464
  this.dataset = dataset;
9326
9465
  this.lastStartTime = getCurrentUnixTimestamp();
@@ -9368,7 +9507,7 @@ var Experiment2 = (_class20 = class extends ObjectFetcher {
9368
9507
  * @returns The `id` of the logged event.
9369
9508
  */
9370
9509
  log(event, options) {
9371
- if (this.calledStartSpan && !_optionalChain([options, 'optionalAccess', _129 => _129.allowConcurrentWithSpans])) {
9510
+ if (this.calledStartSpan && !_optionalChain([options, 'optionalAccess', _133 => _133.allowConcurrentWithSpans])) {
9372
9511
  throw new Error(
9373
9512
  "Cannot run toplevel `log` method while using spans. To log to the span, call `experiment.traced` and then log with `span.log`"
9374
9513
  );
@@ -9421,12 +9560,12 @@ var Experiment2 = (_class20 = class extends ObjectFetcher {
9421
9560
  state: this.state,
9422
9561
  ...startSpanParentArgs({
9423
9562
  state: this.state,
9424
- parent: _optionalChain([args, 'optionalAccess', _130 => _130.parent]),
9563
+ parent: _optionalChain([args, 'optionalAccess', _134 => _134.parent]),
9425
9564
  parentObjectType: this.parentObjectType(),
9426
9565
  parentObjectId: this.lazyId,
9427
9566
  parentComputeObjectMetadataArgs: void 0,
9428
9567
  parentSpanIds: void 0,
9429
- propagatedEvent: _optionalChain([args, 'optionalAccess', _131 => _131.propagatedEvent])
9568
+ propagatedEvent: _optionalChain([args, 'optionalAccess', _135 => _135.propagatedEvent])
9430
9569
  }),
9431
9570
  defaultRootType: "eval" /* EVAL */
9432
9571
  });
@@ -9627,8 +9766,8 @@ var SpanImpl = (_class21 = class _SpanImpl {
9627
9766
 
9628
9767
 
9629
9768
 
9630
- __init63() {this.kind = "span"}
9631
- constructor(args) {;_class21.prototype.__init63.call(this);
9769
+ __init64() {this.kind = "span"}
9770
+ constructor(args) {;_class21.prototype.__init64.call(this);
9632
9771
  this._state = args.state;
9633
9772
  const spanAttributes = _nullishCoalesce(args.spanAttributes, () => ( {}));
9634
9773
  const rawEvent = _nullishCoalesce(args.event, () => ( {}));
@@ -9668,13 +9807,17 @@ var SpanImpl = (_class21 = class _SpanImpl {
9668
9807
  },
9669
9808
  created: (/* @__PURE__ */ new Date()).toISOString()
9670
9809
  };
9671
- this._id = _nullishCoalesce(eventId, () => ( _uuid.v4.call(void 0, )));
9672
- this._spanId = _nullishCoalesce(args.spanId, () => ( _uuid.v4.call(void 0, )));
9810
+ this._id = _nullishCoalesce(eventId, () => ( this._state.idGenerator.getSpanId()));
9811
+ this._spanId = _nullishCoalesce(args.spanId, () => ( this._state.idGenerator.getSpanId()));
9673
9812
  if (args.parentSpanIds) {
9674
9813
  this._rootSpanId = args.parentSpanIds.rootSpanId;
9675
9814
  this._spanParents = "parentSpanIds" in args.parentSpanIds ? args.parentSpanIds.parentSpanIds : [args.parentSpanIds.spanId];
9676
9815
  } else {
9677
- this._rootSpanId = this._spanId;
9816
+ if (this._state.idGenerator.shareRootSpanId()) {
9817
+ this._rootSpanId = this._spanId;
9818
+ } else {
9819
+ this._rootSpanId = this._state.idGenerator.getTraceId();
9820
+ }
9678
9821
  this._spanParents = void 0;
9679
9822
  }
9680
9823
  this.isMerge = false;
@@ -9718,10 +9861,10 @@ var SpanImpl = (_class21 = class _SpanImpl {
9718
9861
  ...serializableInternalData,
9719
9862
  [IS_MERGE_FIELD]: this.isMerge
9720
9863
  });
9721
- if (_optionalChain([partialRecord, 'access', _132 => _132.metrics, 'optionalAccess', _133 => _133.end])) {
9722
- this.loggedEndTime = _optionalChain([partialRecord, 'access', _134 => _134.metrics, 'optionalAccess', _135 => _135.end]);
9864
+ if (_optionalChain([partialRecord, 'access', _136 => _136.metrics, 'optionalAccess', _137 => _137.end])) {
9865
+ this.loggedEndTime = _optionalChain([partialRecord, 'access', _138 => _138.metrics, 'optionalAccess', _139 => _139.end]);
9723
9866
  }
9724
- if ((_nullishCoalesce(partialRecord.tags, () => ( []))).length > 0 && _optionalChain([this, 'access', _136 => _136._spanParents, 'optionalAccess', _137 => _137.length])) {
9867
+ if ((_nullishCoalesce(partialRecord.tags, () => ( []))).length > 0 && _optionalChain([this, 'access', _140 => _140._spanParents, 'optionalAccess', _141 => _141.length])) {
9725
9868
  throw new Error("Tags can only be logged to the root span");
9726
9869
  }
9727
9870
  const computeRecord = async () => ({
@@ -9766,18 +9909,18 @@ var SpanImpl = (_class21 = class _SpanImpl {
9766
9909
  );
9767
9910
  }
9768
9911
  startSpan(args) {
9769
- const parentSpanIds = _optionalChain([args, 'optionalAccess', _138 => _138.parent]) ? void 0 : { spanId: this._spanId, rootSpanId: this._rootSpanId };
9912
+ const parentSpanIds = _optionalChain([args, 'optionalAccess', _142 => _142.parent]) ? void 0 : { spanId: this._spanId, rootSpanId: this._rootSpanId };
9770
9913
  return new _SpanImpl({
9771
9914
  state: this._state,
9772
9915
  ...args,
9773
9916
  ...startSpanParentArgs({
9774
9917
  state: this._state,
9775
- parent: _optionalChain([args, 'optionalAccess', _139 => _139.parent]),
9918
+ parent: _optionalChain([args, 'optionalAccess', _143 => _143.parent]),
9776
9919
  parentObjectType: this.parentObjectType,
9777
9920
  parentObjectId: this.parentObjectId,
9778
9921
  parentComputeObjectMetadataArgs: this.parentComputeObjectMetadataArgs,
9779
9922
  parentSpanIds,
9780
- propagatedEvent: _nullishCoalesce(_optionalChain([args, 'optionalAccess', _140 => _140.propagatedEvent]), () => ( this.propagatedEvent))
9923
+ propagatedEvent: _nullishCoalesce(_optionalChain([args, 'optionalAccess', _144 => _144.propagatedEvent]), () => ( this.propagatedEvent))
9781
9924
  })
9782
9925
  });
9783
9926
  }
@@ -9791,12 +9934,12 @@ var SpanImpl = (_class21 = class _SpanImpl {
9791
9934
  ...args,
9792
9935
  ...startSpanParentArgs({
9793
9936
  state: this._state,
9794
- parent: _optionalChain([args, 'optionalAccess', _141 => _141.parent]),
9937
+ parent: _optionalChain([args, 'optionalAccess', _145 => _145.parent]),
9795
9938
  parentObjectType: this.parentObjectType,
9796
9939
  parentObjectId: this.parentObjectId,
9797
9940
  parentComputeObjectMetadataArgs: this.parentComputeObjectMetadataArgs,
9798
9941
  parentSpanIds,
9799
- propagatedEvent: _nullishCoalesce(_optionalChain([args, 'optionalAccess', _142 => _142.propagatedEvent]), () => ( this.propagatedEvent))
9942
+ propagatedEvent: _nullishCoalesce(_optionalChain([args, 'optionalAccess', _146 => _146.propagatedEvent]), () => ( this.propagatedEvent))
9800
9943
  }),
9801
9944
  spanId
9802
9945
  });
@@ -9805,7 +9948,7 @@ var SpanImpl = (_class21 = class _SpanImpl {
9805
9948
  let endTime;
9806
9949
  let internalData = {};
9807
9950
  if (!this.loggedEndTime) {
9808
- endTime = _nullishCoalesce(_optionalChain([args, 'optionalAccess', _143 => _143.endTime]), () => ( getCurrentUnixTimestamp()));
9951
+ endTime = _nullishCoalesce(_optionalChain([args, 'optionalAccess', _147 => _147.endTime]), () => ( getCurrentUnixTimestamp()));
9809
9952
  internalData = { metrics: { end: endTime } };
9810
9953
  } else {
9811
9954
  endTime = this.loggedEndTime;
@@ -9848,8 +9991,8 @@ var SpanImpl = (_class21 = class _SpanImpl {
9848
9991
  const args = this.parentComputeObjectMetadataArgs;
9849
9992
  switch (this.parentObjectType) {
9850
9993
  case 2 /* PROJECT_LOGS */: {
9851
- const projectID = _optionalChain([args, 'optionalAccess', _144 => _144.project_id]) || this.parentObjectId.getSync().value;
9852
- const projectName = _optionalChain([args, 'optionalAccess', _145 => _145.project_name]);
9994
+ const projectID = _optionalChain([args, 'optionalAccess', _148 => _148.project_id]) || this.parentObjectId.getSync().value;
9995
+ const projectName = _optionalChain([args, 'optionalAccess', _149 => _149.project_name]);
9853
9996
  if (projectID) {
9854
9997
  return `${baseUrl}/object?object_type=project_logs&object_id=${projectID}&id=${this._id}`;
9855
9998
  } else if (projectName) {
@@ -9859,7 +10002,7 @@ var SpanImpl = (_class21 = class _SpanImpl {
9859
10002
  }
9860
10003
  }
9861
10004
  case 1 /* EXPERIMENT */: {
9862
- const expID = _optionalChain([args, 'optionalAccess', _146 => _146.experiment_id]) || _optionalChain([this, 'access', _147 => _147.parentObjectId, 'optionalAccess', _148 => _148.getSync, 'call', _149 => _149(), 'optionalAccess', _150 => _150.value]);
10005
+ const expID = _optionalChain([args, 'optionalAccess', _150 => _150.experiment_id]) || _optionalChain([this, 'access', _151 => _151.parentObjectId, 'optionalAccess', _152 => _152.getSync, 'call', _153 => _153(), 'optionalAccess', _154 => _154.value]);
9863
10006
  if (!expID) {
9864
10007
  return getErrPermlink("provide-experiment-id");
9865
10008
  } else {
@@ -9885,6 +10028,20 @@ var SpanImpl = (_class21 = class _SpanImpl {
9885
10028
  state() {
9886
10029
  return this._state;
9887
10030
  }
10031
+ // Custom inspect for Node.js console.log
10032
+ [Symbol.for("nodejs.util.inspect.custom")]() {
10033
+ return `SpanImpl {
10034
+ kind: '${this.kind}',
10035
+ id: '${this.id}',
10036
+ spanId: '${this.spanId}',
10037
+ rootSpanId: '${this.rootSpanId}',
10038
+ spanParents: ${JSON.stringify(this.spanParents)}
10039
+ }`;
10040
+ }
10041
+ // Custom toString
10042
+ toString() {
10043
+ return `SpanImpl(id=${this.id}, spanId=${this.spanId})`;
10044
+ }
9888
10045
  }, _class21);
9889
10046
  function splitLoggingData({
9890
10047
  event,
@@ -9935,13 +10092,13 @@ var Dataset2 = (_class22 = class extends ObjectFetcher {
9935
10092
  )
9936
10093
  ),
9937
10094
  _internal_btql
9938
- );_class22.prototype.__init64.call(this);_class22.prototype.__init65.call(this);;
10095
+ );_class22.prototype.__init65.call(this);_class22.prototype.__init66.call(this);;
9939
10096
  this.state = state;
9940
10097
  this.lazyMetadata = lazyMetadata;
9941
10098
  }
9942
10099
 
9943
- __init64() {this.__braintrust_dataset_marker = true}
9944
- __init65() {this.newRecords = 0}
10100
+ __init65() {this.__braintrust_dataset_marker = true}
10101
+ __init66() {this.newRecords = 0}
9945
10102
  get id() {
9946
10103
  return (async () => {
9947
10104
  return (await this.lazyMetadata.get()).dataset.id;
@@ -10264,14 +10421,14 @@ function renderPromptParams(params, args, options) {
10264
10421
  return params;
10265
10422
  }
10266
10423
  var Prompt2 = (_class23 = class _Prompt {
10267
- constructor(metadata, defaults, noTrace) {;_class23.prototype.__init66.call(this);_class23.prototype.__init67.call(this);
10424
+ constructor(metadata, defaults, noTrace) {;_class23.prototype.__init67.call(this);_class23.prototype.__init68.call(this);
10268
10425
  this.metadata = metadata;
10269
10426
  this.defaults = defaults;
10270
10427
  this.noTrace = noTrace;
10271
10428
  }
10272
10429
 
10273
- __init66() {this.hasParsedPromptData = false}
10274
- __init67() {this.__braintrust_prompt_marker = true}
10430
+ __init67() {this.hasParsedPromptData = false}
10431
+ __init68() {this.__braintrust_prompt_marker = true}
10275
10432
  get id() {
10276
10433
  return this.metadata.id;
10277
10434
  }
@@ -10285,13 +10442,13 @@ var Prompt2 = (_class23 = class _Prompt {
10285
10442
  return "slug" in this.metadata ? this.metadata.slug : this.metadata.id;
10286
10443
  }
10287
10444
  get prompt() {
10288
- return _optionalChain([this, 'access', _151 => _151.getParsedPromptData, 'call', _152 => _152(), 'optionalAccess', _153 => _153.prompt]);
10445
+ return _optionalChain([this, 'access', _155 => _155.getParsedPromptData, 'call', _156 => _156(), 'optionalAccess', _157 => _157.prompt]);
10289
10446
  }
10290
10447
  get version() {
10291
10448
  return this.metadata[TRANSACTION_ID_FIELD];
10292
10449
  }
10293
10450
  get options() {
10294
- return _optionalChain([this, 'access', _154 => _154.getParsedPromptData, 'call', _155 => _155(), 'optionalAccess', _156 => _156.options]) || {};
10451
+ return _optionalChain([this, 'access', _158 => _158.getParsedPromptData, 'call', _159 => _159(), 'optionalAccess', _160 => _160.options]) || {};
10295
10452
  }
10296
10453
  get promptData() {
10297
10454
  return this.getParsedPromptData();
@@ -10442,7 +10599,7 @@ var Prompt2 = (_class23 = class _Prompt {
10442
10599
  return {
10443
10600
  type: "chat",
10444
10601
  messages,
10445
- ..._optionalChain([prompt, 'access', _157 => _157.tools, 'optionalAccess', _158 => _158.trim, 'call', _159 => _159()]) ? {
10602
+ ..._optionalChain([prompt, 'access', _161 => _161.tools, 'optionalAccess', _162 => _162.trim, 'call', _163 => _163()]) ? {
10446
10603
  tools: render(prompt.tools)
10447
10604
  } : void 0
10448
10605
  };
@@ -10552,9 +10709,15 @@ async function getPromptVersions(projectId, promptId) {
10552
10709
  );
10553
10710
  }
10554
10711
  const result = await response.json();
10555
- return _optionalChain([result, 'access', _160 => _160.data, 'optionalAccess', _161 => _161.filter, 'call', _162 => _162(
10556
- (entry) => ["upsert", "merge"].includes(_optionalChain([entry, 'access', _163 => _163.audit_data, 'optionalAccess', _164 => _164.action]))
10557
- ), 'access', _165 => _165.map, 'call', _166 => _166((entry) => prettifyXact(entry._xact_id))]) || [];
10712
+ return _optionalChain([result, 'access', _164 => _164.data, 'optionalAccess', _165 => _165.filter, 'call', _166 => _166(
10713
+ (entry) => ["upsert", "merge"].includes(_optionalChain([entry, 'access', _167 => _167.audit_data, 'optionalAccess', _168 => _168.action]))
10714
+ ), 'access', _169 => _169.map, 'call', _170 => _170((entry) => prettifyXact(entry._xact_id))]) || [];
10715
+ }
10716
+ function resetIdGenStateForTests() {
10717
+ const state = _internalGetGlobalState();
10718
+ if (state) {
10719
+ state.resetIdGenState();
10720
+ }
10558
10721
  }
10559
10722
  var _exportsForTestingOnly = {
10560
10723
  extractAttachments,
@@ -10566,7 +10729,8 @@ var _exportsForTestingOnly = {
10566
10729
  setInitialTestState,
10567
10730
  initTestExperiment,
10568
10731
  isGeneratorFunction,
10569
- isAsyncGeneratorFunction
10732
+ isAsyncGeneratorFunction,
10733
+ resetIdGenStateForTests
10570
10734
  };
10571
10735
 
10572
10736
  // src/node.ts
@@ -10619,6 +10783,7 @@ _chunkCDBUTZMHjs.__export.call(void 0, exports_node_exports, {
10619
10783
  Experiment: () => Experiment2,
10620
10784
  ExternalAttachment: () => ExternalAttachment,
10621
10785
  FailedHTTPResponse: () => FailedHTTPResponse,
10786
+ IDGenerator: () => IDGenerator,
10622
10787
  INTERNAL_BTQL_LIMIT: () => INTERNAL_BTQL_LIMIT,
10623
10788
  LEGACY_CACHED_HEADER: () => LEGACY_CACHED_HEADER,
10624
10789
  LazyValue: () => LazyValue,
@@ -10626,6 +10791,7 @@ _chunkCDBUTZMHjs.__export.call(void 0, exports_node_exports, {
10626
10791
  NOOP_SPAN: () => NOOP_SPAN,
10627
10792
  NOOP_SPAN_PERMALINK: () => NOOP_SPAN_PERMALINK,
10628
10793
  NoopSpan: () => NoopSpan,
10794
+ OTELIDGenerator: () => OTELIDGenerator,
10629
10795
  Project: () => Project2,
10630
10796
  ProjectNameIdMap: () => ProjectNameIdMap,
10631
10797
  Prompt: () => Prompt2,
@@ -10637,6 +10803,7 @@ _chunkCDBUTZMHjs.__export.call(void 0, exports_node_exports, {
10637
10803
  SpanImpl: () => SpanImpl,
10638
10804
  TestBackgroundLogger: () => TestBackgroundLogger,
10639
10805
  ToolBuilder: () => ToolBuilder,
10806
+ UUIDGenerator: () => UUIDGenerator,
10640
10807
  X_CACHED_HEADER: () => X_CACHED_HEADER,
10641
10808
  _exportsForTestingOnly: () => _exportsForTestingOnly,
10642
10809
  _internalGetGlobalState: () => _internalGetGlobalState,
@@ -10647,10 +10814,12 @@ _chunkCDBUTZMHjs.__export.call(void 0, exports_node_exports, {
10647
10814
  currentExperiment: () => currentExperiment,
10648
10815
  currentLogger: () => currentLogger,
10649
10816
  currentSpan: () => currentSpan,
10817
+ deepCopyEvent: () => deepCopyEvent,
10650
10818
  defaultErrorScoreHandler: () => defaultErrorScoreHandler,
10651
10819
  deserializePlainStringAsJSON: () => deserializePlainStringAsJSON,
10652
10820
  devNullWritableStream: () => devNullWritableStream,
10653
10821
  flush: () => flush,
10822
+ getIdGenerator: () => getIdGenerator,
10654
10823
  getPromptVersions: () => getPromptVersions,
10655
10824
  getSpanParentObject: () => getSpanParentObject,
10656
10825
  graph: () => graph_framework_exports,
@@ -10694,6 +10863,8 @@ _chunkCDBUTZMHjs.__export.call(void 0, exports_node_exports, {
10694
10863
  wrapAISDK: () => wrapAISDK,
10695
10864
  wrapAISDKModel: () => wrapAISDKModel,
10696
10865
  wrapAnthropic: () => wrapAnthropic,
10866
+ wrapClaudeAgentSDK: () => wrapClaudeAgentSDK,
10867
+ wrapMastraAgent: () => wrapMastraAgent,
10697
10868
  wrapOpenAI: () => wrapOpenAI,
10698
10869
  wrapOpenAIv4: () => wrapOpenAIv4,
10699
10870
  wrapTraced: () => wrapTraced
@@ -11840,8 +12011,8 @@ function fitNameToSpaces(name, length) {
11840
12011
  }
11841
12012
  var BarProgressReporter = (_class24 = class {
11842
12013
 
11843
- __init68() {this.bars = {}}
11844
- constructor() {;_class24.prototype.__init68.call(this);
12014
+ __init69() {this.bars = {}}
12015
+ constructor() {;_class24.prototype.__init69.call(this);
11845
12016
  this.multiBar = new cliProgress.MultiBar(
11846
12017
  {
11847
12018
  clearOnComplete: false,
@@ -11884,9 +12055,9 @@ var Project2 = (_class25 = class {
11884
12055
 
11885
12056
 
11886
12057
 
11887
- __init69() {this._publishableCodeFunctions = []}
11888
- __init70() {this._publishablePrompts = []}
11889
- constructor(args) {;_class25.prototype.__init69.call(this);_class25.prototype.__init70.call(this);
12058
+ __init70() {this._publishableCodeFunctions = []}
12059
+ __init71() {this._publishablePrompts = []}
12060
+ constructor(args) {;_class25.prototype.__init70.call(this);_class25.prototype.__init71.call(this);
11890
12061
  _initializeSpanContext();
11891
12062
  this.name = "name" in args ? args.name : void 0;
11892
12063
  this.id = "id" in args ? args.id : void 0;
@@ -11931,10 +12102,10 @@ var Project2 = (_class25 = class {
11931
12102
  }
11932
12103
  }, _class25);
11933
12104
  var ToolBuilder = (_class26 = class {
11934
- constructor(project) {;_class26.prototype.__init71.call(this);
12105
+ constructor(project) {;_class26.prototype.__init72.call(this);
11935
12106
  this.project = project;
11936
12107
  }
11937
- __init71() {this.taskCounter = 0}
12108
+ __init72() {this.taskCounter = 0}
11938
12109
  // This type definition is just a catch all so that the implementation can be
11939
12110
  // less specific than the two more specific declarations above.
11940
12111
  create(opts) {
@@ -11961,10 +12132,10 @@ var ToolBuilder = (_class26 = class {
11961
12132
  }
11962
12133
  }, _class26);
11963
12134
  var ScorerBuilder = (_class27 = class {
11964
- constructor(project) {;_class27.prototype.__init72.call(this);
12135
+ constructor(project) {;_class27.prototype.__init73.call(this);
11965
12136
  this.project = project;
11966
12137
  }
11967
- __init72() {this.taskCounter = 0}
12138
+ __init73() {this.taskCounter = 0}
11968
12139
  create(opts) {
11969
12140
  this.taskCounter++;
11970
12141
  let resolvedName = opts.name;
@@ -12181,9 +12352,9 @@ function promptDefinitionToPromptData(promptDefinition, rawTools) {
12181
12352
  }
12182
12353
  };
12183
12354
  }
12184
- var ProjectNameIdMap = (_class28 = class {constructor() { _class28.prototype.__init73.call(this);_class28.prototype.__init74.call(this); }
12185
- __init73() {this.nameToId = {}}
12186
- __init74() {this.idToName = {}}
12355
+ var ProjectNameIdMap = (_class28 = class {constructor() { _class28.prototype.__init74.call(this);_class28.prototype.__init75.call(this); }
12356
+ __init74() {this.nameToId = {}}
12357
+ __init75() {this.idToName = {}}
12187
12358
  async getId(projectName) {
12188
12359
  if (!(projectName in this.nameToId)) {
12189
12360
  const response = await _internalGetGlobalState().appConn().post_json("api/project/register", {
@@ -12567,10 +12738,10 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
12567
12738
  span,
12568
12739
  parameters: _nullishCoalesce(parameters, () => ( {})),
12569
12740
  reportProgress: (event) => {
12570
- _optionalChain([stream, 'optionalCall', _167 => _167({
12741
+ _optionalChain([stream, 'optionalCall', _171 => _171({
12571
12742
  ...event,
12572
12743
  id: rootSpan.id,
12573
- origin: _optionalChain([baseEvent, 'access', _168 => _168.event, 'optionalAccess', _169 => _169.origin]),
12744
+ origin: _optionalChain([baseEvent, 'access', _172 => _172.event, 'optionalAccess', _173 => _173.origin]),
12574
12745
  name: evaluator.evalName,
12575
12746
  object_type: "task"
12576
12747
  })]);
@@ -12720,7 +12891,7 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
12720
12891
  ...scores
12721
12892
  },
12722
12893
  error: error2,
12723
- origin: _optionalChain([baseEvent, 'access', _170 => _170.event, 'optionalAccess', _171 => _171.origin])
12894
+ origin: _optionalChain([baseEvent, 'access', _174 => _174.event, 'optionalAccess', _175 => _175.origin])
12724
12895
  });
12725
12896
  };
12726
12897
  if (!experiment) {
@@ -12892,14 +13063,14 @@ _chunkCDBUTZMHjs.__export.call(void 0, graph_framework_exports, {
12892
13063
  unescapePath: () => unescapePath
12893
13064
  });
12894
13065
  var GraphBuilder = (_class29 = class {
12895
- __init75() {this.nodes = /* @__PURE__ */ new Map()}
12896
- __init76() {this.edges = {}}
12897
- __init77() {this.nodeLikeNodes = /* @__PURE__ */ new Map()}
13066
+ __init76() {this.nodes = /* @__PURE__ */ new Map()}
13067
+ __init77() {this.edges = {}}
13068
+ __init78() {this.nodeLikeNodes = /* @__PURE__ */ new Map()}
12898
13069
  // Maps node-like objects, like prompts, to their nodes
12899
13070
  // Special nodes
12900
13071
 
12901
13072
 
12902
- constructor() {;_class29.prototype.__init75.call(this);_class29.prototype.__init76.call(this);_class29.prototype.__init77.call(this);
13073
+ constructor() {;_class29.prototype.__init76.call(this);_class29.prototype.__init77.call(this);_class29.prototype.__init78.call(this);
12903
13074
  this.IN = this.createInputNode();
12904
13075
  this.OUT = this.createOutputNode();
12905
13076
  }
@@ -13038,12 +13209,12 @@ function proxyVariableToNode(proxy) {
13038
13209
  return [proxy.__node, proxy.__path];
13039
13210
  }
13040
13211
  var BaseNode = (_class30 = class {
13041
- constructor(graph, id) {;_class30.prototype.__init78.call(this);_class30.prototype.__init79.call(this);
13212
+ constructor(graph, id) {;_class30.prototype.__init79.call(this);_class30.prototype.__init80.call(this);
13042
13213
  this.graph = graph;
13043
13214
  this.id = id;
13044
13215
  }
13045
- __init78() {this.__type = "node"}
13046
- __init79() {this.dependencies = []}
13216
+ __init79() {this.__type = "node"}
13217
+ __init80() {this.dependencies = []}
13047
13218
  addDependency(dependency) {
13048
13219
  this.dependencies.push(dependency);
13049
13220
  }
@@ -13207,8 +13378,8 @@ function parseSpanFromResponseCreateParams(params) {
13207
13378
  }
13208
13379
  function parseEventFromResponseCreateResult(result) {
13209
13380
  const data = {};
13210
- if (_optionalChain([result, 'optionalAccess', _172 => _172.output]) !== void 0) {
13211
- data.output = result.output;
13381
+ if (_optionalChain([result, 'optionalAccess', _176 => _176.output]) !== void 0) {
13382
+ data.output = processImagesInOutput(result.output);
13212
13383
  }
13213
13384
  if (result) {
13214
13385
  const { output, usage, ...metadata } = result;
@@ -13216,9 +13387,38 @@ function parseEventFromResponseCreateResult(result) {
13216
13387
  data.metadata = metadata;
13217
13388
  }
13218
13389
  }
13219
- data.metrics = parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _173 => _173.usage]));
13390
+ data.metrics = parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _177 => _177.usage]));
13220
13391
  return data;
13221
13392
  }
13393
+ function processImagesInOutput(output) {
13394
+ if (Array.isArray(output)) {
13395
+ return output.map(processImagesInOutput);
13396
+ }
13397
+ if (isObject(output)) {
13398
+ if (output.type === "image_generation_call" && output.result && typeof output.result === "string") {
13399
+ const fileExtension = output.output_format || "png";
13400
+ const contentType = `image/${fileExtension}`;
13401
+ const baseFilename = output.revised_prompt && typeof output.revised_prompt === "string" ? output.revised_prompt.slice(0, 50).replace(/[^a-zA-Z0-9]/g, "_") : "generated_image";
13402
+ const filename = `${baseFilename}.${fileExtension}`;
13403
+ const binaryString = atob(output.result);
13404
+ const bytes = new Uint8Array(binaryString.length);
13405
+ for (let i = 0; i < binaryString.length; i++) {
13406
+ bytes[i] = binaryString.charCodeAt(i);
13407
+ }
13408
+ const blob = new Blob([bytes], { type: contentType });
13409
+ const attachment = new Attachment({
13410
+ data: blob,
13411
+ filename,
13412
+ contentType
13413
+ });
13414
+ return {
13415
+ ...output,
13416
+ result: attachment
13417
+ };
13418
+ }
13419
+ }
13420
+ return output;
13421
+ }
13222
13422
  function parseSpanFromResponseParseParams(params) {
13223
13423
  const spanArgs = {
13224
13424
  name: "openai.responses.parse",
@@ -13241,8 +13441,8 @@ function parseSpanFromResponseParseParams(params) {
13241
13441
  }
13242
13442
  function parseEventFromResponseParseResult(result) {
13243
13443
  const data = {};
13244
- if (_optionalChain([result, 'optionalAccess', _174 => _174.output]) !== void 0) {
13245
- data.output = result.output;
13444
+ if (_optionalChain([result, 'optionalAccess', _178 => _178.output]) !== void 0) {
13445
+ data.output = processImagesInOutput(result.output);
13246
13446
  }
13247
13447
  if (result) {
13248
13448
  const { output, usage, ...metadata } = result;
@@ -13250,7 +13450,7 @@ function parseEventFromResponseParseResult(result) {
13250
13450
  data.metadata = metadata;
13251
13451
  }
13252
13452
  }
13253
- data.metrics = parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _175 => _175.usage]));
13453
+ data.metrics = parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _179 => _179.usage]));
13254
13454
  return data;
13255
13455
  }
13256
13456
  function traceResponseCreateStream(stream, timedSpan) {
@@ -13267,7 +13467,7 @@ function traceResponseCreateStream(stream, timedSpan) {
13267
13467
  return result;
13268
13468
  }
13269
13469
  const item = result.value;
13270
- if (!item || !_optionalChain([item, 'optionalAccess', _176 => _176.type]) || !_optionalChain([item, 'optionalAccess', _177 => _177.response])) {
13470
+ if (!item || !_optionalChain([item, 'optionalAccess', _180 => _180.type]) || !_optionalChain([item, 'optionalAccess', _181 => _181.response])) {
13271
13471
  return result;
13272
13472
  }
13273
13473
  const event = parseLogFromItem(item);
@@ -13278,15 +13478,15 @@ function traceResponseCreateStream(stream, timedSpan) {
13278
13478
  };
13279
13479
  }
13280
13480
  function parseLogFromItem(item) {
13281
- if (!item || !_optionalChain([item, 'optionalAccess', _178 => _178.type]) || !_optionalChain([item, 'optionalAccess', _179 => _179.response])) {
13481
+ if (!item || !_optionalChain([item, 'optionalAccess', _182 => _182.type]) || !_optionalChain([item, 'optionalAccess', _183 => _183.response])) {
13282
13482
  return {};
13283
13483
  }
13284
13484
  const response = item.response;
13285
13485
  switch (item.type) {
13286
13486
  case "response.completed":
13287
13487
  const data = {};
13288
- if (_optionalChain([response, 'optionalAccess', _180 => _180.output]) !== void 0) {
13289
- data.output = response.output;
13488
+ if (_optionalChain([response, 'optionalAccess', _184 => _184.output]) !== void 0) {
13489
+ data.output = processImagesInOutput(response.output);
13290
13490
  }
13291
13491
  if (response) {
13292
13492
  const { usage, output, ...metadata } = response;
@@ -13294,7 +13494,7 @@ function parseLogFromItem(item) {
13294
13494
  data.metadata = metadata;
13295
13495
  }
13296
13496
  }
13297
- data.metrics = parseMetricsFromUsage(_optionalChain([response, 'optionalAccess', _181 => _181.usage]));
13497
+ data.metrics = parseMetricsFromUsage(_optionalChain([response, 'optionalAccess', _185 => _185.usage]));
13298
13498
  return data;
13299
13499
  default:
13300
13500
  return {};
@@ -13478,8 +13678,8 @@ function wrapOpenAIv4(openai) {
13478
13678
  const embeddingProxy = createEndpointProxy(openai.embeddings, wrapEmbeddings);
13479
13679
  const moderationProxy = createEndpointProxy(openai.moderations, wrapModerations);
13480
13680
  let betaProxy2;
13481
- if (_optionalChain([openai, 'access', _182 => _182.beta, 'optionalAccess', _183 => _183.chat, 'optionalAccess', _184 => _184.completions, 'optionalAccess', _185 => _185.stream])) {
13482
- const betaChatCompletionProxy = new Proxy(_optionalChain([openai, 'optionalAccess', _186 => _186.beta, 'optionalAccess', _187 => _187.chat, 'access', _188 => _188.completions]), {
13681
+ if (_optionalChain([openai, 'access', _186 => _186.beta, 'optionalAccess', _187 => _187.chat, 'optionalAccess', _188 => _188.completions, 'optionalAccess', _189 => _189.stream])) {
13682
+ const betaChatCompletionProxy = new Proxy(_optionalChain([openai, 'optionalAccess', _190 => _190.beta, 'optionalAccess', _191 => _191.chat, 'access', _192 => _192.completions]), {
13483
13683
  get(target, name, receiver) {
13484
13684
  const baseVal = Reflect.get(target, name, receiver);
13485
13685
  if (name === "parse") {
@@ -13527,7 +13727,7 @@ function wrapOpenAIv4(openai) {
13527
13727
  });
13528
13728
  }
13529
13729
  function logCompletionResponse(startTime, response, span) {
13530
- const metrics = parseMetricsFromUsage(_optionalChain([response, 'optionalAccess', _189 => _189.usage]));
13730
+ const metrics = parseMetricsFromUsage(_optionalChain([response, 'optionalAccess', _193 => _193.usage]));
13531
13731
  metrics.time_to_first_token = getCurrentUnixTimestamp() - startTime;
13532
13732
  span.log({
13533
13733
  output: response.choices,
@@ -13757,7 +13957,7 @@ function parseChatCompletionParams(params) {
13757
13957
  function processEmbeddingResponse(result, span) {
13758
13958
  span.log({
13759
13959
  output: { embedding_length: result.data[0].embedding.length },
13760
- metrics: parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _190 => _190.usage]))
13960
+ metrics: parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _194 => _194.usage]))
13761
13961
  });
13762
13962
  }
13763
13963
  function processModerationResponse(result, span) {
@@ -13787,10 +13987,10 @@ function postprocessStreamingResults(allResults) {
13787
13987
  if (result.usage) {
13788
13988
  metrics = {
13789
13989
  ...metrics,
13790
- ...parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _191 => _191.usage]))
13990
+ ...parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _195 => _195.usage]))
13791
13991
  };
13792
13992
  }
13793
- const delta = _optionalChain([result, 'access', _192 => _192.choices, 'optionalAccess', _193 => _193[0], 'optionalAccess', _194 => _194.delta]);
13993
+ const delta = _optionalChain([result, 'access', _196 => _196.choices, 'optionalAccess', _197 => _197[0], 'optionalAccess', _198 => _198.delta]);
13794
13994
  if (!delta) {
13795
13995
  continue;
13796
13996
  }
@@ -13892,21 +14092,24 @@ function extractAnthropicCacheTokens(cacheReadTokens = 0, cacheCreationTokens =
13892
14092
 
13893
14093
  // src/wrappers/ai-sdk-shared.ts
13894
14094
  function detectProviderFromResult(result) {
13895
- if (!_optionalChain([result, 'optionalAccess', _195 => _195.providerMetadata])) {
14095
+ if (!_optionalChain([result, 'optionalAccess', _199 => _199.providerMetadata])) {
13896
14096
  return void 0;
13897
14097
  }
13898
14098
  const keys = Object.keys(result.providerMetadata);
13899
- return _optionalChain([keys, 'optionalAccess', _196 => _196.at, 'call', _197 => _197(0)]);
14099
+ return _optionalChain([keys, 'optionalAccess', _200 => _200.at, 'call', _201 => _201(0)]);
13900
14100
  }
13901
14101
  function extractModelFromResult(result) {
13902
- if (_optionalChain([result, 'optionalAccess', _198 => _198.response, 'optionalAccess', _199 => _199.modelId])) {
14102
+ if (_optionalChain([result, 'optionalAccess', _202 => _202.response, 'optionalAccess', _203 => _203.modelId])) {
13903
14103
  return result.response.modelId;
13904
14104
  }
13905
- if (_optionalChain([result, 'optionalAccess', _200 => _200.request, 'optionalAccess', _201 => _201.body, 'optionalAccess', _202 => _202.model])) {
14105
+ if (_optionalChain([result, 'optionalAccess', _204 => _204.request, 'optionalAccess', _205 => _205.body, 'optionalAccess', _206 => _206.model])) {
13906
14106
  return result.request.body.model;
13907
14107
  }
13908
14108
  return void 0;
13909
14109
  }
14110
+ function extractModelFromWrapGenerateCallback(model) {
14111
+ return _optionalChain([model, 'optionalAccess', _207 => _207.modelId]);
14112
+ }
13910
14113
  function camelToSnake(str) {
13911
14114
  return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
13912
14115
  }
@@ -13950,7 +14153,7 @@ function normalizeUsageMetrics(usage, provider, providerMetadata) {
13950
14153
  metrics.prompt_cached_tokens = cachedInputTokens;
13951
14154
  }
13952
14155
  if (provider === "anthropic") {
13953
- const anthropicMetadata = _optionalChain([providerMetadata, 'optionalAccess', _203 => _203.anthropic]);
14156
+ const anthropicMetadata = _optionalChain([providerMetadata, 'optionalAccess', _208 => _208.anthropic]);
13954
14157
  if (anthropicMetadata) {
13955
14158
  const cacheReadTokens = getNumberProperty(anthropicMetadata.usage, "cache_read_input_tokens") || 0;
13956
14159
  const cacheCreationTokens = getNumberProperty(
@@ -13976,7 +14179,7 @@ function extractToolCallsFromSteps(steps) {
13976
14179
  if (!Array.isArray(steps)) return toolCalls;
13977
14180
  let idx = 0;
13978
14181
  for (const step of steps) {
13979
- const blocks = _optionalChain([step, 'optionalAccess', _204 => _204.content]);
14182
+ const blocks = _optionalChain([step, 'optionalAccess', _209 => _209.content]);
13980
14183
  if (!Array.isArray(blocks)) continue;
13981
14184
  for (const block of blocks) {
13982
14185
  if (block && typeof block === "object" && block.type === "tool-call") {
@@ -13999,7 +14202,7 @@ function buildAssistantOutputWithToolCalls(result, toolCalls) {
13999
14202
  {
14000
14203
  index: 0,
14001
14204
  logprobs: null,
14002
- finish_reason: _nullishCoalesce(normalizeFinishReason(_optionalChain([result, 'optionalAccess', _205 => _205.finishReason])), () => ( (toolCalls.length ? "tool_calls" : void 0))),
14205
+ finish_reason: _nullishCoalesce(normalizeFinishReason(_optionalChain([result, 'optionalAccess', _210 => _210.finishReason])), () => ( (toolCalls.length ? "tool_calls" : void 0))),
14003
14206
  message: {
14004
14207
  role: "assistant",
14005
14208
  tool_calls: toolCalls.length > 0 ? toolCalls : void 0
@@ -14048,7 +14251,7 @@ function wrapTools(tools) {
14048
14251
  return wrappedTools;
14049
14252
  }
14050
14253
  function extractInput(params) {
14051
- return _nullishCoalesce(_nullishCoalesce(_optionalChain([params, 'optionalAccess', _206 => _206.prompt]), () => ( _optionalChain([params, 'optionalAccess', _207 => _207.messages]))), () => ( _optionalChain([params, 'optionalAccess', _208 => _208.system])));
14254
+ return _nullishCoalesce(_nullishCoalesce(_optionalChain([params, 'optionalAccess', _211 => _211.prompt]), () => ( _optionalChain([params, 'optionalAccess', _212 => _212.messages]))), () => ( _optionalChain([params, 'optionalAccess', _213 => _213.system])));
14052
14255
  }
14053
14256
  function wrapStreamObject(iterable, onFirst) {
14054
14257
  let sawFirst = false;
@@ -14079,7 +14282,11 @@ var V2_EXCLUDE_KEYS = /* @__PURE__ */ new Set([
14079
14282
  ]);
14080
14283
  function BraintrustMiddleware(config = {}) {
14081
14284
  return {
14082
- wrapGenerate: async ({ doGenerate, params }) => {
14285
+ wrapGenerate: async ({
14286
+ doGenerate,
14287
+ params,
14288
+ model: modelFromWrapGenerate
14289
+ }) => {
14083
14290
  const spanArgs = {
14084
14291
  name: "ai-sdk.generateText",
14085
14292
  spanAttributes: {
@@ -14106,13 +14313,20 @@ function BraintrustMiddleware(config = {}) {
14106
14313
  const model = extractModelFromResult(result);
14107
14314
  if (model !== void 0) {
14108
14315
  metadata.model = model;
14316
+ } else if (modelFromWrapGenerate) {
14317
+ const modelId = extractModelFromWrapGenerateCallback(
14318
+ modelFromWrapGenerate
14319
+ );
14320
+ if (modelId) {
14321
+ metadata.model = modelId;
14322
+ }
14109
14323
  }
14110
- let toolCalls = extractToolCallsFromSteps(_optionalChain([result, 'optionalAccess', _209 => _209.steps]));
14324
+ let toolCalls = extractToolCallsFromSteps(_optionalChain([result, 'optionalAccess', _214 => _214.steps]));
14111
14325
  if (!toolCalls || toolCalls.length === 0) {
14112
- toolCalls = extractToolCallsFromBlocks(_optionalChain([result, 'optionalAccess', _210 => _210.content]));
14326
+ toolCalls = extractToolCallsFromBlocks(_optionalChain([result, 'optionalAccess', _215 => _215.content]));
14113
14327
  }
14114
14328
  span.log({
14115
- output: toolCalls.length > 0 ? buildAssistantOutputWithToolCalls(result, toolCalls) : _optionalChain([result, 'optionalAccess', _211 => _211.content]),
14329
+ output: toolCalls.length > 0 ? buildAssistantOutputWithToolCalls(result, toolCalls) : _optionalChain([result, 'optionalAccess', _216 => _216.content]),
14116
14330
  metadata,
14117
14331
  metrics: normalizeUsageMetrics(
14118
14332
  result.usage,
@@ -14245,7 +14459,7 @@ function BraintrustMiddleware(config = {}) {
14245
14459
  // src/wrappers/ai-sdk-v1.ts
14246
14460
  function wrapAISDKModel(model) {
14247
14461
  const m = model;
14248
- if (_optionalChain([m, 'optionalAccess', _212 => _212.specificationVersion]) === "v1" && typeof _optionalChain([m, 'optionalAccess', _213 => _213.provider]) === "string" && typeof _optionalChain([m, 'optionalAccess', _214 => _214.modelId]) === "string") {
14462
+ if (_optionalChain([m, 'optionalAccess', _217 => _217.specificationVersion]) === "v1" && typeof _optionalChain([m, 'optionalAccess', _218 => _218.provider]) === "string" && typeof _optionalChain([m, 'optionalAccess', _219 => _219.modelId]) === "string") {
14249
14463
  return new BraintrustLanguageModelWrapper(m);
14250
14464
  } else {
14251
14465
  console.warn("Unsupported AI SDK model. Not wrapping.");
@@ -14301,10 +14515,10 @@ var BraintrustLanguageModelWrapper = class {
14301
14515
  metrics: {
14302
14516
  time_to_first_token: getCurrentUnixTimestamp() - startTime,
14303
14517
  tokens: !isEmpty(ret.usage) ? ret.usage.promptTokens + ret.usage.completionTokens : void 0,
14304
- prompt_tokens: _optionalChain([ret, 'access', _215 => _215.usage, 'optionalAccess', _216 => _216.promptTokens]),
14305
- completion_tokens: _optionalChain([ret, 'access', _217 => _217.usage, 'optionalAccess', _218 => _218.completionTokens]),
14518
+ prompt_tokens: _optionalChain([ret, 'access', _220 => _220.usage, 'optionalAccess', _221 => _221.promptTokens]),
14519
+ completion_tokens: _optionalChain([ret, 'access', _222 => _222.usage, 'optionalAccess', _223 => _223.completionTokens]),
14306
14520
  cached: parseCachedHeader(
14307
- _nullishCoalesce(_optionalChain([ret, 'access', _219 => _219.rawResponse, 'optionalAccess', _220 => _220.headers, 'optionalAccess', _221 => _221[X_CACHED_HEADER]]), () => ( _optionalChain([ret, 'access', _222 => _222.rawResponse, 'optionalAccess', _223 => _223.headers, 'optionalAccess', _224 => _224[LEGACY_CACHED_HEADER]])))
14521
+ _nullishCoalesce(_optionalChain([ret, 'access', _224 => _224.rawResponse, 'optionalAccess', _225 => _225.headers, 'optionalAccess', _226 => _226[X_CACHED_HEADER]]), () => ( _optionalChain([ret, 'access', _227 => _227.rawResponse, 'optionalAccess', _228 => _228.headers, 'optionalAccess', _229 => _229[LEGACY_CACHED_HEADER]])))
14308
14522
  )
14309
14523
  }
14310
14524
  });
@@ -14396,10 +14610,10 @@ var BraintrustLanguageModelWrapper = class {
14396
14610
  metrics: {
14397
14611
  time_to_first_token,
14398
14612
  tokens: !isEmpty(usage) ? usage.promptTokens + usage.completionTokens : void 0,
14399
- prompt_tokens: _optionalChain([usage, 'optionalAccess', _225 => _225.promptTokens]),
14400
- completion_tokens: _optionalChain([usage, 'optionalAccess', _226 => _226.completionTokens]),
14613
+ prompt_tokens: _optionalChain([usage, 'optionalAccess', _230 => _230.promptTokens]),
14614
+ completion_tokens: _optionalChain([usage, 'optionalAccess', _231 => _231.completionTokens]),
14401
14615
  cached: parseCachedHeader(
14402
- _nullishCoalesce(_optionalChain([ret, 'access', _227 => _227.rawResponse, 'optionalAccess', _228 => _228.headers, 'optionalAccess', _229 => _229[X_CACHED_HEADER]]), () => ( _optionalChain([ret, 'access', _230 => _230.rawResponse, 'optionalAccess', _231 => _231.headers, 'optionalAccess', _232 => _232[LEGACY_CACHED_HEADER]])))
14616
+ _nullishCoalesce(_optionalChain([ret, 'access', _232 => _232.rawResponse, 'optionalAccess', _233 => _233.headers, 'optionalAccess', _234 => _234[X_CACHED_HEADER]]), () => ( _optionalChain([ret, 'access', _235 => _235.rawResponse, 'optionalAccess', _236 => _236.headers, 'optionalAccess', _237 => _237[LEGACY_CACHED_HEADER]])))
14403
14617
  )
14404
14618
  }
14405
14619
  });
@@ -14446,7 +14660,7 @@ function postProcessPrompt(prompt) {
14446
14660
  return [
14447
14661
  {
14448
14662
  role: "assistant",
14449
- content: _optionalChain([textPart, 'optionalAccess', _233 => _233.text]),
14663
+ content: _optionalChain([textPart, 'optionalAccess', _238 => _238.text]),
14450
14664
  ...toolCallParts.length > 0 ? {
14451
14665
  tool_calls: toolCallParts.map((part) => ({
14452
14666
  id: part.toolCallId,
@@ -14554,7 +14768,7 @@ function wrapAISDK(ai) {
14554
14768
  });
14555
14769
  const provider = detectProviderFromResult(result);
14556
14770
  const model = extractModelFromResult(result);
14557
- const finishReason = normalizeFinishReason(_optionalChain([result, 'optionalAccess', _234 => _234.finishReason]));
14771
+ const finishReason = normalizeFinishReason(_optionalChain([result, 'optionalAccess', _239 => _239.finishReason]));
14558
14772
  span.log({
14559
14773
  input: extractInput(params),
14560
14774
  output: result.text,
@@ -14647,9 +14861,9 @@ function wrapAISDK(ai) {
14647
14861
  }
14648
14862
  const provider = detectProviderFromResult(event);
14649
14863
  const model = extractModelFromResult(event);
14650
- const finishReason = normalizeFinishReason(_optionalChain([event, 'optionalAccess', _235 => _235.finishReason]));
14864
+ const finishReason = normalizeFinishReason(_optionalChain([event, 'optionalAccess', _240 => _240.finishReason]));
14651
14865
  span.log({
14652
- output: _optionalChain([event, 'optionalAccess', _236 => _236.text]),
14866
+ output: _optionalChain([event, 'optionalAccess', _241 => _241.text]),
14653
14867
  metadata: {
14654
14868
  ...extractModelParameters(params, V3_EXCLUDE_KEYS),
14655
14869
  ...provider ? { provider } : {},
@@ -14707,9 +14921,9 @@ function wrapAISDK(ai) {
14707
14921
  }
14708
14922
  const provider = detectProviderFromResult(event);
14709
14923
  const model = extractModelFromResult(event);
14710
- const finishReason = normalizeFinishReason(_optionalChain([event, 'optionalAccess', _237 => _237.finishReason]));
14924
+ const finishReason = normalizeFinishReason(_optionalChain([event, 'optionalAccess', _242 => _242.finishReason]));
14711
14925
  span.log({
14712
- output: _optionalChain([event, 'optionalAccess', _238 => _238.object]),
14926
+ output: _optionalChain([event, 'optionalAccess', _243 => _243.object]),
14713
14927
  metadata: {
14714
14928
  ...extractModelParameters(params, V3_EXCLUDE_KEYS),
14715
14929
  ...provider ? { provider } : {},
@@ -14755,6 +14969,146 @@ function wrapAISDK(ai) {
14755
14969
  };
14756
14970
  }
14757
14971
 
14972
+ // src/wrappers/mastra.ts
14973
+ var aiSDKFormatWarning = false;
14974
+ function wrapMastraAgent(agent, options) {
14975
+ const prefix = _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_optionalChain([options, 'optionalAccess', _244 => _244.name]), () => ( _optionalChain([options, 'optionalAccess', _245 => _245.span_name]))), () => ( agent.name)), () => ( "Agent"));
14976
+ if (!hasAllMethods(agent)) {
14977
+ return agent;
14978
+ }
14979
+ if (agent.tools) {
14980
+ agent.__setTools(wrapTools(agent.tools));
14981
+ }
14982
+ return new Proxy(agent, {
14983
+ get(target, prop, receiver) {
14984
+ const value = Reflect.get(target, prop, receiver);
14985
+ if (prop === "generateVNext" && typeof value === "function") {
14986
+ return wrapGenerateVNext(value, target, prefix);
14987
+ }
14988
+ if (prop === "streamVNext" && typeof value === "function") {
14989
+ return wrapStreamVNext(value, target, prefix);
14990
+ }
14991
+ if (typeof value === "function") {
14992
+ return value.bind(target);
14993
+ }
14994
+ return value;
14995
+ }
14996
+ });
14997
+ }
14998
+ function hasAllMethods(a) {
14999
+ return typeof a.generateVNext === "function" && typeof a.streamVNext === "function";
15000
+ }
15001
+ function wrapGenerateVNext(original, target, prefix) {
15002
+ return function(...args) {
15003
+ const input = args[0];
15004
+ return traced(
15005
+ async (span) => {
15006
+ const result = await original.apply(target, args);
15007
+ const provider = detectProviderFromResult(result);
15008
+ const model = extractModelFromResult(result);
15009
+ const finishReason = normalizeFinishReason(_optionalChain([result, 'optionalAccess', _246 => _246.finishReason]));
15010
+ const metrics = _optionalChain([result, 'optionalAccess', _247 => _247.usage]) ? normalizeUsageMetrics(
15011
+ result.usage,
15012
+ provider,
15013
+ result.providerMetadata
15014
+ ) : {};
15015
+ span.log({
15016
+ input,
15017
+ output: result,
15018
+ metadata: {
15019
+ agent_name: _nullishCoalesce(target.name, () => ( prefix)),
15020
+ ...provider ? { provider } : {},
15021
+ ...model ? { model } : {},
15022
+ ...finishReason ? { finish_reason: finishReason } : {}
15023
+ },
15024
+ metrics
15025
+ });
15026
+ return result;
15027
+ },
15028
+ {
15029
+ name: `${prefix}.generateVNext`
15030
+ }
15031
+ );
15032
+ };
15033
+ }
15034
+ function wrapStreamVNext(original, target, prefix) {
15035
+ return function(...args) {
15036
+ const input = args[0];
15037
+ const span = startSpan({
15038
+ name: `${prefix}.streamVNext`,
15039
+ event: {
15040
+ input,
15041
+ metadata: {
15042
+ agent_name: _nullishCoalesce(target.name, () => ( prefix))
15043
+ }
15044
+ }
15045
+ });
15046
+ const baseOpts = typeof args[1] === "object" && args[1] !== null ? args[1] : {};
15047
+ if (baseOpts.format && baseOpts.format !== "aisdk" && !aiSDKFormatWarning) {
15048
+ aiSDKFormatWarning = true;
15049
+ console.warn(
15050
+ `Braintrust Mastra wrapper: For best compatibility, use { format: 'aisdk' } (AI SDK v5) instead of format: '${baseOpts.format}'. See https://mastra.ai/en/docs/frameworks/agentic-uis/ai-sdk for more details.`
15051
+ );
15052
+ }
15053
+ const wrappedOpts = {
15054
+ ...baseOpts,
15055
+ format: baseOpts.format || "aisdk"
15056
+ // Default to AI SDK v5 format if not specified
15057
+ };
15058
+ const userOnChunk = _optionalChain([baseOpts, 'optionalAccess', _248 => _248.onChunk]);
15059
+ const userOnFinish = _optionalChain([baseOpts, 'optionalAccess', _249 => _249.onFinish]);
15060
+ const userOnError = _optionalChain([baseOpts, 'optionalAccess', _250 => _250.onError]);
15061
+ const startTime = Date.now();
15062
+ let receivedFirst = false;
15063
+ wrappedOpts.onChunk = (chunk) => {
15064
+ try {
15065
+ _optionalChain([userOnChunk, 'optionalCall', _251 => _251(chunk)]);
15066
+ } finally {
15067
+ if (!receivedFirst) {
15068
+ receivedFirst = true;
15069
+ span.log({
15070
+ metrics: { time_to_first_token: (Date.now() - startTime) / 1e3 }
15071
+ });
15072
+ }
15073
+ }
15074
+ };
15075
+ wrappedOpts.onFinish = async (event) => {
15076
+ try {
15077
+ await _optionalChain([userOnFinish, 'optionalCall', _252 => _252(event)]);
15078
+ } finally {
15079
+ const e = event;
15080
+ const provider = detectProviderFromResult(e);
15081
+ const model = extractModelFromResult(e);
15082
+ const finishReason = normalizeFinishReason(_optionalChain([e, 'optionalAccess', _253 => _253.finishReason]));
15083
+ const metrics = _optionalChain([e, 'optionalAccess', _254 => _254.usage]) ? normalizeUsageMetrics(e.usage, provider, e.providerMetadata) : {};
15084
+ span.log({
15085
+ output: _nullishCoalesce(_nullishCoalesce(e.text, () => ( e.content)), () => ( e)),
15086
+ metadata: {
15087
+ agent_name: _nullishCoalesce(target.name, () => ( prefix)),
15088
+ ...provider ? { provider } : {},
15089
+ ...model ? { model } : {},
15090
+ ...finishReason ? { finish_reason: finishReason } : {}
15091
+ },
15092
+ metrics
15093
+ });
15094
+ span.end();
15095
+ }
15096
+ };
15097
+ wrappedOpts.onError = async (err) => {
15098
+ try {
15099
+ await _optionalChain([userOnError, 'optionalCall', _255 => _255(err)]);
15100
+ } finally {
15101
+ logError(span, err);
15102
+ span.end();
15103
+ }
15104
+ };
15105
+ return withCurrent(
15106
+ span,
15107
+ () => original.apply(target, [args[0], wrappedOpts, ...args.slice(2)])
15108
+ );
15109
+ };
15110
+ }
15111
+
14758
15112
  // src/wrappers/anthropic.ts
14759
15113
  function wrapAnthropic(anthropic) {
14760
15114
  const au = anthropic;
@@ -14920,9 +15274,9 @@ function streamNextProxy(stream, sspan) {
14920
15274
  return result;
14921
15275
  }
14922
15276
  const item = result.value;
14923
- switch (_optionalChain([item, 'optionalAccess', _239 => _239.type])) {
15277
+ switch (_optionalChain([item, 'optionalAccess', _256 => _256.type])) {
14924
15278
  case "message_start":
14925
- const msg = _optionalChain([item, 'optionalAccess', _240 => _240.message]);
15279
+ const msg = _optionalChain([item, 'optionalAccess', _257 => _257.message]);
14926
15280
  if (msg) {
14927
15281
  const event = parseEventFromMessage(msg);
14928
15282
  totals = { ...totals, ...event.metrics };
@@ -14930,20 +15284,20 @@ function streamNextProxy(stream, sspan) {
14930
15284
  }
14931
15285
  break;
14932
15286
  case "content_block_delta":
14933
- if (_optionalChain([item, 'access', _241 => _241.delta, 'optionalAccess', _242 => _242.type]) === "text_delta") {
14934
- const text = _optionalChain([item, 'optionalAccess', _243 => _243.delta, 'optionalAccess', _244 => _244.text]);
15287
+ if (_optionalChain([item, 'access', _258 => _258.delta, 'optionalAccess', _259 => _259.type]) === "text_delta") {
15288
+ const text = _optionalChain([item, 'optionalAccess', _260 => _260.delta, 'optionalAccess', _261 => _261.text]);
14935
15289
  if (text) {
14936
15290
  deltas.push(text);
14937
15291
  }
14938
15292
  }
14939
15293
  break;
14940
15294
  case "message_delta":
14941
- const usage = _optionalChain([item, 'optionalAccess', _245 => _245.usage]);
15295
+ const usage = _optionalChain([item, 'optionalAccess', _262 => _262.usage]);
14942
15296
  if (usage) {
14943
15297
  const metrics = parseMetricsFromUsage2(usage);
14944
15298
  totals = { ...totals, ...metrics };
14945
15299
  }
14946
- const delta = _optionalChain([item, 'optionalAccess', _246 => _246.delta]);
15300
+ const delta = _optionalChain([item, 'optionalAccess', _263 => _263.delta]);
14947
15301
  if (delta) {
14948
15302
  metadata = { ...metadata, ...delta };
14949
15303
  }
@@ -14955,8 +15309,8 @@ function streamNextProxy(stream, sspan) {
14955
15309
  };
14956
15310
  }
14957
15311
  function parseEventFromMessage(message) {
14958
- const output = _optionalChain([message, 'optionalAccess', _247 => _247.content]) || null;
14959
- const metrics = parseMetricsFromUsage2(_optionalChain([message, 'optionalAccess', _248 => _248.usage]));
15312
+ const output = message ? { role: message.role, content: message.content } : null;
15313
+ const metrics = parseMetricsFromUsage2(_optionalChain([message, 'optionalAccess', _264 => _264.usage]));
14960
15314
  const metas = ["stop_reason", "stop_sequence"];
14961
15315
  const metadata = {};
14962
15316
  for (const m of metas) {
@@ -14995,6 +15349,282 @@ function coalesceInput(messages, system) {
14995
15349
  return input;
14996
15350
  }
14997
15351
 
15352
+ // src/wrappers/claude-agent-sdk.ts
15353
+ function filterSerializableOptions(options) {
15354
+ const allowedKeys = [
15355
+ "model",
15356
+ "maxTurns",
15357
+ "cwd",
15358
+ "continue",
15359
+ "allowedTools",
15360
+ "disallowedTools",
15361
+ "additionalDirectories",
15362
+ "permissionMode",
15363
+ "debug",
15364
+ "apiKey",
15365
+ "apiKeySource",
15366
+ "agentName",
15367
+ "instructions"
15368
+ ];
15369
+ const filtered = {};
15370
+ for (const key of allowedKeys) {
15371
+ if (options[key] !== void 0) {
15372
+ filtered[key] = options[key];
15373
+ }
15374
+ }
15375
+ return filtered;
15376
+ }
15377
+ function wrapClaudeAgentQuery(queryFn, defaultThis) {
15378
+ const proxy = new Proxy(queryFn, {
15379
+ apply(target, thisArg, argArray) {
15380
+ const params = _nullishCoalesce(argArray[0], () => ( {}));
15381
+ const { prompt, options = {} } = params;
15382
+ const span = startSpan({
15383
+ name: "Claude Agent",
15384
+ spanAttributes: {
15385
+ type: "task" /* TASK */
15386
+ },
15387
+ event: {
15388
+ input: typeof prompt === "string" ? prompt : { type: "streaming", description: "AsyncIterable<SDKMessage>" },
15389
+ metadata: filterSerializableOptions(options)
15390
+ }
15391
+ });
15392
+ const finalResults = [];
15393
+ let finalUsageMetrics;
15394
+ let accumulatedOutputTokens = 0;
15395
+ let currentMessageId;
15396
+ let currentMessageStartTime = getCurrentUnixTimestamp();
15397
+ const currentMessages = [];
15398
+ const createLLMSpan = async () => {
15399
+ const finalMessageContent = await _createLLMSpanForMessages(
15400
+ currentMessages,
15401
+ prompt,
15402
+ finalResults,
15403
+ options,
15404
+ currentMessageStartTime,
15405
+ await span.export()
15406
+ );
15407
+ if (finalMessageContent) {
15408
+ finalResults.push(finalMessageContent);
15409
+ }
15410
+ const lastMessage = currentMessages[currentMessages.length - 1];
15411
+ if (_optionalChain([lastMessage, 'optionalAccess', _265 => _265.message, 'optionalAccess', _266 => _266.usage])) {
15412
+ const outputTokens = getNumberProperty(lastMessage.message.usage, "output_tokens") || 0;
15413
+ accumulatedOutputTokens += outputTokens;
15414
+ }
15415
+ currentMessages.length = 0;
15416
+ };
15417
+ const wrappedGenerator = async function* () {
15418
+ try {
15419
+ const invocationTarget = thisArg === proxy || thisArg === void 0 ? _nullishCoalesce(defaultThis, () => ( thisArg)) : thisArg;
15420
+ const generator = withCurrent(
15421
+ span,
15422
+ () => Reflect.apply(target, invocationTarget, argArray)
15423
+ );
15424
+ for await (const message of generator) {
15425
+ const currentTime = getCurrentUnixTimestamp();
15426
+ const messageId = _optionalChain([message, 'access', _267 => _267.message, 'optionalAccess', _268 => _268.id]);
15427
+ if (messageId && messageId !== currentMessageId) {
15428
+ await createLLMSpan();
15429
+ currentMessageId = messageId;
15430
+ currentMessageStartTime = currentTime;
15431
+ }
15432
+ if (message.type === "assistant" && _optionalChain([message, 'access', _269 => _269.message, 'optionalAccess', _270 => _270.usage])) {
15433
+ currentMessages.push(message);
15434
+ }
15435
+ if (message.type === "result" && message.usage) {
15436
+ finalUsageMetrics = _extractUsageFromMessage(message);
15437
+ if (currentMessages.length > 0 && finalUsageMetrics.completion_tokens !== void 0) {
15438
+ const lastMessage = currentMessages[currentMessages.length - 1];
15439
+ if (_optionalChain([lastMessage, 'optionalAccess', _271 => _271.message, 'optionalAccess', _272 => _272.usage])) {
15440
+ const adjustedTokens = finalUsageMetrics.completion_tokens - accumulatedOutputTokens;
15441
+ if (adjustedTokens >= 0) {
15442
+ lastMessage.message.usage.output_tokens = adjustedTokens;
15443
+ }
15444
+ }
15445
+ }
15446
+ const result_metadata = {};
15447
+ if (message.num_turns !== void 0) {
15448
+ result_metadata.num_turns = message.num_turns;
15449
+ }
15450
+ if (message.session_id !== void 0) {
15451
+ result_metadata.session_id = message.session_id;
15452
+ }
15453
+ if (Object.keys(result_metadata).length > 0) {
15454
+ span.log({
15455
+ metadata: result_metadata
15456
+ });
15457
+ }
15458
+ }
15459
+ yield message;
15460
+ }
15461
+ await createLLMSpan();
15462
+ span.log({
15463
+ output: finalResults.length > 0 ? finalResults[finalResults.length - 1] : void 0
15464
+ });
15465
+ } catch (error2) {
15466
+ span.log({
15467
+ error: error2 instanceof Error ? error2.message : String(error2)
15468
+ });
15469
+ throw error2;
15470
+ } finally {
15471
+ span.end();
15472
+ }
15473
+ }();
15474
+ return wrappedGenerator;
15475
+ }
15476
+ });
15477
+ return proxy;
15478
+ }
15479
+ function wrapClaudeAgentTool(toolDef) {
15480
+ const originalHandler = toolDef.handler;
15481
+ const wrappedHandler = (args, extra) => traced(
15482
+ async (span) => {
15483
+ span.log({
15484
+ input: args,
15485
+ metadata: {
15486
+ tool_name: toolDef.name,
15487
+ tool_description: toolDef.description
15488
+ }
15489
+ });
15490
+ const result = await originalHandler(args, extra);
15491
+ span.log({
15492
+ output: result
15493
+ });
15494
+ return result;
15495
+ },
15496
+ {
15497
+ name: `${toolDef.name}`,
15498
+ spanAttributes: {
15499
+ type: "tool" /* TOOL */
15500
+ }
15501
+ }
15502
+ );
15503
+ return {
15504
+ ...toolDef,
15505
+ handler: wrappedHandler
15506
+ };
15507
+ }
15508
+ function _buildLLMInput(prompt, conversationHistory) {
15509
+ const promptMessage = typeof prompt === "string" ? { content: prompt, role: "user" } : void 0;
15510
+ const inputParts = [
15511
+ ...promptMessage ? [promptMessage] : [],
15512
+ ...conversationHistory
15513
+ ];
15514
+ return inputParts.length > 0 ? inputParts : void 0;
15515
+ }
15516
+ function _extractUsageFromMessage(message) {
15517
+ const metrics = {};
15518
+ let usage;
15519
+ if (message.type === "assistant") {
15520
+ usage = _optionalChain([message, 'access', _273 => _273.message, 'optionalAccess', _274 => _274.usage]);
15521
+ } else if (message.type === "result") {
15522
+ usage = message.usage;
15523
+ }
15524
+ if (!usage || typeof usage !== "object") {
15525
+ return metrics;
15526
+ }
15527
+ const inputTokens = getNumberProperty(usage, "input_tokens");
15528
+ if (inputTokens !== void 0) {
15529
+ metrics.prompt_tokens = inputTokens;
15530
+ }
15531
+ const outputTokens = getNumberProperty(usage, "output_tokens");
15532
+ if (outputTokens !== void 0) {
15533
+ metrics.completion_tokens = outputTokens;
15534
+ }
15535
+ const cacheReadTokens = getNumberProperty(usage, "cache_read_input_tokens") || 0;
15536
+ const cacheCreationTokens = getNumberProperty(usage, "cache_creation_input_tokens") || 0;
15537
+ if (cacheReadTokens > 0 || cacheCreationTokens > 0) {
15538
+ const cacheTokens = extractAnthropicCacheTokens(
15539
+ cacheReadTokens,
15540
+ cacheCreationTokens
15541
+ );
15542
+ Object.assign(metrics, cacheTokens);
15543
+ }
15544
+ if (Object.keys(metrics).length > 0) {
15545
+ Object.assign(metrics, finalizeAnthropicTokens(metrics));
15546
+ }
15547
+ return metrics;
15548
+ }
15549
+ async function _createLLMSpanForMessages(messages, prompt, conversationHistory, options, startTime, parentSpan) {
15550
+ if (messages.length === 0) return void 0;
15551
+ const lastMessage = messages[messages.length - 1];
15552
+ if (lastMessage.type !== "assistant" || !_optionalChain([lastMessage, 'access', _275 => _275.message, 'optionalAccess', _276 => _276.usage])) {
15553
+ return void 0;
15554
+ }
15555
+ const model = lastMessage.message.model || options.model;
15556
+ const usage = _extractUsageFromMessage(lastMessage);
15557
+ const input = _buildLLMInput(prompt, conversationHistory);
15558
+ const outputs = messages.map(
15559
+ (m) => _optionalChain([m, 'access', _277 => _277.message, 'optionalAccess', _278 => _278.content]) && _optionalChain([m, 'access', _279 => _279.message, 'optionalAccess', _280 => _280.role]) ? { content: m.message.content, role: m.message.role } : void 0
15560
+ ).filter((c) => c !== void 0);
15561
+ await traced(
15562
+ (llmSpan) => {
15563
+ llmSpan.log({
15564
+ input,
15565
+ output: outputs,
15566
+ metadata: model ? { model } : void 0,
15567
+ metrics: usage
15568
+ });
15569
+ },
15570
+ {
15571
+ name: "anthropic.messages.create",
15572
+ spanAttributes: {
15573
+ type: "llm" /* LLM */
15574
+ },
15575
+ startTime,
15576
+ parent: parentSpan
15577
+ }
15578
+ );
15579
+ return _optionalChain([lastMessage, 'access', _281 => _281.message, 'optionalAccess', _282 => _282.content]) && _optionalChain([lastMessage, 'access', _283 => _283.message, 'optionalAccess', _284 => _284.role]) ? { content: lastMessage.message.content, role: lastMessage.message.role } : void 0;
15580
+ }
15581
+ function wrapClaudeAgentSDK(sdk) {
15582
+ const cache = /* @__PURE__ */ new Map();
15583
+ return new Proxy(sdk, {
15584
+ get(target, prop, receiver) {
15585
+ if (cache.has(prop)) {
15586
+ return cache.get(prop);
15587
+ }
15588
+ const value = Reflect.get(target, prop, receiver);
15589
+ if (prop === "query" && typeof value === "function") {
15590
+ const wrappedQuery = wrapClaudeAgentQuery(
15591
+ value,
15592
+ target
15593
+ );
15594
+ cache.set(prop, wrappedQuery);
15595
+ return wrappedQuery;
15596
+ }
15597
+ if (prop === "tool" && typeof value === "function") {
15598
+ const toolFn = value;
15599
+ const wrappedToolFactory = new Proxy(toolFn, {
15600
+ apply(toolTarget, thisArg, argArray) {
15601
+ const invocationTarget = thisArg === receiver || thisArg === void 0 ? target : thisArg;
15602
+ const toolDef = Reflect.apply(
15603
+ toolTarget,
15604
+ invocationTarget,
15605
+ argArray
15606
+ );
15607
+ if (toolDef && typeof toolDef === "object" && "handler" in toolDef) {
15608
+ return wrapClaudeAgentTool(
15609
+ toolDef
15610
+ );
15611
+ }
15612
+ return toolDef;
15613
+ }
15614
+ });
15615
+ cache.set(prop, wrappedToolFactory);
15616
+ return wrappedToolFactory;
15617
+ }
15618
+ if (typeof value === "function") {
15619
+ const bound = value.bind(target);
15620
+ cache.set(prop, bound);
15621
+ return bound;
15622
+ }
15623
+ return value;
15624
+ }
15625
+ });
15626
+ }
15627
+
14998
15628
  // src/otel.ts
14999
15629
  var otelApi = null;
15000
15630
  var otelSdk = null;
@@ -15158,8 +15788,8 @@ var BraintrustSpanProcessor = class _BraintrustSpanProcessor {
15158
15788
  span.instrumentationScope = span.instrumentationLibrary;
15159
15789
  }
15160
15790
  if (!span.parentSpanContext && span.parentSpanId) {
15161
- const spanContext = _optionalChain([span, 'access', _249 => _249.spanContext, 'optionalCall', _250 => _250()]);
15162
- if (_optionalChain([spanContext, 'optionalAccess', _251 => _251.traceId])) {
15791
+ const spanContext = _optionalChain([span, 'access', _285 => _285.spanContext, 'optionalCall', _286 => _286()]);
15792
+ if (_optionalChain([spanContext, 'optionalAccess', _287 => _287.traceId])) {
15163
15793
  span.parentSpanContext = {
15164
15794
  spanId: span.parentSpanId,
15165
15795
  traceId: spanContext.traceId
@@ -15218,9 +15848,9 @@ var BraintrustExporter = (_class31 = class _BraintrustExporter {
15218
15848
  }
15219
15849
  }
15220
15850
 
15221
- __init80() {this.spans = []}
15222
- __init81() {this.callbacks = []}
15223
- constructor(options = {}) {;_class31.prototype.__init80.call(this);_class31.prototype.__init81.call(this);
15851
+ __init81() {this.spans = []}
15852
+ __init82() {this.callbacks = []}
15853
+ constructor(options = {}) {;_class31.prototype.__init81.call(this);_class31.prototype.__init82.call(this);
15224
15854
  _BraintrustExporter.checkOtelAvailable();
15225
15855
  this.processor = new BraintrustSpanProcessor(options);
15226
15856
  }
@@ -15400,4 +16030,11 @@ var index_default = exports_node_exports;
15400
16030
 
15401
16031
 
15402
16032
 
15403
- exports.AISpanProcessor = AISpanProcessor; exports.Attachment = Attachment; exports.BaseAttachment = BaseAttachment; exports.BaseExperiment = BaseExperiment; exports.BraintrustExporter = BraintrustExporter; exports.BraintrustMiddleware = BraintrustMiddleware; exports.BraintrustSpanProcessor = BraintrustSpanProcessor; exports.BraintrustState = BraintrustState; exports.BraintrustStream = BraintrustStream; exports.CodeFunction = CodeFunction; exports.CodePrompt = CodePrompt; exports.Dataset = Dataset2; exports.ERR_PERMALINK = ERR_PERMALINK; exports.Eval = Eval; exports.EvalResultWithSummary = EvalResultWithSummary; exports.Experiment = Experiment2; exports.ExternalAttachment = ExternalAttachment; exports.FailedHTTPResponse = FailedHTTPResponse; exports.INTERNAL_BTQL_LIMIT = INTERNAL_BTQL_LIMIT; exports.LEGACY_CACHED_HEADER = LEGACY_CACHED_HEADER; exports.LazyValue = LazyValue; exports.Logger = Logger; exports.NOOP_SPAN = NOOP_SPAN; exports.NOOP_SPAN_PERMALINK = NOOP_SPAN_PERMALINK; exports.NoopSpan = NoopSpan; exports.Project = Project2; exports.ProjectNameIdMap = ProjectNameIdMap; exports.Prompt = Prompt2; exports.PromptBuilder = PromptBuilder; exports.ReadonlyAttachment = ReadonlyAttachment; exports.ReadonlyExperiment = ReadonlyExperiment; exports.Reporter = Reporter; exports.ScorerBuilder = ScorerBuilder; exports.SpanImpl = SpanImpl; exports.TestBackgroundLogger = TestBackgroundLogger; exports.ToolBuilder = ToolBuilder; exports.X_CACHED_HEADER = X_CACHED_HEADER; exports._exportsForTestingOnly = _exportsForTestingOnly; exports._internalGetGlobalState = _internalGetGlobalState; exports._internalSetInitialState = _internalSetInitialState; exports.braintrustStreamChunkSchema = braintrustStreamChunkSchema; exports.buildLocalSummary = buildLocalSummary; exports.createFinalValuePassThroughStream = createFinalValuePassThroughStream; exports.currentExperiment = currentExperiment; exports.currentLogger = currentLogger; exports.currentSpan = currentSpan; exports.default = index_default; exports.defaultErrorScoreHandler = defaultErrorScoreHandler; exports.deserializePlainStringAsJSON = deserializePlainStringAsJSON; exports.devNullWritableStream = devNullWritableStream; exports.evaluatorDefinitionSchema = evaluatorDefinitionSchema; exports.evaluatorDefinitionsSchema = evaluatorDefinitionsSchema; exports.flush = flush; exports.getPromptVersions = getPromptVersions; exports.getSpanParentObject = getSpanParentObject; exports.graph = graph_framework_exports; exports.init = init; exports.initDataset = initDataset; exports.initExperiment = initExperiment; exports.initFunction = initFunction; exports.initLogger = initLogger; exports.invoke = invoke; exports.loadPrompt = loadPrompt; exports.log = log; exports.logError = logError; exports.login = login; exports.loginToState = loginToState; exports.newId = newId; exports.parseCachedHeader = parseCachedHeader; exports.permalink = permalink; exports.projects = projects; exports.promptContentsSchema = promptContentsSchema; exports.promptDefinitionSchema = promptDefinitionSchema; exports.promptDefinitionToPromptData = promptDefinitionToPromptData; exports.promptDefinitionWithToolsSchema = promptDefinitionWithToolsSchema; exports.renderMessage = renderMessage; exports.renderPromptParams = renderPromptParams; exports.reportFailures = reportFailures; exports.runEvaluator = runEvaluator; exports.setFetch = setFetch; exports.setMaskingFunction = setMaskingFunction; exports.spanComponentsToObjectId = spanComponentsToObjectId; exports.startSpan = startSpan; exports.summarize = summarize; exports.toolFunctionDefinitionSchema = ToolFunctionDefinition; exports.traceable = traceable; exports.traced = traced; exports.updateSpan = updateSpan; exports.withCurrent = withCurrent; exports.withDataset = withDataset; exports.withExperiment = withExperiment; exports.withLogger = withLogger; exports.withParent = withParent; exports.wrapAISDK = wrapAISDK; exports.wrapAISDKModel = wrapAISDKModel; exports.wrapAnthropic = wrapAnthropic; exports.wrapOpenAI = wrapOpenAI; exports.wrapOpenAIv4 = wrapOpenAIv4; exports.wrapTraced = wrapTraced;
16033
+
16034
+
16035
+
16036
+
16037
+
16038
+
16039
+
16040
+ exports.AISpanProcessor = AISpanProcessor; exports.Attachment = Attachment; exports.BaseAttachment = BaseAttachment; exports.BaseExperiment = BaseExperiment; exports.BraintrustExporter = BraintrustExporter; exports.BraintrustMiddleware = BraintrustMiddleware; exports.BraintrustSpanProcessor = BraintrustSpanProcessor; exports.BraintrustState = BraintrustState; exports.BraintrustStream = BraintrustStream; exports.CodeFunction = CodeFunction; exports.CodePrompt = CodePrompt; exports.Dataset = Dataset2; exports.ERR_PERMALINK = ERR_PERMALINK; exports.Eval = Eval; exports.EvalResultWithSummary = EvalResultWithSummary; exports.Experiment = Experiment2; exports.ExternalAttachment = ExternalAttachment; exports.FailedHTTPResponse = FailedHTTPResponse; exports.IDGenerator = IDGenerator; exports.INTERNAL_BTQL_LIMIT = INTERNAL_BTQL_LIMIT; exports.LEGACY_CACHED_HEADER = LEGACY_CACHED_HEADER; exports.LazyValue = LazyValue; exports.Logger = Logger; exports.NOOP_SPAN = NOOP_SPAN; exports.NOOP_SPAN_PERMALINK = NOOP_SPAN_PERMALINK; exports.NoopSpan = NoopSpan; exports.OTELIDGenerator = OTELIDGenerator; exports.Project = Project2; exports.ProjectNameIdMap = ProjectNameIdMap; exports.Prompt = Prompt2; exports.PromptBuilder = PromptBuilder; exports.ReadonlyAttachment = ReadonlyAttachment; exports.ReadonlyExperiment = ReadonlyExperiment; exports.Reporter = Reporter; exports.ScorerBuilder = ScorerBuilder; exports.SpanImpl = SpanImpl; exports.TestBackgroundLogger = TestBackgroundLogger; exports.ToolBuilder = ToolBuilder; exports.UUIDGenerator = UUIDGenerator; exports.X_CACHED_HEADER = X_CACHED_HEADER; exports._exportsForTestingOnly = _exportsForTestingOnly; exports._internalGetGlobalState = _internalGetGlobalState; exports._internalSetInitialState = _internalSetInitialState; exports.braintrustStreamChunkSchema = braintrustStreamChunkSchema; exports.buildLocalSummary = buildLocalSummary; exports.createFinalValuePassThroughStream = createFinalValuePassThroughStream; exports.currentExperiment = currentExperiment; exports.currentLogger = currentLogger; exports.currentSpan = currentSpan; exports.deepCopyEvent = deepCopyEvent; exports.default = index_default; exports.defaultErrorScoreHandler = defaultErrorScoreHandler; exports.deserializePlainStringAsJSON = deserializePlainStringAsJSON; exports.devNullWritableStream = devNullWritableStream; exports.evaluatorDefinitionSchema = evaluatorDefinitionSchema; exports.evaluatorDefinitionsSchema = evaluatorDefinitionsSchema; exports.flush = flush; exports.getIdGenerator = getIdGenerator; exports.getPromptVersions = getPromptVersions; exports.getSpanParentObject = getSpanParentObject; exports.graph = graph_framework_exports; exports.init = init; exports.initDataset = initDataset; exports.initExperiment = initExperiment; exports.initFunction = initFunction; exports.initLogger = initLogger; exports.invoke = invoke; exports.loadPrompt = loadPrompt; exports.log = log; exports.logError = logError; exports.login = login; exports.loginToState = loginToState; exports.newId = newId; exports.parseCachedHeader = parseCachedHeader; exports.permalink = permalink; exports.projects = projects; exports.promptContentsSchema = promptContentsSchema; exports.promptDefinitionSchema = promptDefinitionSchema; exports.promptDefinitionToPromptData = promptDefinitionToPromptData; exports.promptDefinitionWithToolsSchema = promptDefinitionWithToolsSchema; exports.renderMessage = renderMessage; exports.renderPromptParams = renderPromptParams; exports.reportFailures = reportFailures; exports.runEvaluator = runEvaluator; exports.setFetch = setFetch; exports.setMaskingFunction = setMaskingFunction; exports.spanComponentsToObjectId = spanComponentsToObjectId; exports.startSpan = startSpan; exports.summarize = summarize; exports.toolFunctionDefinitionSchema = ToolFunctionDefinition; exports.traceable = traceable; exports.traced = traced; exports.updateSpan = updateSpan; exports.withCurrent = withCurrent; exports.withDataset = withDataset; exports.withExperiment = withExperiment; exports.withLogger = withLogger; exports.withParent = withParent; exports.wrapAISDK = wrapAISDK; exports.wrapAISDKModel = wrapAISDKModel; exports.wrapAnthropic = wrapAnthropic; exports.wrapClaudeAgentSDK = wrapClaudeAgentSDK; exports.wrapMastraAgent = wrapMastraAgent; exports.wrapOpenAI = wrapOpenAI; exports.wrapOpenAIv4 = wrapOpenAIv4; exports.wrapTraced = wrapTraced;