braintrust 3.12.0 → 3.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dev/dist/index.d.mts +31 -14
  2. package/dev/dist/index.d.ts +31 -14
  3. package/dev/dist/index.js +919 -485
  4. package/dev/dist/index.mjs +480 -46
  5. package/dist/apply-auto-instrumentation.js +204 -174
  6. package/dist/apply-auto-instrumentation.mjs +35 -5
  7. package/dist/auto-instrumentations/bundler/esbuild.cjs +226 -1
  8. package/dist/auto-instrumentations/bundler/esbuild.mjs +3 -2
  9. package/dist/auto-instrumentations/bundler/next.cjs +226 -1
  10. package/dist/auto-instrumentations/bundler/next.mjs +4 -3
  11. package/dist/auto-instrumentations/bundler/rollup.cjs +226 -1
  12. package/dist/auto-instrumentations/bundler/rollup.mjs +3 -2
  13. package/dist/auto-instrumentations/bundler/vite.cjs +226 -1
  14. package/dist/auto-instrumentations/bundler/vite.mjs +3 -2
  15. package/dist/auto-instrumentations/bundler/webpack-loader.cjs +9 -0
  16. package/dist/auto-instrumentations/bundler/webpack.cjs +226 -1
  17. package/dist/auto-instrumentations/bundler/webpack.mjs +4 -3
  18. package/dist/auto-instrumentations/{chunk-2DPA74KK.mjs → chunk-E5DUYJWK.mjs} +1 -0
  19. package/dist/auto-instrumentations/chunk-J57YF7WS.mjs +208 -0
  20. package/dist/auto-instrumentations/{chunk-AFXRW7I7.mjs → chunk-OTUQ7KH5.mjs} +1 -1
  21. package/dist/auto-instrumentations/chunk-QFMACSOL.mjs +280 -0
  22. package/dist/auto-instrumentations/{chunk-73BZUKVI.mjs → chunk-XKAAVWT6.mjs} +24 -2
  23. package/dist/auto-instrumentations/hook.mjs +7981 -7
  24. package/dist/auto-instrumentations/index.cjs +1 -0
  25. package/dist/auto-instrumentations/index.mjs +1 -1
  26. package/dist/auto-instrumentations/loader/cjs-patch.cjs +194 -4
  27. package/dist/auto-instrumentations/loader/cjs-patch.mjs +13 -27
  28. package/dist/auto-instrumentations/loader/esm-hook.mjs +24 -10
  29. package/dist/browser.d.mts +274 -30
  30. package/dist/browser.d.ts +274 -30
  31. package/dist/browser.js +407 -48
  32. package/dist/browser.mjs +407 -48
  33. package/dist/{chunk-BW4DF4CY.js → chunk-NKD77KGB.js} +180 -1
  34. package/dist/{chunk-MSLBGITU.mjs → chunk-NU2GSPHX.mjs} +180 -1
  35. package/dist/cli.js +494 -94
  36. package/dist/edge-light.d.mts +1 -1
  37. package/dist/edge-light.d.ts +1 -1
  38. package/dist/edge-light.js +407 -48
  39. package/dist/edge-light.mjs +407 -48
  40. package/dist/index.d.mts +274 -30
  41. package/dist/index.d.ts +274 -30
  42. package/dist/index.js +1267 -857
  43. package/dist/index.mjs +465 -55
  44. package/dist/instrumentation/index.d.mts +47 -11
  45. package/dist/instrumentation/index.d.ts +47 -11
  46. package/dist/instrumentation/index.js +116 -26
  47. package/dist/instrumentation/index.mjs +116 -26
  48. package/dist/workerd.d.mts +1 -1
  49. package/dist/workerd.d.ts +1 -1
  50. package/dist/workerd.js +407 -48
  51. package/dist/workerd.mjs +407 -48
  52. package/package.json +3 -23
  53. package/util/dist/index.d.mts +3 -1
  54. package/util/dist/index.d.ts +3 -1
  55. package/dist/auto-instrumentations/chunk-MWZXZQUO.mjs +0 -81
package/dev/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } async function _asyncOptionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = await fn(value); } else if (op === 'call' || op === 'optionalCall') { value = await fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3; var _class4; var _class5; var _class6; var _class7; var _class8; var _class9; var _class10; var _class11; var _class12; var _class13; var _class14; var _class15; var _class16; var _class17; var _class18; var _class19; var _class20; var _class21; var _class22; var _class23; var _class24; var _class25; var _class26; var _class27; var _class28; var _class29; var _class30; var _class31; var _class32;// src/node/config.ts
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } async function _asyncOptionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = await fn(value); } else if (op === 'call' || op === 'optionalCall') { value = await fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3; var _class4; var _class5; var _class6; var _class7; var _class8; var _class9; var _class10; var _class11; var _class12; var _class13; var _class14; var _class15; var _class16; var _class17; var _class18; var _class19; var _class20; var _class21; var _class22; var _class23; var _class24; var _class25; var _class26; var _class27; var _class28; var _class29; var _class30; var _class31; var _class32; var _class33;// src/node/config.ts
2
2
  var _nodeasync_hooks = require('node:async_hooks');
3
3
  var _nodediagnostics_channel = require('node:diagnostics_channel'); var diagnostics_channel = _interopRequireWildcard(_nodediagnostics_channel);
4
4
  var _nodepath = require('node:path'); var path = _interopRequireWildcard(_nodepath);
@@ -96,6 +96,7 @@ var _nodefs = require('node:fs'); var fsSync = _interopRequireWildcard(_nodefs);
96
96
  var _nodecrypto = require('node:crypto'); var crypto = _interopRequireWildcard(_nodecrypto);
97
97
  var _nodeutil = require('node:util');
98
98
  var _nodezlib = require('node:zlib'); var zlib = _interopRequireWildcard(_nodezlib);
99
+ var _dotenv = require('dotenv'); var dotenv = _interopRequireWildcard(_dotenv);
99
100
 
100
101
  // src/isomorph.ts
101
102
  var DefaultAsyncLocalStorage = class {
@@ -182,6 +183,7 @@ var iso = {
182
183
  getRepoInfo: async (_settings) => void 0,
183
184
  getPastNAncestors: async () => [],
184
185
  getEnv: (_name) => void 0,
186
+ getBraintrustApiKey: async () => void 0,
185
187
  getCallerLocation: () => void 0,
186
188
  newAsyncLocalStorage: () => new DefaultAsyncLocalStorage(),
187
189
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -4252,6 +4254,76 @@ var LRUCache = class {
4252
4254
  }
4253
4255
  };
4254
4256
 
4257
+ // src/prompt-cache/cache-config.ts
4258
+ var CACHE_LOCATION_ENV_VAR = "BRAINTRUST_CACHE_LOCATION";
4259
+ var DEFAULT_CACHE_MEMORY_MAX = 1 << 10;
4260
+ var DEFAULT_CACHE_DISK_MAX = 1 << 20;
4261
+ var warnedInvalidCacheModeEnvValue = false;
4262
+ var warnedUnavailableDiskCacheMode = false;
4263
+ function warnInvalidCacheMode(value) {
4264
+ if (warnedInvalidCacheModeEnvValue) {
4265
+ return;
4266
+ }
4267
+ warnedInvalidCacheModeEnvValue = true;
4268
+ debugLogger.warn(
4269
+ `Invalid ${CACHE_LOCATION_ENV_VAR} value "${value}". Expected "mixed", "memory", "disk", or "none". Falling back to "mixed".`
4270
+ );
4271
+ }
4272
+ function warnUnavailableDiskCache() {
4273
+ if (warnedUnavailableDiskCacheMode) {
4274
+ return;
4275
+ }
4276
+ warnedUnavailableDiskCacheMode = true;
4277
+ debugLogger.warn(
4278
+ `Disk cache is not supported on this platform, so ${CACHE_LOCATION_ENV_VAR}="disk" disables prompt and parameters caching.`
4279
+ );
4280
+ }
4281
+ function parseCacheMode() {
4282
+ const value = isomorph_default.getEnv(CACHE_LOCATION_ENV_VAR);
4283
+ const normalized = _optionalChain([value, 'optionalAccess', _63 => _63.trim, 'call', _64 => _64(), 'access', _65 => _65.toLowerCase, 'call', _66 => _66()]);
4284
+ if (!normalized) {
4285
+ return "mixed";
4286
+ }
4287
+ if (normalized === "mixed" || normalized === "memory" || normalized === "disk" || normalized === "none") {
4288
+ return normalized;
4289
+ }
4290
+ warnInvalidCacheMode(_nullishCoalesce(value, () => ( "")));
4291
+ return "mixed";
4292
+ }
4293
+ function parsePositiveIntegerEnv(envVar, defaultValue) {
4294
+ const value = Number(isomorph_default.getEnv(envVar));
4295
+ return Number.isInteger(value) && value > 0 ? value : defaultValue;
4296
+ }
4297
+ function createCacheLayers({
4298
+ memoryMaxEnvVar,
4299
+ diskCacheDirEnvVar,
4300
+ diskMaxEnvVar,
4301
+ getDefaultDiskCacheDir
4302
+ }) {
4303
+ const mode = parseCacheMode();
4304
+ const memoryCache = mode === "mixed" || mode === "memory" ? new LRUCache({
4305
+ max: parsePositiveIntegerEnv(
4306
+ memoryMaxEnvVar,
4307
+ DEFAULT_CACHE_MEMORY_MAX
4308
+ )
4309
+ }) : void 0;
4310
+ let diskCache;
4311
+ if (mode === "mixed" || mode === "disk") {
4312
+ if (canUseDiskCache()) {
4313
+ diskCache = new DiskCache({
4314
+ cacheDir: _nullishCoalesce(isomorph_default.getEnv(diskCacheDirEnvVar), () => ( getDefaultDiskCacheDir())),
4315
+ max: parsePositiveIntegerEnv(diskMaxEnvVar, DEFAULT_CACHE_DISK_MAX)
4316
+ });
4317
+ } else if (mode === "disk") {
4318
+ warnUnavailableDiskCache();
4319
+ }
4320
+ }
4321
+ if (diskCache) {
4322
+ return { memoryCache, diskCache };
4323
+ }
4324
+ return { memoryCache };
4325
+ }
4326
+
4255
4327
  // src/prompt-cache/prompt-cache.ts
4256
4328
  function createCacheKey(key) {
4257
4329
  if (key.id) {
@@ -4279,16 +4351,18 @@ var PromptCache = class {
4279
4351
  */
4280
4352
  async get(key) {
4281
4353
  const cacheKey = createCacheKey(key);
4282
- const memoryPrompt = this.memoryCache.get(cacheKey);
4283
- if (memoryPrompt !== void 0) {
4284
- return memoryPrompt;
4354
+ if (this.memoryCache) {
4355
+ const memoryPrompt = this.memoryCache.get(cacheKey);
4356
+ if (memoryPrompt !== void 0) {
4357
+ return memoryPrompt;
4358
+ }
4285
4359
  }
4286
4360
  if (this.diskCache) {
4287
4361
  const diskPrompt = await this.diskCache.get(cacheKey);
4288
4362
  if (!diskPrompt) {
4289
4363
  return void 0;
4290
4364
  }
4291
- this.memoryCache.set(cacheKey, diskPrompt);
4365
+ _optionalChain([this, 'access', _67 => _67.memoryCache, 'optionalAccess', _68 => _68.set, 'call', _69 => _69(cacheKey, diskPrompt)]);
4292
4366
  return diskPrompt;
4293
4367
  }
4294
4368
  return void 0;
@@ -4303,7 +4377,7 @@ var PromptCache = class {
4303
4377
  */
4304
4378
  async set(key, value) {
4305
4379
  const cacheKey = createCacheKey(key);
4306
- this.memoryCache.set(cacheKey, value);
4380
+ _optionalChain([this, 'access', _70 => _70.memoryCache, 'optionalAccess', _71 => _71.set, 'call', _72 => _72(cacheKey, value)]);
4307
4381
  if (this.diskCache) {
4308
4382
  await this.diskCache.set(cacheKey, value);
4309
4383
  }
@@ -4333,23 +4407,25 @@ var ParametersCache = class {
4333
4407
  }
4334
4408
  async get(key) {
4335
4409
  const cacheKey = createCacheKey2(key);
4336
- const memoryParams = this.memoryCache.get(cacheKey);
4337
- if (memoryParams !== void 0) {
4338
- return memoryParams;
4410
+ if (this.memoryCache) {
4411
+ const memoryParams = this.memoryCache.get(cacheKey);
4412
+ if (memoryParams !== void 0) {
4413
+ return memoryParams;
4414
+ }
4339
4415
  }
4340
4416
  if (this.diskCache) {
4341
4417
  const diskParams = await this.diskCache.get(cacheKey);
4342
4418
  if (!diskParams) {
4343
4419
  return void 0;
4344
4420
  }
4345
- this.memoryCache.set(cacheKey, diskParams);
4421
+ _optionalChain([this, 'access', _73 => _73.memoryCache, 'optionalAccess', _74 => _74.set, 'call', _75 => _75(cacheKey, diskParams)]);
4346
4422
  return diskParams;
4347
4423
  }
4348
4424
  return void 0;
4349
4425
  }
4350
4426
  async set(key, value) {
4351
4427
  const cacheKey = createCacheKey2(key);
4352
- this.memoryCache.set(cacheKey, value);
4428
+ _optionalChain([this, 'access', _76 => _76.memoryCache, 'optionalAccess', _77 => _77.set, 'call', _78 => _78(cacheKey, value)]);
4353
4429
  if (this.diskCache) {
4354
4430
  await this.diskCache.set(cacheKey, value);
4355
4431
  }
@@ -4377,7 +4453,7 @@ var SpanCache = (_class6 = class {
4377
4453
  // Small in-memory index tracking which rootSpanIds have data
4378
4454
  __init14() {this.rootSpanIndex = /* @__PURE__ */ new Set()}
4379
4455
  constructor(options) {;_class6.prototype.__init8.call(this);_class6.prototype.__init9.call(this);_class6.prototype.__init10.call(this);_class6.prototype.__init11.call(this);_class6.prototype.__init12.call(this);_class6.prototype.__init13.call(this);_class6.prototype.__init14.call(this);_class6.prototype.__init15.call(this);_class6.prototype.__init16.call(this);_class6.prototype.__init17.call(this);
4380
- this._explicitlyDisabled = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _63 => _63.disabled]), () => ( false));
4456
+ this._explicitlyDisabled = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _79 => _79.disabled]), () => ( false));
4381
4457
  }
4382
4458
  /**
4383
4459
  * Disable the cache at runtime. This is called automatically when
@@ -4797,7 +4873,7 @@ var NoopSpan = (_class7 = class {
4797
4873
  return this;
4798
4874
  }
4799
4875
  end(args) {
4800
- return _nullishCoalesce(_optionalChain([args, 'optionalAccess', _64 => _64.endTime]), () => ( getCurrentUnixTimestamp()));
4876
+ return _nullishCoalesce(_optionalChain([args, 'optionalAccess', _80 => _80.endTime]), () => ( getCurrentUnixTimestamp()));
4801
4877
  }
4802
4878
  async export() {
4803
4879
  return "";
@@ -4881,21 +4957,22 @@ var BraintrustState = (_class8 = class _BraintrustState {
4881
4957
  setGlobalDebugLogLevel(void 0);
4882
4958
  }
4883
4959
  this.resetLoginInfo();
4884
- const memoryCache = new LRUCache({
4885
- max: _nullishCoalesce(Number(isomorph_default.getEnv("BRAINTRUST_PROMPT_CACHE_MEMORY_MAX")), () => ( 1 << 10))
4960
+ const { memoryCache, diskCache } = createCacheLayers({
4961
+ memoryMaxEnvVar: "BRAINTRUST_PROMPT_CACHE_MEMORY_MAX",
4962
+ diskCacheDirEnvVar: "BRAINTRUST_PROMPT_CACHE_DIR",
4963
+ diskMaxEnvVar: "BRAINTRUST_PROMPT_CACHE_DISK_MAX",
4964
+ getDefaultDiskCacheDir: () => `${_nullishCoalesce(isomorph_default.getEnv("HOME"), () => ( isomorph_default.homedir()))}/.braintrust/prompt_cache`
4886
4965
  });
4887
- const diskCache = canUseDiskCache() ? new DiskCache({
4888
- cacheDir: _nullishCoalesce(isomorph_default.getEnv("BRAINTRUST_PROMPT_CACHE_DIR"), () => ( `${_nullishCoalesce(isomorph_default.getEnv("HOME"), () => ( isomorph_default.homedir()))}/.braintrust/prompt_cache`)),
4889
- max: _nullishCoalesce(Number(isomorph_default.getEnv("BRAINTRUST_PROMPT_CACHE_DISK_MAX")), () => ( 1 << 20))
4890
- }) : void 0;
4891
4966
  this.promptCache = new PromptCache({ memoryCache, diskCache });
4892
- const parametersMemoryCache = new LRUCache({
4893
- max: _nullishCoalesce(Number(isomorph_default.getEnv("BRAINTRUST_PARAMETERS_CACHE_MEMORY_MAX")), () => ( 1 << 10))
4967
+ const {
4968
+ memoryCache: parametersMemoryCache,
4969
+ diskCache: parametersDiskCache
4970
+ } = createCacheLayers({
4971
+ memoryMaxEnvVar: "BRAINTRUST_PARAMETERS_CACHE_MEMORY_MAX",
4972
+ diskCacheDirEnvVar: "BRAINTRUST_PARAMETERS_CACHE_DIR",
4973
+ diskMaxEnvVar: "BRAINTRUST_PARAMETERS_CACHE_DISK_MAX",
4974
+ getDefaultDiskCacheDir: () => `${_nullishCoalesce(isomorph_default.getEnv("HOME"), () => ( isomorph_default.homedir()))}/.braintrust/parameters_cache`
4894
4975
  });
4895
- const parametersDiskCache = canUseDiskCache() ? new DiskCache({
4896
- cacheDir: _nullishCoalesce(isomorph_default.getEnv("BRAINTRUST_PARAMETERS_CACHE_DIR"), () => ( `${_nullishCoalesce(isomorph_default.getEnv("HOME"), () => ( isomorph_default.homedir()))}/.braintrust/parameters_cache`)),
4897
- max: _nullishCoalesce(Number(isomorph_default.getEnv("BRAINTRUST_PARAMETERS_CACHE_DISK_MAX")), () => ( 1 << 20))
4898
- }) : void 0;
4899
4976
  this.parametersCache = new ParametersCache({
4900
4977
  memoryCache: parametersMemoryCache,
4901
4978
  diskCache: parametersDiskCache
@@ -5062,8 +5139,8 @@ var BraintrustState = (_class8 = class _BraintrustState {
5062
5139
  setFetch(fetch2) {
5063
5140
  this.loginParams.fetch = fetch2;
5064
5141
  this.fetch = fetch2;
5065
- _optionalChain([this, 'access', _65 => _65._apiConn, 'optionalAccess', _66 => _66.setFetch, 'call', _67 => _67(fetch2)]);
5066
- _optionalChain([this, 'access', _68 => _68._appConn, 'optionalAccess', _69 => _69.setFetch, 'call', _70 => _70(fetch2)]);
5142
+ _optionalChain([this, 'access', _81 => _81._apiConn, 'optionalAccess', _82 => _82.setFetch, 'call', _83 => _83(fetch2)]);
5143
+ _optionalChain([this, 'access', _84 => _84._appConn, 'optionalAccess', _85 => _85.setFetch, 'call', _86 => _86(fetch2)]);
5067
5144
  }
5068
5145
  setMaskingFunction(maskingFunction) {
5069
5146
  this.bgLogger().setMaskingFunction(maskingFunction);
@@ -5463,7 +5540,7 @@ var Attachment = class extends BaseAttachment {
5463
5540
  body: data
5464
5541
  })
5465
5542
  );
5466
- await _optionalChain([objectStoreResponse, 'access', _71 => _71.body, 'optionalAccess', _72 => _72.cancel, 'call', _73 => _73()]);
5543
+ await _optionalChain([objectStoreResponse, 'access', _87 => _87.body, 'optionalAccess', _88 => _88.cancel, 'call', _89 => _89()]);
5467
5544
  } catch (error) {
5468
5545
  if (error instanceof FailedHTTPResponse) {
5469
5546
  throw new Error(
@@ -5495,7 +5572,7 @@ var Attachment = class extends BaseAttachment {
5495
5572
  "/attachment/status",
5496
5573
  requestParams
5497
5574
  );
5498
- await _optionalChain([statusResponse, 'access', _74 => _74.body, 'optionalAccess', _75 => _75.cancel, 'call', _76 => _76()]);
5575
+ await _optionalChain([statusResponse, 'access', _90 => _90.body, 'optionalAccess', _91 => _91.cancel, 'call', _92 => _92()]);
5499
5576
  if (!statusResponse.ok) {
5500
5577
  const errorStr = JSON.stringify(statusResponse);
5501
5578
  throw new Error(`Couldn't log attachment status: ${errorStr}`);
@@ -5774,8 +5851,8 @@ function _getOrgName(orgName) {
5774
5851
  return orgName || isomorph_default.getEnv("BRAINTRUST_ORG_NAME") || void 0;
5775
5852
  }
5776
5853
  function _getLinkBaseUrl(state, linkArgs) {
5777
- const appUrl = _getAppUrl(state.appUrl || _optionalChain([linkArgs, 'optionalAccess', _77 => _77.app_url]));
5778
- const orgName = _getOrgName(state.orgName || _optionalChain([linkArgs, 'optionalAccess', _78 => _78.org_name]));
5854
+ const appUrl = _getAppUrl(state.appUrl || _optionalChain([linkArgs, 'optionalAccess', _93 => _93.app_url]));
5855
+ const orgName = _getOrgName(state.orgName || _optionalChain([linkArgs, 'optionalAccess', _94 => _94.org_name]));
5779
5856
  if (!orgName) {
5780
5857
  return null;
5781
5858
  }
@@ -5785,9 +5862,9 @@ async function permalink(slug, opts) {
5785
5862
  if (slug === "") {
5786
5863
  return NOOP_SPAN_PERMALINK;
5787
5864
  }
5788
- const state = _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _79 => _79.state]), () => ( _globalState));
5865
+ const state = _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _95 => _95.state]), () => ( _globalState));
5789
5866
  const getOrgName = async () => {
5790
- if (_optionalChain([opts, 'optionalAccess', _80 => _80.orgName])) {
5867
+ if (_optionalChain([opts, 'optionalAccess', _96 => _96.orgName])) {
5791
5868
  return opts.orgName;
5792
5869
  }
5793
5870
  await state.login({});
@@ -5797,7 +5874,7 @@ async function permalink(slug, opts) {
5797
5874
  return state.orgName;
5798
5875
  };
5799
5876
  const getAppUrl = async () => {
5800
- if (_optionalChain([opts, 'optionalAccess', _81 => _81.appUrl])) {
5877
+ if (_optionalChain([opts, 'optionalAccess', _97 => _97.appUrl])) {
5801
5878
  return opts.appUrl;
5802
5879
  }
5803
5880
  await state.login({});
@@ -5919,7 +5996,7 @@ var Logger = (_class9 = class {
5919
5996
  * @returns The `id` of the logged event.
5920
5997
  */
5921
5998
  log(event, options) {
5922
- if (this.calledStartSpan && !_optionalChain([options, 'optionalAccess', _82 => _82.allowConcurrentWithSpans])) {
5999
+ if (this.calledStartSpan && !_optionalChain([options, 'optionalAccess', _98 => _98.allowConcurrentWithSpans])) {
5923
6000
  throw new Error(
5924
6001
  "Cannot run toplevel `log` method while using spans. To log to the span, call `logger.traced` and then log with `span.log`"
5925
6002
  );
@@ -5987,12 +6064,12 @@ var Logger = (_class9 = class {
5987
6064
  state: this.state,
5988
6065
  ...startSpanParentArgs({
5989
6066
  state: this.state,
5990
- parent: _optionalChain([args, 'optionalAccess', _83 => _83.parent]),
6067
+ parent: _optionalChain([args, 'optionalAccess', _99 => _99.parent]),
5991
6068
  parentObjectType: this.parentObjectType(),
5992
6069
  parentObjectId: this.lazyId,
5993
6070
  parentComputeObjectMetadataArgs: this.computeMetadataArgs,
5994
- parentSpanIds: _optionalChain([args, 'optionalAccess', _84 => _84.parentSpanIds]),
5995
- propagatedEvent: _optionalChain([args, 'optionalAccess', _85 => _85.propagatedEvent])
6071
+ parentSpanIds: _optionalChain([args, 'optionalAccess', _100 => _100.parentSpanIds]),
6072
+ propagatedEvent: _optionalChain([args, 'optionalAccess', _101 => _101.propagatedEvent])
5996
6073
  }),
5997
6074
  defaultRootType: "task" /* TASK */
5998
6075
  });
@@ -6328,7 +6405,7 @@ var HTTPBackgroundLogger = (_class10 = class _HTTPBackgroundLogger {
6328
6405
  this.queue.clear();
6329
6406
  return;
6330
6407
  }
6331
- const batchSize = _nullishCoalesce(_optionalChain([args, 'optionalAccess', _86 => _86.batchSize]), () => ( this.defaultBatchSize));
6408
+ const batchSize = _nullishCoalesce(_optionalChain([args, 'optionalAccess', _102 => _102.batchSize]), () => ( this.defaultBatchSize));
6332
6409
  const wrappedItems = this.queue.drain();
6333
6410
  if (wrappedItems.length === 0) {
6334
6411
  return;
@@ -6642,10 +6719,10 @@ Error: ${errorText}`;
6642
6719
  } catch (err) {
6643
6720
  if (err instanceof AggregateError) {
6644
6721
  for (const e of err.errors) {
6645
- _optionalChain([this, 'access', _87 => _87.onFlushError, 'optionalCall', _88 => _88(e)]);
6722
+ _optionalChain([this, 'access', _103 => _103.onFlushError, 'optionalCall', _104 => _104(e)]);
6646
6723
  }
6647
6724
  } else {
6648
- _optionalChain([this, 'access', _89 => _89.onFlushError, 'optionalCall', _90 => _90(err)]);
6725
+ _optionalChain([this, 'access', _105 => _105.onFlushError, 'optionalCall', _106 => _106(err)]);
6649
6726
  }
6650
6727
  this.activeFlushError = err;
6651
6728
  } finally {
@@ -6695,7 +6772,7 @@ function getExperimentDatasetFilter({
6695
6772
  return isObject(datasetFilter) ? datasetFilter : void 0;
6696
6773
  }
6697
6774
  function getInternalBtqlLimit(internalBtql) {
6698
- const limit = _optionalChain([internalBtql, 'optionalAccess', _91 => _91["limit"]]);
6775
+ const limit = _optionalChain([internalBtql, 'optionalAccess', _107 => _107["limit"]]);
6699
6776
  return typeof limit === "number" ? limit : void 0;
6700
6777
  }
6701
6778
  function init(projectOrOptions, optionalOptions) {
@@ -7266,10 +7343,11 @@ async function login(options = {}) {
7266
7343
  async function loginToState(options = {}) {
7267
7344
  const {
7268
7345
  appUrl = isomorph_default.getEnv("BRAINTRUST_APP_URL") || "https://www.braintrust.dev",
7269
- apiKey = isomorph_default.getEnv("BRAINTRUST_API_KEY"),
7346
+ apiKey: apiKeyArg,
7270
7347
  orgName = isomorph_default.getEnv("BRAINTRUST_ORG_NAME"),
7271
7348
  fetch: fetch2 = globalThis.fetch
7272
7349
  } = options || {};
7350
+ const apiKey = apiKeyArg !== void 0 ? apiKeyArg : await isomorph_default.getBraintrustApiKey();
7273
7351
  const appPublicUrl = isomorph_default.getEnv("BRAINTRUST_APP_PUBLIC_URL") || appUrl;
7274
7352
  const state = new BraintrustState(options);
7275
7353
  state.resetLoginInfo();
@@ -7332,24 +7410,24 @@ async function loginToState(options = {}) {
7332
7410
  return state;
7333
7411
  }
7334
7412
  function currentExperiment(options) {
7335
- const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _92 => _92.state]), () => ( _globalState));
7413
+ const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _108 => _108.state]), () => ( _globalState));
7336
7414
  return state.currentExperiment;
7337
7415
  }
7338
7416
  function currentLogger(options) {
7339
- const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _93 => _93.state]), () => ( _globalState));
7340
- return castLogger(state.currentLogger, _optionalChain([options, 'optionalAccess', _94 => _94.asyncFlush]));
7417
+ const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _109 => _109.state]), () => ( _globalState));
7418
+ return castLogger(state.currentLogger, _optionalChain([options, 'optionalAccess', _110 => _110.asyncFlush]));
7341
7419
  }
7342
7420
  function currentSpan(options) {
7343
- const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _95 => _95.state]), () => ( _globalState));
7421
+ const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _111 => _111.state]), () => ( _globalState));
7344
7422
  return _nullishCoalesce(state.contextManager.getCurrentSpan(), () => ( NOOP_SPAN));
7345
7423
  }
7346
7424
  function getSpanParentObject(options) {
7347
- const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _96 => _96.state]), () => ( _globalState));
7425
+ const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _112 => _112.state]), () => ( _globalState));
7348
7426
  const parentSpan = currentSpan({ state });
7349
7427
  if (!Object.is(parentSpan, NOOP_SPAN)) {
7350
7428
  return parentSpan;
7351
7429
  }
7352
- const parentStr = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _97 => _97.parent]), () => ( state.currentParent.getStore()));
7430
+ const parentStr = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _113 => _113.parent]), () => ( state.currentParent.getStore()));
7353
7431
  if (parentStr) return getSpanComponentsClass().fromStr(parentStr);
7354
7432
  const experiment = currentExperiment();
7355
7433
  if (experiment) {
@@ -7378,7 +7456,7 @@ function traced(callback, args) {
7378
7456
  const { span, isSyncFlushLogger } = startSpanAndIsLogger(args);
7379
7457
  const ret = runCatchFinally(
7380
7458
  () => {
7381
- if (_nullishCoalesce(_optionalChain([args, 'optionalAccess', _98 => _98.setCurrent]), () => ( true))) {
7459
+ if (_nullishCoalesce(_optionalChain([args, 'optionalAccess', _114 => _114.setCurrent]), () => ( true))) {
7382
7460
  return withCurrent(span, callback);
7383
7461
  } else {
7384
7462
  return callback(span);
@@ -7390,7 +7468,7 @@ function traced(callback, args) {
7390
7468
  },
7391
7469
  () => span.end()
7392
7470
  );
7393
- if (_optionalChain([args, 'optionalAccess', _99 => _99.asyncFlush]) === void 0 || _optionalChain([args, 'optionalAccess', _100 => _100.asyncFlush])) {
7471
+ if (_optionalChain([args, 'optionalAccess', _115 => _115.asyncFlush]) === void 0 || _optionalChain([args, 'optionalAccess', _116 => _116.asyncFlush])) {
7394
7472
  return ret;
7395
7473
  } else {
7396
7474
  return (async () => {
@@ -7406,14 +7484,14 @@ function startSpan(args) {
7406
7484
  return startSpanAndIsLogger(args).span;
7407
7485
  }
7408
7486
  async function flush(options) {
7409
- const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _101 => _101.state]), () => ( _globalState));
7487
+ const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _117 => _117.state]), () => ( _globalState));
7410
7488
  return await state.bgLogger().flush();
7411
7489
  }
7412
7490
  function startSpanAndIsLogger(args) {
7413
- const state = _nullishCoalesce(_optionalChain([args, 'optionalAccess', _102 => _102.state]), () => ( _globalState));
7491
+ const state = _nullishCoalesce(_optionalChain([args, 'optionalAccess', _118 => _118.state]), () => ( _globalState));
7414
7492
  const parentObject = getSpanParentObject({
7415
- asyncFlush: _optionalChain([args, 'optionalAccess', _103 => _103.asyncFlush]),
7416
- parent: _optionalChain([args, 'optionalAccess', _104 => _104.parent]),
7493
+ asyncFlush: _optionalChain([args, 'optionalAccess', _119 => _119.asyncFlush]),
7494
+ parent: _optionalChain([args, 'optionalAccess', _120 => _120.parent]),
7417
7495
  state
7418
7496
  });
7419
7497
  if (parentObject instanceof SpanComponentsV3 || parentObject instanceof SpanComponentsV4) {
@@ -7430,14 +7508,14 @@ function startSpanAndIsLogger(args) {
7430
7508
  ),
7431
7509
  parentComputeObjectMetadataArgs: _nullishCoalesce(parentObject.data.compute_object_metadata_args, () => ( void 0)),
7432
7510
  parentSpanIds,
7433
- propagatedEvent: _nullishCoalesce(_optionalChain([args, 'optionalAccess', _105 => _105.propagatedEvent]), () => ( // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
7511
+ propagatedEvent: _nullishCoalesce(_optionalChain([args, 'optionalAccess', _121 => _121.propagatedEvent]), () => ( // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
7434
7512
  (_nullishCoalesce(parentObject.data.propagated_event, () => ( void 0)))))
7435
7513
  });
7436
7514
  return {
7437
7515
  span,
7438
7516
  isSyncFlushLogger: parentObject.data.object_type === 2 /* PROJECT_LOGS */ && // Since there's no parent logger here, we're free to choose the async flush
7439
7517
  // behavior, and therefore propagate along whatever we get from the arguments
7440
- _optionalChain([args, 'optionalAccess', _106 => _106.asyncFlush]) === false
7518
+ _optionalChain([args, 'optionalAccess', _122 => _122.asyncFlush]) === false
7441
7519
  };
7442
7520
  } else {
7443
7521
  const span = parentObject.startSpan(args);
@@ -7604,10 +7682,10 @@ function extractAttachments(event, attachments) {
7604
7682
  event[key] = value.reference;
7605
7683
  continue;
7606
7684
  }
7607
- if (_optionalChain([value, 'optionalAccess', _107 => _107.type]) === BRAINTRUST_ATTACHMENT && value.key && !value.uploader) {
7685
+ if (_optionalChain([value, 'optionalAccess', _123 => _123.type]) === BRAINTRUST_ATTACHMENT && value.key && !value.uploader) {
7608
7686
  continue;
7609
7687
  }
7610
- if (_optionalChain([value, 'optionalAccess', _108 => _108.reference, 'optionalAccess', _109 => _109.type]) === BRAINTRUST_ATTACHMENT && _optionalChain([value, 'optionalAccess', _110 => _110.uploader])) {
7688
+ if (_optionalChain([value, 'optionalAccess', _124 => _124.reference, 'optionalAccess', _125 => _125.type]) === BRAINTRUST_ATTACHMENT && _optionalChain([value, 'optionalAccess', _126 => _126.uploader])) {
7611
7689
  const attachment = new Attachment({
7612
7690
  data: value.dataDebugString,
7613
7691
  filename: value.reference.filename,
@@ -7774,7 +7852,7 @@ var ObjectFetcher = (_class11 = class {
7774
7852
  }
7775
7853
  return;
7776
7854
  }
7777
- for await (const record of this.fetchRecordsFromApi(_optionalChain([options, 'optionalAccess', _111 => _111.batchSize]))) {
7855
+ for await (const record of this.fetchRecordsFromApi(_optionalChain([options, 'optionalAccess', _127 => _127.batchSize]))) {
7778
7856
  yield record;
7779
7857
  }
7780
7858
  }
@@ -7784,7 +7862,7 @@ var ObjectFetcher = (_class11 = class {
7784
7862
  async fetchedData(options) {
7785
7863
  if (this._fetchedData === void 0) {
7786
7864
  const data = [];
7787
- for await (const record of this.fetchRecordsFromApi(_optionalChain([options, 'optionalAccess', _112 => _112.batchSize]))) {
7865
+ for await (const record of this.fetchRecordsFromApi(_optionalChain([options, 'optionalAccess', _128 => _128.batchSize]))) {
7788
7866
  data.push(record);
7789
7867
  }
7790
7868
  this._fetchedData = data;
@@ -7879,7 +7957,7 @@ var Experiment2 = (_class12 = class extends ObjectFetcher {
7879
7957
  * @returns The `id` of the logged event.
7880
7958
  */
7881
7959
  log(event, options) {
7882
- if (this.calledStartSpan && !_optionalChain([options, 'optionalAccess', _113 => _113.allowConcurrentWithSpans])) {
7960
+ if (this.calledStartSpan && !_optionalChain([options, 'optionalAccess', _129 => _129.allowConcurrentWithSpans])) {
7883
7961
  throw new Error(
7884
7962
  "Cannot run toplevel `log` method while using spans. To log to the span, call `experiment.traced` and then log with `span.log`"
7885
7963
  );
@@ -7932,12 +8010,12 @@ var Experiment2 = (_class12 = class extends ObjectFetcher {
7932
8010
  state: this.state,
7933
8011
  ...startSpanParentArgs({
7934
8012
  state: this.state,
7935
- parent: _optionalChain([args, 'optionalAccess', _114 => _114.parent]),
8013
+ parent: _optionalChain([args, 'optionalAccess', _130 => _130.parent]),
7936
8014
  parentObjectType: this.parentObjectType(),
7937
8015
  parentObjectId: this.lazyId,
7938
8016
  parentComputeObjectMetadataArgs: void 0,
7939
8017
  parentSpanIds: void 0,
7940
- propagatedEvent: _optionalChain([args, 'optionalAccess', _115 => _115.propagatedEvent])
8018
+ propagatedEvent: _optionalChain([args, 'optionalAccess', _131 => _131.propagatedEvent])
7941
8019
  }),
7942
8020
  defaultRootType: "eval" /* EVAL */
7943
8021
  });
@@ -8281,16 +8359,22 @@ var SpanImpl = (_class13 = class _SpanImpl {
8281
8359
  ...serializableInternalData,
8282
8360
  [IS_MERGE_FIELD]: this.isMerge
8283
8361
  });
8284
- if (typeof _optionalChain([partialRecord, 'access', _116 => _116.metrics, 'optionalAccess', _117 => _117.end]) === "number") {
8362
+ if (typeof _optionalChain([partialRecord, 'access', _132 => _132.metrics, 'optionalAccess', _133 => _133.end]) === "number") {
8285
8363
  this.loggedEndTime = partialRecord.metrics.end;
8286
8364
  }
8287
8365
  if (this.parentObjectType === 1 /* EXPERIMENT */) {
8288
8366
  const cachedSpan = {
8289
8367
  input: partialRecord.input,
8290
8368
  output: partialRecord.output,
8369
+ expected: partialRecord.expected,
8370
+ error: partialRecord.error,
8371
+ scores: partialRecord.scores,
8372
+ metrics: partialRecord.metrics,
8291
8373
  metadata: partialRecord.metadata,
8374
+ tags: partialRecord.tags,
8292
8375
  span_id: this._spanId,
8293
8376
  span_parents: this._spanParents,
8377
+ is_root: this._spanId === this._rootSpanId,
8294
8378
  span_attributes: partialRecord.span_attributes
8295
8379
  };
8296
8380
  this._state.spanCache.queueWrite(
@@ -8341,18 +8425,18 @@ var SpanImpl = (_class13 = class _SpanImpl {
8341
8425
  );
8342
8426
  }
8343
8427
  startSpan(args) {
8344
- const parentSpanIds = _optionalChain([args, 'optionalAccess', _118 => _118.parent]) ? void 0 : { spanId: this._spanId, rootSpanId: this._rootSpanId };
8428
+ const parentSpanIds = _optionalChain([args, 'optionalAccess', _134 => _134.parent]) ? void 0 : { spanId: this._spanId, rootSpanId: this._rootSpanId };
8345
8429
  return new _SpanImpl({
8346
8430
  state: this._state,
8347
8431
  ...args,
8348
8432
  ...startSpanParentArgs({
8349
8433
  state: this._state,
8350
- parent: _optionalChain([args, 'optionalAccess', _119 => _119.parent]),
8434
+ parent: _optionalChain([args, 'optionalAccess', _135 => _135.parent]),
8351
8435
  parentObjectType: this.parentObjectType,
8352
8436
  parentObjectId: this.parentObjectId,
8353
8437
  parentComputeObjectMetadataArgs: this.parentComputeObjectMetadataArgs,
8354
8438
  parentSpanIds,
8355
- propagatedEvent: _nullishCoalesce(_optionalChain([args, 'optionalAccess', _120 => _120.propagatedEvent]), () => ( this.propagatedEvent))
8439
+ propagatedEvent: _nullishCoalesce(_optionalChain([args, 'optionalAccess', _136 => _136.propagatedEvent]), () => ( this.propagatedEvent))
8356
8440
  })
8357
8441
  });
8358
8442
  }
@@ -8366,12 +8450,12 @@ var SpanImpl = (_class13 = class _SpanImpl {
8366
8450
  ...args,
8367
8451
  ...startSpanParentArgs({
8368
8452
  state: this._state,
8369
- parent: _optionalChain([args, 'optionalAccess', _121 => _121.parent]),
8453
+ parent: _optionalChain([args, 'optionalAccess', _137 => _137.parent]),
8370
8454
  parentObjectType: this.parentObjectType,
8371
8455
  parentObjectId: this.parentObjectId,
8372
8456
  parentComputeObjectMetadataArgs: this.parentComputeObjectMetadataArgs,
8373
8457
  parentSpanIds,
8374
- propagatedEvent: _nullishCoalesce(_optionalChain([args, 'optionalAccess', _122 => _122.propagatedEvent]), () => ( this.propagatedEvent))
8458
+ propagatedEvent: _nullishCoalesce(_optionalChain([args, 'optionalAccess', _138 => _138.propagatedEvent]), () => ( this.propagatedEvent))
8375
8459
  }),
8376
8460
  spanId
8377
8461
  });
@@ -8380,7 +8464,7 @@ var SpanImpl = (_class13 = class _SpanImpl {
8380
8464
  let endTime;
8381
8465
  let internalData = {};
8382
8466
  if (!this.loggedEndTime) {
8383
- endTime = _nullishCoalesce(_optionalChain([args, 'optionalAccess', _123 => _123.endTime]), () => ( getCurrentUnixTimestamp()));
8467
+ endTime = _nullishCoalesce(_optionalChain([args, 'optionalAccess', _139 => _139.endTime]), () => ( getCurrentUnixTimestamp()));
8384
8468
  internalData = { metrics: { end: endTime } };
8385
8469
  } else {
8386
8470
  endTime = this.loggedEndTime;
@@ -8431,8 +8515,8 @@ var SpanImpl = (_class13 = class _SpanImpl {
8431
8515
  const args = this.parentComputeObjectMetadataArgs;
8432
8516
  switch (this.parentObjectType) {
8433
8517
  case 2 /* PROJECT_LOGS */: {
8434
- const projectID = _optionalChain([args, 'optionalAccess', _124 => _124.project_id]) || this.parentObjectId.getSync().value;
8435
- const projectName = _optionalChain([args, 'optionalAccess', _125 => _125.project_name]);
8518
+ const projectID = _optionalChain([args, 'optionalAccess', _140 => _140.project_id]) || this.parentObjectId.getSync().value;
8519
+ const projectName = _optionalChain([args, 'optionalAccess', _141 => _141.project_name]);
8436
8520
  if (projectID) {
8437
8521
  return `${baseUrl}/object?object_type=project_logs&object_id=${projectID}&id=${this._id}`;
8438
8522
  } else if (projectName) {
@@ -8442,7 +8526,7 @@ var SpanImpl = (_class13 = class _SpanImpl {
8442
8526
  }
8443
8527
  }
8444
8528
  case 1 /* EXPERIMENT */: {
8445
- const expID = _optionalChain([args, 'optionalAccess', _126 => _126.experiment_id]) || _optionalChain([this, 'access', _127 => _127.parentObjectId, 'optionalAccess', _128 => _128.getSync, 'call', _129 => _129(), 'optionalAccess', _130 => _130.value]);
8529
+ const expID = _optionalChain([args, 'optionalAccess', _142 => _142.experiment_id]) || _optionalChain([this, 'access', _143 => _143.parentObjectId, 'optionalAccess', _144 => _144.getSync, 'call', _145 => _145(), 'optionalAccess', _146 => _146.value]);
8446
8530
  if (!expID) {
8447
8531
  return getErrPermlink("provide-experiment-id");
8448
8532
  } else {
@@ -8535,9 +8619,9 @@ var Dataset2 = (_class14 = class extends ObjectFetcher {
8535
8619
  );_class14.prototype.__init57.call(this);_class14.prototype.__init58.call(this);;
8536
8620
  this.state = state;
8537
8621
  this.lazyMetadata = lazyMetadata;
8538
- this.lazyPinnedVersion = _optionalChain([pinState, 'optionalAccess', _131 => _131.lazyPinnedVersion]);
8539
- this.pinnedEnvironment = _optionalChain([pinState, 'optionalAccess', _132 => _132.pinnedEnvironment]);
8540
- this.pinnedSnapshotName = _optionalChain([pinState, 'optionalAccess', _133 => _133.pinnedSnapshotName]);
8622
+ this.lazyPinnedVersion = _optionalChain([pinState, 'optionalAccess', _147 => _147.lazyPinnedVersion]);
8623
+ this.pinnedEnvironment = _optionalChain([pinState, 'optionalAccess', _148 => _148.pinnedEnvironment]);
8624
+ this.pinnedSnapshotName = _optionalChain([pinState, 'optionalAccess', _149 => _149.pinnedSnapshotName]);
8541
8625
  }
8542
8626
 
8543
8627
  __init57() {this.__braintrust_dataset_marker = true}
@@ -8626,6 +8710,7 @@ var Dataset2 = (_class14 = class extends ObjectFetcher {
8626
8710
  metadata,
8627
8711
  tags,
8628
8712
  output,
8713
+ origin,
8629
8714
  isMerge
8630
8715
  }) {
8631
8716
  return new LazyValue(async () => {
@@ -8640,6 +8725,7 @@ var Dataset2 = (_class14 = class extends ObjectFetcher {
8640
8725
  created: !isMerge ? (/* @__PURE__ */ new Date()).toISOString() : void 0,
8641
8726
  //if we're merging/updating an event we will not add this ts
8642
8727
  metadata,
8728
+ origin,
8643
8729
  ...!!isMerge ? {
8644
8730
  [IS_MERGE_FIELD]: true
8645
8731
  } : {}
@@ -8659,6 +8745,7 @@ var Dataset2 = (_class14 = class extends ObjectFetcher {
8659
8745
  * about anything else that's relevant, that you can use to help find and analyze examples later. For example, you could log the
8660
8746
  * `prompt`, example's `id`, or anything else that would be useful to slice/dice later. The values in `metadata` can be any
8661
8747
  * JSON-serializable type, but its keys must be strings.
8748
+ * @param event.origin (Optional) a reference to the source object this dataset record was derived from.
8662
8749
  * @param event.id (Optional) a unique identifier for the event. If you don't provide one, Braintrust will generate one for you.
8663
8750
  * @param event.output: (Deprecated) The output of your application. Use `expected` instead.
8664
8751
  * @returns The `id` of the logged record.
@@ -8669,7 +8756,8 @@ var Dataset2 = (_class14 = class extends ObjectFetcher {
8669
8756
  metadata,
8670
8757
  tags,
8671
8758
  id,
8672
- output
8759
+ output,
8760
+ origin
8673
8761
  }) {
8674
8762
  this.validateEvent({ metadata, expected, output, tags });
8675
8763
  const rowId = id || _uuid.v4.call(void 0, );
@@ -8681,6 +8769,7 @@ var Dataset2 = (_class14 = class extends ObjectFetcher {
8681
8769
  metadata,
8682
8770
  tags,
8683
8771
  output,
8772
+ origin,
8684
8773
  isMerge: false
8685
8774
  })
8686
8775
  );
@@ -9060,16 +9149,16 @@ var Prompt2 = (_class15 = class _Prompt {
9060
9149
  return "slug" in this.metadata ? this.metadata.slug : this.metadata.id;
9061
9150
  }
9062
9151
  get prompt() {
9063
- return _optionalChain([this, 'access', _134 => _134.getParsedPromptData, 'call', _135 => _135(), 'optionalAccess', _136 => _136.prompt]);
9152
+ return _optionalChain([this, 'access', _150 => _150.getParsedPromptData, 'call', _151 => _151(), 'optionalAccess', _152 => _152.prompt]);
9064
9153
  }
9065
9154
  get version() {
9066
9155
  return this.metadata[TRANSACTION_ID_FIELD];
9067
9156
  }
9068
9157
  get options() {
9069
- return _optionalChain([this, 'access', _137 => _137.getParsedPromptData, 'call', _138 => _138(), 'optionalAccess', _139 => _139.options]) || {};
9158
+ return _optionalChain([this, 'access', _153 => _153.getParsedPromptData, 'call', _154 => _154(), 'optionalAccess', _155 => _155.options]) || {};
9070
9159
  }
9071
9160
  get templateFormat() {
9072
- return _optionalChain([this, 'access', _140 => _140.getParsedPromptData, 'call', _141 => _141(), 'optionalAccess', _142 => _142.template_format]);
9161
+ return _optionalChain([this, 'access', _156 => _156.getParsedPromptData, 'call', _157 => _157(), 'optionalAccess', _158 => _158.template_format]);
9073
9162
  }
9074
9163
  get promptData() {
9075
9164
  return this.getParsedPromptData();
@@ -9231,7 +9320,7 @@ var Prompt2 = (_class15 = class _Prompt {
9231
9320
  return {
9232
9321
  type: "chat",
9233
9322
  messages,
9234
- ..._optionalChain([prompt, 'access', _143 => _143.tools, 'optionalAccess', _144 => _144.trim, 'call', _145 => _145()]) ? {
9323
+ ..._optionalChain([prompt, 'access', _159 => _159.tools, 'optionalAccess', _160 => _160.trim, 'call', _161 => _161()]) ? {
9235
9324
  tools: render(prompt.tools)
9236
9325
  } : void 0
9237
9326
  };
@@ -9549,7 +9638,7 @@ function getChannelSpanInfo(event) {
9549
9638
  if (isObject(event.span_info)) {
9550
9639
  return event.span_info;
9551
9640
  }
9552
- const firstArg = _optionalChain([event, 'access', _146 => _146.arguments, 'optionalAccess', _147 => _147[0]]);
9641
+ const firstArg = _optionalChain([event, 'access', _162 => _162.arguments, 'optionalAccess', _163 => _163[0]]);
9553
9642
  if (hasChannelSpanInfo(firstArg)) {
9554
9643
  return firstArg.span_info;
9555
9644
  }
@@ -9560,13 +9649,13 @@ function buildStartSpanArgs(config, event) {
9560
9649
  const spanAttributes = {
9561
9650
  type: config.type
9562
9651
  };
9563
- if (isObject(_optionalChain([spanInfo, 'optionalAccess', _148 => _148.spanAttributes]))) {
9652
+ if (isObject(_optionalChain([spanInfo, 'optionalAccess', _164 => _164.spanAttributes]))) {
9564
9653
  mergeDicts(spanAttributes, spanInfo.spanAttributes);
9565
9654
  }
9566
9655
  return {
9567
- name: typeof _optionalChain([spanInfo, 'optionalAccess', _149 => _149.name]) === "string" && spanInfo.name ? spanInfo.name : config.name,
9656
+ name: typeof _optionalChain([spanInfo, 'optionalAccess', _165 => _165.name]) === "string" && spanInfo.name ? spanInfo.name : config.name,
9568
9657
  spanAttributes,
9569
- spanInfoMetadata: isObject(_optionalChain([spanInfo, 'optionalAccess', _150 => _150.metadata])) ? spanInfo.metadata : void 0
9658
+ spanInfoMetadata: isObject(_optionalChain([spanInfo, 'optionalAccess', _166 => _166.metadata])) ? spanInfo.metadata : void 0
9570
9659
  };
9571
9660
  }
9572
9661
  function mergeInputMetadata(metadata, spanInfoMetadata) {
@@ -9656,7 +9745,7 @@ var BasePlugin = (_class17 = class {constructor() { _class17.prototype.__init62.
9656
9745
  try {
9657
9746
  const output = config.extractOutput(event.result, event);
9658
9747
  const metrics = config.extractMetrics(event.result, startTime, event);
9659
- const metadata = _optionalChain([config, 'access', _151 => _151.extractMetadata, 'optionalCall', _152 => _152(event.result, event)]);
9748
+ const metadata = _optionalChain([config, 'access', _167 => _167.extractMetadata, 'optionalCall', _168 => _168(event.result, event)]);
9660
9749
  span.log({
9661
9750
  output,
9662
9751
  ...metadata !== void 0 ? { metadata } : {},
@@ -9976,7 +10065,7 @@ function ensureSpanStateForEvent(states, config, event, channelName) {
9976
10065
  function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelName) {
9977
10066
  const state = _internalGetGlobalState();
9978
10067
  const startChannel = tracingChannel2.start;
9979
- const contextManager = _optionalChain([state, 'optionalAccess', _153 => _153.contextManager]);
10068
+ const contextManager = _optionalChain([state, 'optionalAccess', _169 => _169.contextManager]);
9980
10069
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
9981
10070
  if (!currentSpanStore || !startChannel) {
9982
10071
  return void 0;
@@ -10064,7 +10153,7 @@ function traceAsyncChannel(channel2, config) {
10064
10153
  startTime,
10065
10154
  asyncEndEvent
10066
10155
  );
10067
- const metadata = _optionalChain([config, 'access', _154 => _154.extractMetadata, 'optionalCall', _155 => _155(
10156
+ const metadata = _optionalChain([config, 'access', _170 => _170.extractMetadata, 'optionalCall', _171 => _171(
10068
10157
  asyncEndEvent.result,
10069
10158
  asyncEndEvent
10070
10159
  )]);
@@ -10086,7 +10175,7 @@ function traceAsyncChannel(channel2, config) {
10086
10175
  };
10087
10176
  tracingChannel2.subscribe(handlers);
10088
10177
  return () => {
10089
- _optionalChain([unbindCurrentSpanStore, 'optionalCall', _156 => _156()]);
10178
+ _optionalChain([unbindCurrentSpanStore, 'optionalCall', _172 => _172()]);
10090
10179
  tracingChannel2.unsubscribe(handlers);
10091
10180
  };
10092
10181
  }
@@ -10192,7 +10281,7 @@ function traceStreamingChannel(channel2, config) {
10192
10281
  });
10193
10282
  return;
10194
10283
  }
10195
- if (_optionalChain([config, 'access', _157 => _157.patchResult, 'optionalCall', _158 => _158({
10284
+ if (_optionalChain([config, 'access', _173 => _173.patchResult, 'optionalCall', _174 => _174({
10196
10285
  channelName,
10197
10286
  endEvent: asyncEndEvent,
10198
10287
  result: asyncEndEvent.result,
@@ -10212,7 +10301,7 @@ function traceStreamingChannel(channel2, config) {
10212
10301
  startTime,
10213
10302
  asyncEndEvent
10214
10303
  );
10215
- const metadata = _optionalChain([config, 'access', _159 => _159.extractMetadata, 'optionalCall', _160 => _160(
10304
+ const metadata = _optionalChain([config, 'access', _175 => _175.extractMetadata, 'optionalCall', _176 => _176(
10216
10305
  asyncEndEvent.result,
10217
10306
  asyncEndEvent
10218
10307
  )]);
@@ -10245,7 +10334,7 @@ function traceStreamingChannel(channel2, config) {
10245
10334
  };
10246
10335
  tracingChannel2.subscribe(handlers);
10247
10336
  return () => {
10248
- _optionalChain([unbindCurrentSpanStore, 'optionalCall', _161 => _161()]);
10337
+ _optionalChain([unbindCurrentSpanStore, 'optionalCall', _177 => _177()]);
10249
10338
  tracingChannel2.unsubscribe(handlers);
10250
10339
  };
10251
10340
  }
@@ -10280,7 +10369,7 @@ function traceSyncStreamChannel(channel2, config) {
10280
10369
  ...endEvent,
10281
10370
  result
10282
10371
  };
10283
- if (_optionalChain([config, 'access', _162 => _162.patchResult, 'optionalCall', _163 => _163({
10372
+ if (_optionalChain([config, 'access', _178 => _178.patchResult, 'optionalCall', _179 => _179({
10284
10373
  channelName,
10285
10374
  endEvent: resolvedEndEvent,
10286
10375
  result,
@@ -10361,7 +10450,7 @@ function traceSyncStreamChannel(channel2, config) {
10361
10450
  };
10362
10451
  tracingChannel2.subscribe(handlers);
10363
10452
  return () => {
10364
- _optionalChain([unbindCurrentSpanStore, 'optionalCall', _164 => _164()]);
10453
+ _optionalChain([unbindCurrentSpanStore, 'optionalCall', _180 => _180()]);
10365
10454
  tracingChannel2.unsubscribe(handlers);
10366
10455
  };
10367
10456
  }
@@ -10436,7 +10525,7 @@ function processInputAttachments(input) {
10436
10525
  let attachmentIndex = 0;
10437
10526
  const inferMediaTypeFromDataUrl = (value, fallback2) => {
10438
10527
  const mediaTypeMatch = value.match(/^data:([^;]+);/);
10439
- return _optionalChain([mediaTypeMatch, 'optionalAccess', _165 => _165[1]]) || fallback2;
10528
+ return _optionalChain([mediaTypeMatch, 'optionalAccess', _181 => _181[1]]) || fallback2;
10440
10529
  };
10441
10530
  const toAttachment = (value, mediaType, filename) => {
10442
10531
  const blob = convertDataToBlob(value, mediaType);
@@ -10690,11 +10779,11 @@ var OpenAIPlugin = class extends BasePlugin {
10690
10779
  };
10691
10780
  },
10692
10781
  extractOutput: (result) => {
10693
- return _optionalChain([result, 'optionalAccess', _166 => _166.choices]);
10782
+ return _optionalChain([result, 'optionalAccess', _182 => _182.choices]);
10694
10783
  },
10695
10784
  extractMetrics: (result, startTime, endEvent) => {
10696
10785
  const metrics = withCachedMetric(
10697
- parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _167 => _167.usage])),
10786
+ parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _183 => _183.usage])),
10698
10787
  result,
10699
10788
  endEvent
10700
10789
  );
@@ -10718,12 +10807,12 @@ var OpenAIPlugin = class extends BasePlugin {
10718
10807
  };
10719
10808
  },
10720
10809
  extractOutput: (result) => {
10721
- const embedding = _optionalChain([result, 'optionalAccess', _168 => _168.data, 'optionalAccess', _169 => _169[0], 'optionalAccess', _170 => _170.embedding]);
10810
+ const embedding = _optionalChain([result, 'optionalAccess', _184 => _184.data, 'optionalAccess', _185 => _185[0], 'optionalAccess', _186 => _186.embedding]);
10722
10811
  return Array.isArray(embedding) ? { embedding_length: embedding.length } : void 0;
10723
10812
  },
10724
10813
  extractMetrics: (result, _startTime, endEvent) => {
10725
10814
  return withCachedMetric(
10726
- parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _171 => _171.usage])),
10815
+ parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _187 => _187.usage])),
10727
10816
  result,
10728
10817
  endEvent
10729
10818
  );
@@ -10742,11 +10831,11 @@ var OpenAIPlugin = class extends BasePlugin {
10742
10831
  };
10743
10832
  },
10744
10833
  extractOutput: (result) => {
10745
- return _optionalChain([result, 'optionalAccess', _172 => _172.choices]);
10834
+ return _optionalChain([result, 'optionalAccess', _188 => _188.choices]);
10746
10835
  },
10747
10836
  extractMetrics: (result, startTime, endEvent) => {
10748
10837
  const metrics = withCachedMetric(
10749
- parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _173 => _173.usage])),
10838
+ parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _189 => _189.usage])),
10750
10839
  result,
10751
10840
  endEvent
10752
10841
  );
@@ -10783,11 +10872,11 @@ var OpenAIPlugin = class extends BasePlugin {
10783
10872
  };
10784
10873
  },
10785
10874
  extractOutput: (result) => {
10786
- return _optionalChain([result, 'optionalAccess', _174 => _174.results]);
10875
+ return _optionalChain([result, 'optionalAccess', _190 => _190.results]);
10787
10876
  },
10788
10877
  extractMetrics: (result, _startTime, endEvent) => {
10789
10878
  return withCachedMetric(
10790
- parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _175 => _175.usage])),
10879
+ parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _191 => _191.usage])),
10791
10880
  result,
10792
10881
  endEvent
10793
10882
  );
@@ -10806,7 +10895,7 @@ var OpenAIPlugin = class extends BasePlugin {
10806
10895
  };
10807
10896
  },
10808
10897
  extractOutput: (result) => {
10809
- return processImagesInOutput(_optionalChain([result, 'optionalAccess', _176 => _176.output]));
10898
+ return processImagesInOutput(_optionalChain([result, 'optionalAccess', _192 => _192.output]));
10810
10899
  },
10811
10900
  extractMetadata: (result) => {
10812
10901
  if (!result) {
@@ -10817,7 +10906,7 @@ var OpenAIPlugin = class extends BasePlugin {
10817
10906
  },
10818
10907
  extractMetrics: (result, startTime, endEvent) => {
10819
10908
  const metrics = withCachedMetric(
10820
- parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _177 => _177.usage])),
10909
+ parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _193 => _193.usage])),
10821
10910
  result,
10822
10911
  endEvent
10823
10912
  );
@@ -10870,7 +10959,7 @@ var OpenAIPlugin = class extends BasePlugin {
10870
10959
  };
10871
10960
  },
10872
10961
  extractOutput: (result) => {
10873
- return processImagesInOutput(_optionalChain([result, 'optionalAccess', _178 => _178.output]));
10962
+ return processImagesInOutput(_optionalChain([result, 'optionalAccess', _194 => _194.output]));
10874
10963
  },
10875
10964
  extractMetadata: (result) => {
10876
10965
  if (!result) {
@@ -10881,7 +10970,7 @@ var OpenAIPlugin = class extends BasePlugin {
10881
10970
  },
10882
10971
  extractMetrics: (result, startTime, endEvent) => {
10883
10972
  const metrics = withCachedMetric(
10884
- parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _179 => _179.usage])),
10973
+ parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _195 => _195.usage])),
10885
10974
  result,
10886
10975
  endEvent
10887
10976
  );
@@ -10905,7 +10994,7 @@ var OpenAIPlugin = class extends BasePlugin {
10905
10994
  };
10906
10995
  },
10907
10996
  extractOutput: (result) => {
10908
- return processImagesInOutput(_optionalChain([result, 'optionalAccess', _180 => _180.output]));
10997
+ return processImagesInOutput(_optionalChain([result, 'optionalAccess', _196 => _196.output]));
10909
10998
  },
10910
10999
  extractMetadata: (result) => {
10911
11000
  if (!result) {
@@ -10916,7 +11005,7 @@ var OpenAIPlugin = class extends BasePlugin {
10916
11005
  },
10917
11006
  extractMetrics: (result, startTime, endEvent) => {
10918
11007
  const metrics = withCachedMetric(
10919
- parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _181 => _181.usage])),
11008
+ parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _197 => _197.usage])),
10920
11009
  result,
10921
11010
  endEvent
10922
11011
  );
@@ -11018,11 +11107,11 @@ function aggregateChatLogprobs(existing, incoming) {
11018
11107
  return _nullishCoalesce(existing, () => ( null));
11019
11108
  }
11020
11109
  const aggregated = existing && existing !== null ? { ...existing, ...incoming } : { ...incoming };
11021
- const content = mergeLogprobTokens(_optionalChain([existing, 'optionalAccess', _182 => _182.content]), incoming.content);
11110
+ const content = mergeLogprobTokens(_optionalChain([existing, 'optionalAccess', _198 => _198.content]), incoming.content);
11022
11111
  if (content !== void 0) {
11023
11112
  aggregated.content = content;
11024
11113
  }
11025
- const refusal = mergeLogprobTokens(_optionalChain([existing, 'optionalAccess', _183 => _183.refusal]), incoming.refusal);
11114
+ const refusal = mergeLogprobTokens(_optionalChain([existing, 'optionalAccess', _199 => _199.refusal]), incoming.refusal);
11026
11115
  if (refusal !== void 0) {
11027
11116
  aggregated.refusal = refusal;
11028
11117
  }
@@ -11043,7 +11132,7 @@ function aggregateChatCompletionChunks(chunks, streamResult, endEvent) {
11043
11132
  ...parseMetricsFromUsage(chunk.usage)
11044
11133
  };
11045
11134
  }
11046
- const choice = _optionalChain([chunk, 'access', _184 => _184.choices, 'optionalAccess', _185 => _185[0]]);
11135
+ const choice = _optionalChain([chunk, 'access', _200 => _200.choices, 'optionalAccess', _201 => _201[0]]);
11047
11136
  if (!choice) {
11048
11137
  continue;
11049
11138
  }
@@ -11113,14 +11202,14 @@ function aggregateResponseStreamEvents(chunks, _streamResult, endEvent) {
11113
11202
  continue;
11114
11203
  }
11115
11204
  const response = chunk.response;
11116
- if (_optionalChain([response, 'optionalAccess', _186 => _186.output]) !== void 0) {
11205
+ if (_optionalChain([response, 'optionalAccess', _202 => _202.output]) !== void 0) {
11117
11206
  output = processImagesInOutput(response.output);
11118
11207
  }
11119
11208
  const { usage: _usage, output: _output, ...rest } = response || {};
11120
11209
  if (Object.keys(rest).length > 0) {
11121
11210
  metadata = rest;
11122
11211
  }
11123
- metrics = parseMetricsFromUsage(_optionalChain([response, 'optionalAccess', _187 => _187.usage]));
11212
+ metrics = parseMetricsFromUsage(_optionalChain([response, 'optionalAccess', _203 => _203.usage]));
11124
11213
  }
11125
11214
  return {
11126
11215
  output,
@@ -11295,7 +11384,7 @@ async function handleCodexEvent(state, event) {
11295
11384
  return;
11296
11385
  case "turn.failed":
11297
11386
  await finalizeCodexRun(state, {
11298
- error: _nullishCoalesce(_optionalChain([event, 'access', _188 => _188.error, 'optionalAccess', _189 => _189.message]), () => ( "Codex turn failed"))
11387
+ error: _nullishCoalesce(_optionalChain([event, 'access', _204 => _204.error, 'optionalAccess', _205 => _205.message]), () => ( "Codex turn failed"))
11299
11388
  });
11300
11389
  return;
11301
11390
  case "item.started":
@@ -11566,7 +11655,7 @@ function mcpToolSpanArgs(parent, baseMetadata, item) {
11566
11655
  spanAttributes: { type: "tool" /* TOOL */ }
11567
11656
  },
11568
11657
  end: {
11569
- ..._optionalChain([item, 'access', _190 => _190.error, 'optionalAccess', _191 => _191.message]) ? { error: item.error.message } : {},
11658
+ ..._optionalChain([item, 'access', _206 => _206.error, 'optionalAccess', _207 => _207.message]) ? { error: item.error.message } : {},
11570
11659
  metadata,
11571
11660
  output: item.result
11572
11661
  }
@@ -11628,7 +11717,7 @@ function extractThreadFromEvent(event) {
11628
11717
  function extractThreadMetadata(thread) {
11629
11718
  const threadOptions = extractThreadOptions(thread);
11630
11719
  return {
11631
- ..._optionalChain([thread, 'optionalAccess', _192 => _192.id]) ? { "openai_codex.thread_id": thread.id } : {},
11720
+ ..._optionalChain([thread, 'optionalAccess', _208 => _208.id]) ? { "openai_codex.thread_id": thread.id } : {},
11632
11721
  ...extractThreadOptionsMetadata(threadOptions)
11633
11722
  };
11634
11723
  }
@@ -11829,7 +11918,7 @@ var AnthropicPlugin = class extends BasePlugin {
11829
11918
  return message ? { role: message.role, content: message.content } : null;
11830
11919
  },
11831
11920
  extractMetrics: (message, startTime) => {
11832
- const metrics = parseMetricsFromUsage2(_optionalChain([message, 'optionalAccess', _193 => _193.usage]));
11921
+ const metrics = parseMetricsFromUsage2(_optionalChain([message, 'optionalAccess', _209 => _209.usage]));
11833
11922
  if (startTime) {
11834
11923
  metrics.time_to_first_token = getCurrentUnixTimestamp() - startTime;
11835
11924
  }
@@ -11844,7 +11933,7 @@ var AnthropicPlugin = class extends BasePlugin {
11844
11933
  const metadata = {};
11845
11934
  const metas = ["stop_reason", "stop_sequence"];
11846
11935
  for (const m of metas) {
11847
- if (_optionalChain([message, 'optionalAccess', _194 => _194[m]]) !== void 0) {
11936
+ if (_optionalChain([message, 'optionalAccess', _210 => _210[m]]) !== void 0) {
11848
11937
  metadata[m] = message[m];
11849
11938
  }
11850
11939
  }
@@ -11994,8 +12083,8 @@ function wrapAnthropicToolRunnerTool(tool, index, state) {
11994
12083
  Object.getOwnPropertyDescriptors(tool)
11995
12084
  );
11996
12085
  Object.defineProperty(wrappedTool, "run", {
11997
- configurable: _nullishCoalesce(_optionalChain([runDescriptor, 'optionalAccess', _195 => _195.configurable]), () => ( true)),
11998
- enumerable: _nullishCoalesce(_optionalChain([runDescriptor, 'optionalAccess', _196 => _196.enumerable]), () => ( true)),
12086
+ configurable: _nullishCoalesce(_optionalChain([runDescriptor, 'optionalAccess', _211 => _211.configurable]), () => ( true)),
12087
+ enumerable: _nullishCoalesce(_optionalChain([runDescriptor, 'optionalAccess', _212 => _212.enumerable]), () => ( true)),
11999
12088
  value: function braintrustAnthropicToolRunnerRun(...args) {
12000
12089
  return state.span.traced(
12001
12090
  (span) => {
@@ -12032,7 +12121,7 @@ function wrapAnthropicToolRunnerTool(tool, index, state) {
12032
12121
  }
12033
12122
  );
12034
12123
  },
12035
- writable: _nullishCoalesce(_optionalChain([runDescriptor, 'optionalAccess', _197 => _197.writable]), () => ( true))
12124
+ writable: _nullishCoalesce(_optionalChain([runDescriptor, 'optionalAccess', _213 => _213.writable]), () => ( true))
12036
12125
  });
12037
12126
  Object.defineProperty(wrappedTool, ANTHROPIC_TOOL_RUNNER_TOOL_WRAPPED, {
12038
12127
  configurable: false,
@@ -12137,10 +12226,10 @@ async function finalizeAnthropicToolRunner(state, finalMessage) {
12137
12226
  const metadata = {
12138
12227
  anthropic_tool_runner_iterations: state.iterationCount
12139
12228
  };
12140
- if (_optionalChain([message, 'optionalAccess', _198 => _198.stop_reason]) !== void 0) {
12229
+ if (_optionalChain([message, 'optionalAccess', _214 => _214.stop_reason]) !== void 0) {
12141
12230
  metadata.stop_reason = message.stop_reason;
12142
12231
  }
12143
- if (_optionalChain([message, 'optionalAccess', _199 => _199.stop_sequence]) !== void 0) {
12232
+ if (_optionalChain([message, 'optionalAccess', _215 => _215.stop_sequence]) !== void 0) {
12144
12233
  metadata.stop_sequence = message.stop_sequence;
12145
12234
  }
12146
12235
  state.span.log({
@@ -12282,13 +12371,13 @@ function aggregateAnthropicStreamChunks(chunks) {
12282
12371
  let metadata = {};
12283
12372
  let role;
12284
12373
  for (const event of chunks) {
12285
- switch (_optionalChain([event, 'optionalAccess', _200 => _200.type])) {
12374
+ switch (_optionalChain([event, 'optionalAccess', _216 => _216.type])) {
12286
12375
  case "message_start":
12287
- if (_optionalChain([event, 'access', _201 => _201.message, 'optionalAccess', _202 => _202.usage])) {
12376
+ if (_optionalChain([event, 'access', _217 => _217.message, 'optionalAccess', _218 => _218.usage])) {
12288
12377
  const initialMetrics = parseMetricsFromUsage2(event.message.usage);
12289
12378
  metrics = { ...metrics, ...initialMetrics };
12290
12379
  }
12291
- if (typeof _optionalChain([event, 'access', _203 => _203.message, 'optionalAccess', _204 => _204.role]) === "string") {
12380
+ if (typeof _optionalChain([event, 'access', _219 => _219.message, 'optionalAccess', _220 => _220.role]) === "string") {
12292
12381
  role = event.message.role;
12293
12382
  }
12294
12383
  break;
@@ -12354,7 +12443,7 @@ function aggregateAnthropicStreamChunks(chunks) {
12354
12443
  })).filter(({ block }) => block !== void 0).sort((left, right) => left.index - right.index).map(({ block }) => block);
12355
12444
  let output = fallbackTextDeltas.join("");
12356
12445
  if (orderedContent.length > 0) {
12357
- if (orderedContent.every(isTextContentBlock) && orderedContent.every((block) => !_optionalChain([block, 'access', _205 => _205.citations, 'optionalAccess', _206 => _206.length]))) {
12446
+ if (orderedContent.every(isTextContentBlock) && orderedContent.every((block) => !_optionalChain([block, 'access', _221 => _221.citations, 'optionalAccess', _222 => _222.length]))) {
12358
12447
  output = orderedContent.map((block) => block.text).join("");
12359
12448
  } else {
12360
12449
  output = {
@@ -12381,7 +12470,7 @@ function finalizeContentBlock(index, contentBlocks, contentBlockDeltas, fallback
12381
12470
  return;
12382
12471
  }
12383
12472
  const acc = contentBlockDeltas[index];
12384
- const text = _nullishCoalesce(_optionalChain([acc, 'optionalAccess', _207 => _207.textDeltas, 'access', _208 => _208.join, 'call', _209 => _209("")]), () => ( ""));
12473
+ const text = _nullishCoalesce(_optionalChain([acc, 'optionalAccess', _223 => _223.textDeltas, 'access', _224 => _224.join, 'call', _225 => _225("")]), () => ( ""));
12385
12474
  if (isToolUseLikeContentBlock(contentBlock)) {
12386
12475
  if (!text) {
12387
12476
  return;
@@ -12412,7 +12501,7 @@ function finalizeContentBlock(index, contentBlocks, contentBlockDeltas, fallback
12412
12501
  return;
12413
12502
  }
12414
12503
  const updated = { ...contentBlock, text };
12415
- if (_optionalChain([acc, 'optionalAccess', _210 => _210.citations, 'access', _211 => _211.length])) {
12504
+ if (_optionalChain([acc, 'optionalAccess', _226 => _226.citations, 'access', _227 => _227.length])) {
12416
12505
  updated.citations = acc.citations;
12417
12506
  }
12418
12507
  contentBlocks[index] = updated;
@@ -12917,10 +13006,10 @@ var AISDKPlugin = class extends BasePlugin {
12917
13006
  }
12918
13007
  };
12919
13008
  function resolveDenyOutputPaths(event, defaultDenyOutputPaths) {
12920
- if (Array.isArray(_optionalChain([event, 'optionalAccess', _212 => _212.denyOutputPaths]))) {
13009
+ if (Array.isArray(_optionalChain([event, 'optionalAccess', _228 => _228.denyOutputPaths]))) {
12921
13010
  return event.denyOutputPaths;
12922
13011
  }
12923
- const firstArgument2 = _optionalChain([event, 'optionalAccess', _213 => _213.arguments]) && event.arguments.length > 0 ? event.arguments[0] : void 0;
13012
+ const firstArgument2 = _optionalChain([event, 'optionalAccess', _229 => _229.arguments]) && event.arguments.length > 0 ? event.arguments[0] : void 0;
12924
13013
  if (!firstArgument2 || typeof firstArgument2 !== "object") {
12925
13014
  return defaultDenyOutputPaths;
12926
13015
  }
@@ -13135,7 +13224,7 @@ var convertImageToAttachment = (image, explicitMimeType) => {
13135
13224
  try {
13136
13225
  if (typeof image === "string" && image.startsWith("data:")) {
13137
13226
  const [mimeTypeSection, base64Data] = image.split(",");
13138
- const mimeType = _optionalChain([mimeTypeSection, 'access', _214 => _214.match, 'call', _215 => _215(/data:(.*?);/), 'optionalAccess', _216 => _216[1]]);
13227
+ const mimeType = _optionalChain([mimeTypeSection, 'access', _230 => _230.match, 'call', _231 => _231(/data:(.*?);/), 'optionalAccess', _232 => _232[1]]);
13139
13228
  if (mimeType && base64Data) {
13140
13229
  const blob = convertDataToBlob(base64Data, mimeType);
13141
13230
  if (blob) {
@@ -13265,7 +13354,7 @@ function extractTopLevelAISDKMetrics(result, event, startTime) {
13265
13354
  return metrics;
13266
13355
  }
13267
13356
  function hasModelChildTracing(event) {
13268
- return _optionalChain([event, 'optionalAccess', _217 => _217.modelWrapped]) === true || _optionalChain([event, 'optionalAccess', _218 => _218.__braintrust_ai_sdk_model_wrapped]) === true;
13357
+ return _optionalChain([event, 'optionalAccess', _233 => _233.modelWrapped]) === true || _optionalChain([event, 'optionalAccess', _234 => _234.__braintrust_ai_sdk_model_wrapped]) === true;
13269
13358
  }
13270
13359
  function createAISDKIntegrationMetadata() {
13271
13360
  return {
@@ -13276,7 +13365,7 @@ function createAISDKIntegrationMetadata() {
13276
13365
  };
13277
13366
  }
13278
13367
  function resolveModelFromSelf(self) {
13279
- return self && typeof self === "object" && "model" in self && self.model ? self.model : self && typeof self === "object" && "settings" in self && _optionalChain([self, 'access', _219 => _219.settings, 'optionalAccess', _220 => _220.model]) ? _optionalChain([self, 'access', _221 => _221.settings, 'optionalAccess', _222 => _222.model]) : void 0;
13368
+ return self && typeof self === "object" && "model" in self && self.model ? self.model : self && typeof self === "object" && "settings" in self && _optionalChain([self, 'access', _235 => _235.settings, 'optionalAccess', _236 => _236.model]) ? _optionalChain([self, 'access', _237 => _237.settings, 'optionalAccess', _238 => _238.model]) : void 0;
13280
13369
  }
13281
13370
  function extractBaseMetadata(model, self) {
13282
13371
  const metadata = createAISDKIntegrationMetadata();
@@ -13403,9 +13492,9 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
13403
13492
  case "raw":
13404
13493
  if (chunk.rawValue) {
13405
13494
  const rawVal = chunk.rawValue;
13406
- if (_optionalChain([rawVal, 'access', _223 => _223.delta, 'optionalAccess', _224 => _224.content])) {
13495
+ if (_optionalChain([rawVal, 'access', _239 => _239.delta, 'optionalAccess', _240 => _240.content])) {
13407
13496
  text += rawVal.delta.content;
13408
- } else if (_optionalChain([rawVal, 'access', _225 => _225.choices, 'optionalAccess', _226 => _226[0], 'optionalAccess', _227 => _227.delta, 'optionalAccess', _228 => _228.content])) {
13497
+ } else if (_optionalChain([rawVal, 'access', _241 => _241.choices, 'optionalAccess', _242 => _242[0], 'optionalAccess', _243 => _243.delta, 'optionalAccess', _244 => _244.content])) {
13409
13498
  text += rawVal.choices[0].delta.content;
13410
13499
  } else if (typeof rawVal.text === "string") {
13411
13500
  text += rawVal.text;
@@ -13559,14 +13648,14 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
13559
13648
  return {
13560
13649
  cleanup: cleanup.length > 0 ? () => {
13561
13650
  while (cleanup.length > 0) {
13562
- _optionalChain([cleanup, 'access', _229 => _229.pop, 'call', _230 => _230(), 'optionalCall', _231 => _231()]);
13651
+ _optionalChain([cleanup, 'access', _245 => _245.pop, 'call', _246 => _246(), 'optionalCall', _247 => _247()]);
13563
13652
  }
13564
13653
  } : void 0,
13565
13654
  modelWrapped
13566
13655
  };
13567
13656
  }
13568
13657
  function finalizeAISDKChildTracing(event) {
13569
- const cleanup = _optionalChain([event, 'optionalAccess', _232 => _232.__braintrust_ai_sdk_cleanup]);
13658
+ const cleanup = _optionalChain([event, 'optionalAccess', _248 => _248.__braintrust_ai_sdk_cleanup]);
13570
13659
  if (event && typeof cleanup === "function") {
13571
13660
  cleanup();
13572
13661
  delete event.__braintrust_ai_sdk_cleanup;
@@ -13779,10 +13868,10 @@ function buildAISDKChildMetadata(model) {
13779
13868
  function buildResolvedMetadataPayload(result) {
13780
13869
  const gatewayInfo = extractGatewayRoutingInfo(result);
13781
13870
  const metadata = {};
13782
- if (_optionalChain([gatewayInfo, 'optionalAccess', _233 => _233.provider])) {
13871
+ if (_optionalChain([gatewayInfo, 'optionalAccess', _249 => _249.provider])) {
13783
13872
  metadata.provider = gatewayInfo.provider;
13784
13873
  }
13785
- if (_optionalChain([gatewayInfo, 'optionalAccess', _234 => _234.model])) {
13874
+ if (_optionalChain([gatewayInfo, 'optionalAccess', _250 => _250.model])) {
13786
13875
  metadata.model = gatewayInfo.model;
13787
13876
  }
13788
13877
  let finishReason;
@@ -13803,7 +13892,7 @@ function resolveAISDKModel(model, aiSDK) {
13803
13892
  if (typeof model !== "string") {
13804
13893
  return model;
13805
13894
  }
13806
- const provider = _nullishCoalesce(_nullishCoalesce(globalThis.AI_SDK_DEFAULT_PROVIDER, () => ( _optionalChain([aiSDK, 'optionalAccess', _235 => _235.gateway]))), () => ( null));
13895
+ const provider = _nullishCoalesce(_nullishCoalesce(globalThis.AI_SDK_DEFAULT_PROVIDER, () => ( _optionalChain([aiSDK, 'optionalAccess', _251 => _251.gateway]))), () => ( null));
13807
13896
  if (provider && typeof provider.languageModel === "function") {
13808
13897
  return provider.languageModel(model);
13809
13898
  }
@@ -13865,8 +13954,8 @@ function processAISDKRerankOutput(output, _denyOutputPaths) {
13865
13954
  return ranking.slice(0, 100).map((item) => {
13866
13955
  const entry = item && typeof item === "object" ? item : void 0;
13867
13956
  return {
13868
- index: typeof _optionalChain([entry, 'optionalAccess', _236 => _236.originalIndex]) === "number" ? entry.originalIndex : void 0,
13869
- relevance_score: typeof _optionalChain([entry, 'optionalAccess', _237 => _237.score]) === "number" ? entry.score : void 0
13957
+ index: typeof _optionalChain([entry, 'optionalAccess', _252 => _252.originalIndex]) === "number" ? entry.originalIndex : void 0,
13958
+ relevance_score: typeof _optionalChain([entry, 'optionalAccess', _253 => _253.score]) === "number" ? entry.score : void 0
13870
13959
  };
13871
13960
  });
13872
13961
  }
@@ -13889,7 +13978,7 @@ function extractTokenMetrics(result) {
13889
13978
  return metrics;
13890
13979
  }
13891
13980
  const promptTokens = firstNumber2(
13892
- _optionalChain([usage, 'access', _238 => _238.inputTokens, 'optionalAccess', _239 => _239.total]),
13981
+ _optionalChain([usage, 'access', _254 => _254.inputTokens, 'optionalAccess', _255 => _255.total]),
13893
13982
  usage.inputTokens,
13894
13983
  usage.promptTokens,
13895
13984
  usage.prompt_tokens
@@ -13898,7 +13987,7 @@ function extractTokenMetrics(result) {
13898
13987
  metrics.prompt_tokens = promptTokens;
13899
13988
  }
13900
13989
  const completionTokens = firstNumber2(
13901
- _optionalChain([usage, 'access', _240 => _240.outputTokens, 'optionalAccess', _241 => _241.total]),
13990
+ _optionalChain([usage, 'access', _256 => _256.outputTokens, 'optionalAccess', _257 => _257.total]),
13902
13991
  usage.outputTokens,
13903
13992
  usage.completionTokens,
13904
13993
  usage.completion_tokens
@@ -13915,8 +14004,8 @@ function extractTokenMetrics(result) {
13915
14004
  metrics.tokens = totalTokens;
13916
14005
  }
13917
14006
  const promptCachedTokens = firstNumber2(
13918
- _optionalChain([usage, 'access', _242 => _242.inputTokens, 'optionalAccess', _243 => _243.cacheRead]),
13919
- _optionalChain([usage, 'access', _244 => _244.inputTokenDetails, 'optionalAccess', _245 => _245.cacheReadTokens]),
14007
+ _optionalChain([usage, 'access', _258 => _258.inputTokens, 'optionalAccess', _259 => _259.cacheRead]),
14008
+ _optionalChain([usage, 'access', _260 => _260.inputTokenDetails, 'optionalAccess', _261 => _261.cacheReadTokens]),
13920
14009
  usage.cachedInputTokens,
13921
14010
  usage.promptCachedTokens,
13922
14011
  usage.prompt_cached_tokens
@@ -13925,8 +14014,8 @@ function extractTokenMetrics(result) {
13925
14014
  metrics.prompt_cached_tokens = promptCachedTokens;
13926
14015
  }
13927
14016
  const promptCacheCreationTokens = firstNumber2(
13928
- _optionalChain([usage, 'access', _246 => _246.inputTokens, 'optionalAccess', _247 => _247.cacheWrite]),
13929
- _optionalChain([usage, 'access', _248 => _248.inputTokenDetails, 'optionalAccess', _249 => _249.cacheWriteTokens]),
14017
+ _optionalChain([usage, 'access', _262 => _262.inputTokens, 'optionalAccess', _263 => _263.cacheWrite]),
14018
+ _optionalChain([usage, 'access', _264 => _264.inputTokenDetails, 'optionalAccess', _265 => _265.cacheWriteTokens]),
13930
14019
  usage.promptCacheCreationTokens,
13931
14020
  usage.prompt_cache_creation_tokens,
13932
14021
  extractAnthropicCacheCreationTokens(result)
@@ -13949,7 +14038,7 @@ function extractTokenMetrics(result) {
13949
14038
  metrics.completion_cached_tokens = completionCachedTokens;
13950
14039
  }
13951
14040
  const reasoningTokenCount = firstNumber2(
13952
- _optionalChain([usage, 'access', _250 => _250.outputTokens, 'optionalAccess', _251 => _251.reasoning]),
14041
+ _optionalChain([usage, 'access', _266 => _266.outputTokens, 'optionalAccess', _267 => _267.reasoning]),
13953
14042
  usage.reasoningTokens,
13954
14043
  usage.completionReasoningTokens,
13955
14044
  usage.completion_reasoning_tokens,
@@ -13979,13 +14068,13 @@ function extractAnthropicCacheCreationTokens(result) {
13979
14068
  result,
13980
14069
  "providerMetadata"
13981
14070
  );
13982
- const anthropicMetadata = _optionalChain([providerMetadata, 'optionalAccess', _252 => _252.anthropic]);
14071
+ const anthropicMetadata = _optionalChain([providerMetadata, 'optionalAccess', _268 => _268.anthropic]);
13983
14072
  if (!anthropicMetadata) {
13984
14073
  return void 0;
13985
14074
  }
13986
14075
  return firstNumber2(
13987
14076
  anthropicMetadata.cacheCreationInputTokens,
13988
- _optionalChain([anthropicMetadata, 'access', _253 => _253.usage, 'optionalAccess', _254 => _254.cache_creation_input_tokens])
14077
+ _optionalChain([anthropicMetadata, 'access', _269 => _269.usage, 'optionalAccess', _270 => _270.cache_creation_input_tokens])
13989
14078
  );
13990
14079
  }
13991
14080
  function safeResultFieldRead(result, field) {
@@ -13993,7 +14082,7 @@ function safeResultFieldRead(result, field) {
13993
14082
  }
13994
14083
  function safeSerializableFieldRead(obj, field) {
13995
14084
  try {
13996
- const value = _optionalChain([obj, 'optionalAccess', _255 => _255[field]]);
14085
+ const value = _optionalChain([obj, 'optionalAccess', _271 => _271[field]]);
13997
14086
  if (isPromiseLike(value)) {
13998
14087
  void Promise.resolve(value).catch(() => {
13999
14088
  });
@@ -14087,7 +14176,7 @@ function extractSerializableOutputFields(output) {
14087
14176
  ];
14088
14177
  for (const name of directFieldNames) {
14089
14178
  try {
14090
- const value = _optionalChain([output, 'optionalAccess', _256 => _256[name]]);
14179
+ const value = _optionalChain([output, 'optionalAccess', _272 => _272[name]]);
14091
14180
  if (isPromiseLike(value)) {
14092
14181
  void Promise.resolve(value).catch(() => {
14093
14182
  });
@@ -14120,8 +14209,8 @@ function isSerializableOutputValue(value) {
14120
14209
  return true;
14121
14210
  }
14122
14211
  function serializeModelWithProvider(model) {
14123
- const modelId = typeof model === "string" ? model : _optionalChain([model, 'optionalAccess', _257 => _257.modelId]);
14124
- const explicitProvider = typeof model === "object" ? _optionalChain([model, 'optionalAccess', _258 => _258.provider]) : void 0;
14212
+ const modelId = typeof model === "string" ? model : _optionalChain([model, 'optionalAccess', _273 => _273.modelId]);
14213
+ const explicitProvider = typeof model === "object" ? _optionalChain([model, 'optionalAccess', _274 => _274.provider]) : void 0;
14125
14214
  if (!modelId) {
14126
14215
  return { model: modelId, provider: explicitProvider };
14127
14216
  }
@@ -14147,7 +14236,7 @@ function parseGatewayModelString(modelString) {
14147
14236
  function extractGatewayRoutingInfo(result) {
14148
14237
  const steps = safeSerializableFieldRead(result, "steps");
14149
14238
  if (Array.isArray(steps) && steps.length > 0) {
14150
- const routing2 = _optionalChain([steps, 'access', _259 => _259[0], 'optionalAccess', _260 => _260.providerMetadata, 'optionalAccess', _261 => _261.gateway, 'optionalAccess', _262 => _262.routing]);
14239
+ const routing2 = _optionalChain([steps, 'access', _275 => _275[0], 'optionalAccess', _276 => _276.providerMetadata, 'optionalAccess', _277 => _277.gateway, 'optionalAccess', _278 => _278.routing]);
14151
14240
  if (routing2) {
14152
14241
  return {
14153
14242
  provider: routing2.resolvedProvider || routing2.finalProvider,
@@ -14159,7 +14248,7 @@ function extractGatewayRoutingInfo(result) {
14159
14248
  result,
14160
14249
  "providerMetadata"
14161
14250
  );
14162
- const routing = _optionalChain([providerMetadata, 'optionalAccess', _263 => _263.gateway, 'optionalAccess', _264 => _264.routing]);
14251
+ const routing = _optionalChain([providerMetadata, 'optionalAccess', _279 => _279.gateway, 'optionalAccess', _280 => _280.routing]);
14163
14252
  if (routing) {
14164
14253
  return {
14165
14254
  provider: routing.resolvedProvider || routing.finalProvider,
@@ -14174,8 +14263,8 @@ function extractCostFromResult(result) {
14174
14263
  let totalCost = 0;
14175
14264
  let foundCost = false;
14176
14265
  for (const step of steps) {
14177
- const gateway2 = _optionalChain([step, 'optionalAccess', _265 => _265.providerMetadata, 'optionalAccess', _266 => _266.gateway]);
14178
- const stepCost = parseGatewayCost(_optionalChain([gateway2, 'optionalAccess', _267 => _267.cost])) || parseGatewayCost(_optionalChain([gateway2, 'optionalAccess', _268 => _268.marketCost]));
14266
+ const gateway2 = _optionalChain([step, 'optionalAccess', _281 => _281.providerMetadata, 'optionalAccess', _282 => _282.gateway]);
14267
+ const stepCost = parseGatewayCost(_optionalChain([gateway2, 'optionalAccess', _283 => _283.cost])) || parseGatewayCost(_optionalChain([gateway2, 'optionalAccess', _284 => _284.marketCost]));
14179
14268
  if (stepCost !== void 0 && stepCost > 0) {
14180
14269
  totalCost += stepCost;
14181
14270
  foundCost = true;
@@ -14189,8 +14278,8 @@ function extractCostFromResult(result) {
14189
14278
  result,
14190
14279
  "providerMetadata"
14191
14280
  );
14192
- const gateway = _optionalChain([providerMetadata, 'optionalAccess', _269 => _269.gateway]);
14193
- const directCost = parseGatewayCost(_optionalChain([gateway, 'optionalAccess', _270 => _270.cost])) || parseGatewayCost(_optionalChain([gateway, 'optionalAccess', _271 => _271.marketCost]));
14281
+ const gateway = _optionalChain([providerMetadata, 'optionalAccess', _285 => _285.gateway]);
14282
+ const directCost = parseGatewayCost(_optionalChain([gateway, 'optionalAccess', _286 => _286.cost])) || parseGatewayCost(_optionalChain([gateway, 'optionalAccess', _287 => _287.marketCost]));
14194
14283
  if (directCost !== void 0 && directCost > 0) {
14195
14284
  return directCost;
14196
14285
  }
@@ -14366,7 +14455,7 @@ function setClaudeLocalToolParentResolver(resolver) {
14366
14455
  context.resolveLocalToolParent = resolver;
14367
14456
  }
14368
14457
  function getClaudeLocalToolParentResolver() {
14369
- return _nullishCoalesce(_optionalChain([localToolContextStore, 'access', _272 => _272.getStore, 'call', _273 => _273(), 'optionalAccess', _274 => _274.resolveLocalToolParent]), () => ( fallbackLocalToolParentResolver));
14458
+ return _nullishCoalesce(_optionalChain([localToolContextStore, 'access', _288 => _288.getStore, 'call', _289 => _289(), 'optionalAccess', _290 => _290.resolveLocalToolParent]), () => ( fallbackLocalToolParentResolver));
14370
14459
  }
14371
14460
  function isAsyncIterable3(value) {
14372
14461
  return value !== null && typeof value === "object" && Symbol.asyncIterator in value && typeof value[Symbol.asyncIterator] === "function";
@@ -14660,10 +14749,10 @@ function upsertSubAgentDetails(detailsByToolUseId, toolUseId, update) {
14660
14749
  return merged;
14661
14750
  }
14662
14751
  function formatSubAgentSpanName(details) {
14663
- if (_optionalChain([details, 'optionalAccess', _275 => _275.description])) {
14752
+ if (_optionalChain([details, 'optionalAccess', _291 => _291.description])) {
14664
14753
  return `Agent: ${details.description}`;
14665
14754
  }
14666
- if (_optionalChain([details, 'optionalAccess', _276 => _276.agentType])) {
14755
+ if (_optionalChain([details, 'optionalAccess', _292 => _292.agentType])) {
14667
14756
  return `Agent: ${details.agentType}`;
14668
14757
  }
14669
14758
  return "Agent: sub-agent";
@@ -14718,7 +14807,7 @@ function extractUsageFromMessage(message) {
14718
14807
  const metrics = {};
14719
14808
  let usage;
14720
14809
  if (message.type === "assistant") {
14721
- usage = _optionalChain([message, 'access', _277 => _277.message, 'optionalAccess', _278 => _278.usage]);
14810
+ usage = _optionalChain([message, 'access', _293 => _293.message, 'optionalAccess', _294 => _294.usage]);
14722
14811
  } else if (message.type === "result") {
14723
14812
  usage = message.usage;
14724
14813
  }
@@ -14752,8 +14841,8 @@ function buildLLMInput(prompt, conversationHistory, capturedPromptMessages) {
14752
14841
  promptMessages.push({ content: prompt, role: "user" });
14753
14842
  } else if (capturedPromptMessages && capturedPromptMessages.length > 0) {
14754
14843
  for (const msg of capturedPromptMessages) {
14755
- const role = _optionalChain([msg, 'access', _279 => _279.message, 'optionalAccess', _280 => _280.role]);
14756
- const content = _optionalChain([msg, 'access', _281 => _281.message, 'optionalAccess', _282 => _282.content]);
14844
+ const role = _optionalChain([msg, 'access', _295 => _295.message, 'optionalAccess', _296 => _296.role]);
14845
+ const content = _optionalChain([msg, 'access', _297 => _297.message, 'optionalAccess', _298 => _298.content]);
14757
14846
  if (role && content !== void 0) {
14758
14847
  promptMessages.push({ content, role });
14759
14848
  }
@@ -14770,7 +14859,7 @@ async function createLLMSpanForMessages(messages, prompt, conversationHistory, o
14770
14859
  return void 0;
14771
14860
  }
14772
14861
  const lastMessage = messages[messages.length - 1];
14773
- if (lastMessage.type !== "assistant" || !_optionalChain([lastMessage, 'access', _283 => _283.message, 'optionalAccess', _284 => _284.usage])) {
14862
+ if (lastMessage.type !== "assistant" || !_optionalChain([lastMessage, 'access', _299 => _299.message, 'optionalAccess', _300 => _300.usage])) {
14774
14863
  return void 0;
14775
14864
  }
14776
14865
  const model = lastMessage.message.model || options.model;
@@ -14781,7 +14870,7 @@ async function createLLMSpanForMessages(messages, prompt, conversationHistory, o
14781
14870
  capturedPromptMessages
14782
14871
  );
14783
14872
  const outputs = messages.map(
14784
- (m) => _optionalChain([m, 'access', _285 => _285.message, 'optionalAccess', _286 => _286.content]) && _optionalChain([m, 'access', _287 => _287.message, 'optionalAccess', _288 => _288.role]) ? { content: m.message.content, role: m.message.role } : void 0
14873
+ (m) => _optionalChain([m, 'access', _301 => _301.message, 'optionalAccess', _302 => _302.content]) && _optionalChain([m, 'access', _303 => _303.message, 'optionalAccess', _304 => _304.role]) ? { content: m.message.content, role: m.message.role } : void 0
14785
14874
  ).filter(
14786
14875
  (c) => c !== void 0
14787
14876
  );
@@ -14801,7 +14890,7 @@ async function createLLMSpanForMessages(messages, prompt, conversationHistory, o
14801
14890
  });
14802
14891
  const spanExport = await span.export();
14803
14892
  await span.end();
14804
- const finalMessage = _optionalChain([lastMessage, 'access', _289 => _289.message, 'optionalAccess', _290 => _290.content]) && _optionalChain([lastMessage, 'access', _291 => _291.message, 'optionalAccess', _292 => _292.role]) ? { content: lastMessage.message.content, role: lastMessage.message.role } : void 0;
14893
+ const finalMessage = _optionalChain([lastMessage, 'access', _305 => _305.message, 'optionalAccess', _306 => _306.content]) && _optionalChain([lastMessage, 'access', _307 => _307.message, 'optionalAccess', _308 => _308.role]) ? { content: lastMessage.message.content, role: lastMessage.message.role } : void 0;
14805
14894
  return {
14806
14895
  finalMessage,
14807
14896
  spanExport
@@ -14938,18 +15027,18 @@ function createToolTracingHooks(resolveParentSpan, activeToolSpans, mcpServers,
14938
15027
  subAgentDetailsByToolUseId.get(toolUseID)
14939
15028
  )
14940
15029
  };
14941
- if (_optionalChain([response, 'optionalAccess', _293 => _293.status])) {
15030
+ if (_optionalChain([response, 'optionalAccess', _309 => _309.status])) {
14942
15031
  metadata["claude_agent_sdk.status"] = response.status;
14943
15032
  }
14944
- if (_optionalChain([response, 'optionalAccess', _294 => _294.totalDurationMs])) {
15033
+ if (_optionalChain([response, 'optionalAccess', _310 => _310.totalDurationMs])) {
14945
15034
  metadata["claude_agent_sdk.duration_ms"] = response.totalDurationMs;
14946
15035
  }
14947
- if (_optionalChain([response, 'optionalAccess', _295 => _295.totalToolUseCount]) !== void 0) {
15036
+ if (_optionalChain([response, 'optionalAccess', _311 => _311.totalToolUseCount]) !== void 0) {
14948
15037
  metadata["claude_agent_sdk.tool_use_count"] = response.totalToolUseCount;
14949
15038
  }
14950
15039
  subAgentSpan.log({
14951
15040
  metadata,
14952
- output: _optionalChain([response, 'optionalAccess', _296 => _296.content])
15041
+ output: _optionalChain([response, 'optionalAccess', _312 => _312.content])
14953
15042
  });
14954
15043
  } finally {
14955
15044
  subAgentSpan.end();
@@ -15161,7 +15250,7 @@ async function finalizeCurrentMessageGroup(state) {
15161
15250
  if (state.currentMessages.length === 0) {
15162
15251
  return;
15163
15252
  }
15164
- const parentToolUseId = _nullishCoalesce(_optionalChain([state, 'access', _297 => _297.currentMessages, 'access', _298 => _298[0], 'optionalAccess', _299 => _299.parent_tool_use_id]), () => ( null));
15253
+ const parentToolUseId = _nullishCoalesce(_optionalChain([state, 'access', _313 => _313.currentMessages, 'access', _314 => _314[0], 'optionalAccess', _315 => _315.parent_tool_use_id]), () => ( null));
15165
15254
  const parentKey = llmParentKey(parentToolUseId);
15166
15255
  let parentSpan = await state.span.export();
15167
15256
  if (parentToolUseId) {
@@ -15196,14 +15285,14 @@ async function finalizeCurrentMessageGroup(state) {
15196
15285
  }
15197
15286
  state.activeLlmSpansByParentToolUse.delete(parentKey);
15198
15287
  const lastMessage = state.currentMessages[state.currentMessages.length - 1];
15199
- if (_optionalChain([lastMessage, 'optionalAccess', _300 => _300.message, 'optionalAccess', _301 => _301.usage])) {
15288
+ if (_optionalChain([lastMessage, 'optionalAccess', _316 => _316.message, 'optionalAccess', _317 => _317.usage])) {
15200
15289
  state.accumulatedOutputTokens += getNumberProperty(lastMessage.message.usage, "output_tokens") || 0;
15201
15290
  }
15202
15291
  state.currentMessages.length = 0;
15203
15292
  }
15204
15293
  function maybeTrackToolUseContext(state, message) {
15205
15294
  seedTaskToolUseIdMapping(state.taskIdToToolUseId, message);
15206
- if (message.type !== "assistant" || !Array.isArray(_optionalChain([message, 'access', _302 => _302.message, 'optionalAccess', _303 => _303.content]))) {
15295
+ if (message.type !== "assistant" || !Array.isArray(_optionalChain([message, 'access', _318 => _318.message, 'optionalAccess', _319 => _319.content]))) {
15207
15296
  return;
15208
15297
  }
15209
15298
  const parentToolUseId = _nullishCoalesce(message.parent_tool_use_id, () => ( null));
@@ -15386,13 +15475,13 @@ async function handleStreamMessage(state, message) {
15386
15475
  return;
15387
15476
  }
15388
15477
  await maybeStartSubAgentSpan(state, message);
15389
- const messageId = _optionalChain([message, 'access', _304 => _304.message, 'optionalAccess', _305 => _305.id]);
15478
+ const messageId = _optionalChain([message, 'access', _320 => _320.message, 'optionalAccess', _321 => _321.id]);
15390
15479
  if (messageId && messageId !== state.currentMessageId) {
15391
15480
  await finalizeCurrentMessageGroup(state);
15392
15481
  state.currentMessageId = messageId;
15393
15482
  state.currentMessageStartTime = getCurrentUnixTimestamp();
15394
15483
  }
15395
- if (message.type === "assistant" && _optionalChain([message, 'access', _306 => _306.message, 'optionalAccess', _307 => _307.usage])) {
15484
+ if (message.type === "assistant" && _optionalChain([message, 'access', _322 => _322.message, 'optionalAccess', _323 => _323.usage])) {
15396
15485
  const parentToolUseId = _nullishCoalesce(message.parent_tool_use_id, () => ( null));
15397
15486
  await ensureActiveLlmSpanForParentToolUse(
15398
15487
  state.span,
@@ -15411,7 +15500,7 @@ async function handleStreamMessage(state, message) {
15411
15500
  const finalUsageMetrics = extractUsageFromMessage(message);
15412
15501
  if (state.currentMessages.length > 0 && finalUsageMetrics.completion_tokens !== void 0) {
15413
15502
  const lastMessage = state.currentMessages[state.currentMessages.length - 1];
15414
- if (_optionalChain([lastMessage, 'optionalAccess', _308 => _308.message, 'optionalAccess', _309 => _309.usage])) {
15503
+ if (_optionalChain([lastMessage, 'optionalAccess', _324 => _324.message, 'optionalAccess', _325 => _325.usage])) {
15415
15504
  const adjustedTokens = finalUsageMetrics.completion_tokens - state.accumulatedOutputTokens;
15416
15505
  if (adjustedTokens >= 0) {
15417
15506
  lastMessage.message.usage.output_tokens = adjustedTokens;
@@ -15516,7 +15605,7 @@ var ClaudeAgentSDKPlugin = class extends BasePlugin {
15516
15605
  yield message;
15517
15606
  }
15518
15607
  } finally {
15519
- _optionalChain([resolvePromptDone, 'optionalCall', _310 => _310()]);
15608
+ _optionalChain([resolvePromptDone, 'optionalCall', _326 => _326()]);
15520
15609
  }
15521
15610
  })();
15522
15611
  }
@@ -15551,10 +15640,10 @@ var ClaudeAgentSDKPlugin = class extends BasePlugin {
15551
15640
  const skipLocalToolHooks = options[CLAUDE_AGENT_SDK_SKIP_LOCAL_TOOL_HOOKS_OPTION] === true || hasLocalToolHandlers;
15552
15641
  const resolveToolUseParentSpan = async (toolUseID, context) => {
15553
15642
  const trackedParentToolUseId = toolUseToParent.get(toolUseID);
15554
- const parentToolUseId = _nullishCoalesce(trackedParentToolUseId, () => ( (_optionalChain([context, 'optionalAccess', _311 => _311.agentId]) ? _nullishCoalesce(taskIdToToolUseId.get(context.agentId), () => ( null)) : null)));
15643
+ const parentToolUseId = _nullishCoalesce(trackedParentToolUseId, () => ( (_optionalChain([context, 'optionalAccess', _327 => _327.agentId]) ? _nullishCoalesce(taskIdToToolUseId.get(context.agentId), () => ( null)) : null)));
15555
15644
  const parentKey = llmParentKey(parentToolUseId);
15556
15645
  const activeLlmSpan = activeLlmSpansByParentToolUse.get(parentKey);
15557
- if (_optionalChain([context, 'optionalAccess', _312 => _312.preferTaskSiblingParent])) {
15646
+ if (_optionalChain([context, 'optionalAccess', _328 => _328.preferTaskSiblingParent])) {
15558
15647
  if (!activeLlmSpan) {
15559
15648
  await ensureActiveLlmSpanForParentToolUse(
15560
15649
  span,
@@ -15799,7 +15888,7 @@ var CursorSDKPlugin = (_class18 = class extends BasePlugin {constructor(...args3
15799
15888
  ...extractRunResultMetadata(event.result)
15800
15889
  },
15801
15890
  metrics: buildDurationMetrics2(state.startTime),
15802
- output: _nullishCoalesce(_optionalChain([event, 'access', _313 => _313.result, 'optionalAccess', _314 => _314.result]), () => ( event.result))
15891
+ output: _nullishCoalesce(_optionalChain([event, 'access', _329 => _329.result, 'optionalAccess', _330 => _330.result]), () => ( event.result))
15803
15892
  });
15804
15893
  } finally {
15805
15894
  state.span.end();
@@ -16120,9 +16209,9 @@ async function handleToolUpdate(state, update) {
16120
16209
  toolCall
16121
16210
  })));
16122
16211
  finishToolSpan(toolState, {
16123
- error: _optionalChain([toolCall, 'optionalAccess', _315 => _315.status]) === "error" ? stringifyUnknown(result) : void 0,
16212
+ error: _optionalChain([toolCall, 'optionalAccess', _331 => _331.status]) === "error" ? stringifyUnknown(result) : void 0,
16124
16213
  metadata: {
16125
- "cursor_sdk.tool.status": _nullishCoalesce(_optionalChain([toolCall, 'optionalAccess', _316 => _316.status]), () => ( "completed"))
16214
+ "cursor_sdk.tool.status": _nullishCoalesce(_optionalChain([toolCall, 'optionalAccess', _332 => _332.status]), () => ( "completed"))
16126
16215
  },
16127
16216
  output: result
16128
16217
  });
@@ -16143,10 +16232,10 @@ async function handleStreamMessage2(state, message) {
16143
16232
  }
16144
16233
  if (message.type === "assistant") {
16145
16234
  const assistantMessage = message;
16146
- for (const block of _nullishCoalesce(_optionalChain([assistantMessage, 'access', _317 => _317.message, 'optionalAccess', _318 => _318.content]), () => ( []))) {
16147
- if (_optionalChain([block, 'optionalAccess', _319 => _319.type]) === "text" && typeof block.text === "string") {
16235
+ for (const block of _nullishCoalesce(_optionalChain([assistantMessage, 'access', _333 => _333.message, 'optionalAccess', _334 => _334.content]), () => ( []))) {
16236
+ if (_optionalChain([block, 'optionalAccess', _335 => _335.type]) === "text" && typeof block.text === "string") {
16148
16237
  state.streamText.push(block.text);
16149
- } else if (_optionalChain([block, 'optionalAccess', _320 => _320.type]) === "tool_use" && block.id) {
16238
+ } else if (_optionalChain([block, 'optionalAccess', _336 => _336.type]) === "tool_use" && block.id) {
16150
16239
  state.activeToolSpans.set(
16151
16240
  block.id,
16152
16241
  await startToolSpan(state, {
@@ -16215,29 +16304,29 @@ async function handleConversation(state, turns) {
16215
16304
  state.conversationOutput = turns;
16216
16305
  for (const turn of turns) {
16217
16306
  if (turn.type === "agentConversationTurn") {
16218
- for (const step of _nullishCoalesce(_optionalChain([turn, 'access', _321 => _321.turn, 'optionalAccess', _322 => _322.steps]), () => ( []))) {
16307
+ for (const step of _nullishCoalesce(_optionalChain([turn, 'access', _337 => _337.turn, 'optionalAccess', _338 => _338.steps]), () => ( []))) {
16219
16308
  await handleConversationStep(state, step);
16220
16309
  }
16221
16310
  } else if (turn.type === "shellConversationTurn") {
16222
- const command = _optionalChain([turn, 'access', _323 => _323.turn, 'optionalAccess', _324 => _324.shellCommand, 'optionalAccess', _325 => _325.command]);
16311
+ const command = _optionalChain([turn, 'access', _339 => _339.turn, 'optionalAccess', _340 => _340.shellCommand, 'optionalAccess', _341 => _341.command]);
16223
16312
  if (command) {
16224
16313
  const callId = `shell:${state.activeToolSpans.size}:${command}`;
16225
16314
  const toolState = await startToolSpan(state, {
16226
- args: _optionalChain([turn, 'access', _326 => _326.turn, 'optionalAccess', _327 => _327.shellCommand]),
16315
+ args: _optionalChain([turn, 'access', _342 => _342.turn, 'optionalAccess', _343 => _343.shellCommand]),
16227
16316
  callId,
16228
16317
  name: "shell",
16229
16318
  status: "completed"
16230
16319
  });
16231
16320
  finishToolSpan(toolState, {
16232
16321
  metadata: { "cursor_sdk.tool.status": "completed" },
16233
- output: _optionalChain([turn, 'access', _328 => _328.turn, 'optionalAccess', _329 => _329.shellOutput])
16322
+ output: _optionalChain([turn, 'access', _344 => _344.turn, 'optionalAccess', _345 => _345.shellOutput])
16234
16323
  });
16235
16324
  }
16236
16325
  }
16237
16326
  }
16238
16327
  }
16239
16328
  async function handleConversationStep(state, step) {
16240
- if (step.type === "assistantMessage" && typeof _optionalChain([step, 'access', _330 => _330.message, 'optionalAccess', _331 => _331.text]) === "string") {
16329
+ if (step.type === "assistantMessage" && typeof _optionalChain([step, 'access', _346 => _346.message, 'optionalAccess', _347 => _347.text]) === "string") {
16241
16330
  state.conversationText.push(step.message.text);
16242
16331
  return;
16243
16332
  }
@@ -16245,18 +16334,18 @@ async function handleConversationStep(state, step) {
16245
16334
  return;
16246
16335
  }
16247
16336
  const toolCall = step.message;
16248
- const callId = typeof _optionalChain([toolCall, 'optionalAccess', _332 => _332.callId]) === "string" ? toolCall.callId : `conversation-tool:${state.activeToolSpans.size}`;
16337
+ const callId = typeof _optionalChain([toolCall, 'optionalAccess', _348 => _348.callId]) === "string" ? toolCall.callId : `conversation-tool:${state.activeToolSpans.size}`;
16249
16338
  const toolState = await startToolSpan(state, {
16250
16339
  args: extractToolArgs(toolCall),
16251
16340
  callId,
16252
16341
  name: extractToolName(toolCall),
16253
- status: _optionalChain([toolCall, 'optionalAccess', _333 => _333.status]),
16342
+ status: _optionalChain([toolCall, 'optionalAccess', _349 => _349.status]),
16254
16343
  toolCall
16255
16344
  });
16256
16345
  finishToolSpan(toolState, {
16257
- error: _optionalChain([toolCall, 'optionalAccess', _334 => _334.status]) === "error" ? stringifyUnknown(toolCall.result) : void 0,
16346
+ error: _optionalChain([toolCall, 'optionalAccess', _350 => _350.status]) === "error" ? stringifyUnknown(toolCall.result) : void 0,
16258
16347
  metadata: {
16259
- "cursor_sdk.tool.status": _nullishCoalesce(_optionalChain([toolCall, 'optionalAccess', _335 => _335.status]), () => ( "completed"))
16348
+ "cursor_sdk.tool.status": _nullishCoalesce(_optionalChain([toolCall, 'optionalAccess', _351 => _351.status]), () => ( "completed"))
16260
16349
  },
16261
16350
  output: extractToolResult(toolCall)
16262
16351
  });
@@ -16273,7 +16362,7 @@ function handleStepUpdate(state, step) {
16273
16362
  state.metadata["cursor_sdk.step_types"] = [step.type];
16274
16363
  }
16275
16364
  }
16276
- if (step.type === "assistantMessage" && typeof _optionalChain([step, 'access', _336 => _336.message, 'optionalAccess', _337 => _337.text]) === "string") {
16365
+ if (step.type === "assistantMessage" && typeof _optionalChain([step, 'access', _352 => _352.message, 'optionalAccess', _353 => _353.text]) === "string") {
16277
16366
  state.stepText.push(step.message.text);
16278
16367
  }
16279
16368
  }
@@ -16284,10 +16373,10 @@ async function startToolSpan(state, args) {
16284
16373
  "gen_ai.tool.call.id": args.callId,
16285
16374
  "gen_ai.tool.name": name
16286
16375
  };
16287
- if (_optionalChain([args, 'access', _338 => _338.truncated, 'optionalAccess', _339 => _339.args]) !== void 0) {
16376
+ if (_optionalChain([args, 'access', _354 => _354.truncated, 'optionalAccess', _355 => _355.args]) !== void 0) {
16288
16377
  metadata["cursor_sdk.tool.args_truncated"] = args.truncated.args;
16289
16378
  }
16290
- if (_optionalChain([args, 'access', _340 => _340.truncated, 'optionalAccess', _341 => _341.result]) !== void 0) {
16379
+ if (_optionalChain([args, 'access', _356 => _356.truncated, 'optionalAccess', _357 => _357.result]) !== void 0) {
16291
16380
  metadata["cursor_sdk.tool.result_truncated"] = args.truncated.result;
16292
16381
  }
16293
16382
  const span = startSpan({
@@ -16344,7 +16433,7 @@ function finishToolSpan(toolState, result) {
16344
16433
  }
16345
16434
  }
16346
16435
  } finally {
16347
- _optionalChain([toolState, 'access', _342 => _342.subAgentSpan, 'optionalAccess', _343 => _343.end, 'call', _344 => _344()]);
16436
+ _optionalChain([toolState, 'access', _358 => _358.subAgentSpan, 'optionalAccess', _359 => _359.end, 'call', _360 => _360()]);
16348
16437
  toolState.span.end();
16349
16438
  }
16350
16439
  }
@@ -16355,7 +16444,7 @@ async function finalizeCursorRun(state, params = {}) {
16355
16444
  state.finalized = true;
16356
16445
  const error = params.error;
16357
16446
  const result = _nullishCoalesce(params.result, () => ( state.lastResult));
16358
- const output = _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(params.output, () => ( _optionalChain([result, 'optionalAccess', _345 => _345.result]))), () => ( _optionalChain([state, 'access', _346 => _346.run, 'optionalAccess', _347 => _347.result]))), () => ( (state.conversationText.length > 0 ? state.conversationText.join("\n") : void 0))), () => ( state.conversationOutput)), () => ( (state.streamText.length > 0 ? state.streamText.join("") : void 0))), () => ( (state.deltaText.length > 0 ? state.deltaText.join("") : void 0))), () => ( (state.stepText.length > 0 ? state.stepText.join("\n") : void 0))), () => ( (state.taskText.length > 0 ? state.taskText.join("\n") : void 0)));
16447
+ const output = _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(params.output, () => ( _optionalChain([result, 'optionalAccess', _361 => _361.result]))), () => ( _optionalChain([state, 'access', _362 => _362.run, 'optionalAccess', _363 => _363.result]))), () => ( (state.conversationText.length > 0 ? state.conversationText.join("\n") : void 0))), () => ( state.conversationOutput)), () => ( (state.streamText.length > 0 ? state.streamText.join("") : void 0))), () => ( (state.deltaText.length > 0 ? state.deltaText.join("") : void 0))), () => ( (state.stepText.length > 0 ? state.stepText.join("\n") : void 0))), () => ( (state.taskText.length > 0 ? state.taskText.join("\n") : void 0)));
16359
16448
  try {
16360
16449
  const metadata = {
16361
16450
  ...state.metadata,
@@ -16399,7 +16488,7 @@ function sanitizeUserMessage(message) {
16399
16488
  }
16400
16489
  return {
16401
16490
  ...message,
16402
- images: _optionalChain([message, 'access', _348 => _348.images, 'optionalAccess', _349 => _349.map, 'call', _350 => _350((image) => {
16491
+ images: _optionalChain([message, 'access', _364 => _364.images, 'optionalAccess', _365 => _365.map, 'call', _366 => _366((image) => {
16403
16492
  const imageRecord = image;
16404
16493
  return {
16405
16494
  ...typeof imageRecord.url === "string" ? { url: imageRecord.url } : {},
@@ -16425,9 +16514,9 @@ function extractAgentOptionsMetadata(options) {
16425
16514
  ...options.cloud ? {
16426
16515
  "cursor_sdk.runtime": "cloud",
16427
16516
  "cursor_sdk.cloud.auto_create_pr": options.cloud.autoCreatePR,
16428
- "cursor_sdk.cloud.env_type": _optionalChain([options, 'access', _351 => _351.cloud, 'access', _352 => _352.env, 'optionalAccess', _353 => _353.type]),
16429
- "cursor_sdk.cloud.env_name": _optionalChain([options, 'access', _354 => _354.cloud, 'access', _355 => _355.env, 'optionalAccess', _356 => _356.name]),
16430
- "cursor_sdk.cloud.repos": _optionalChain([options, 'access', _357 => _357.cloud, 'access', _358 => _358.repos, 'optionalAccess', _359 => _359.map, 'call', _360 => _360((repo) => repo.url), 'access', _361 => _361.filter, 'call', _362 => _362((url) => typeof url === "string")])
16517
+ "cursor_sdk.cloud.env_type": _optionalChain([options, 'access', _367 => _367.cloud, 'access', _368 => _368.env, 'optionalAccess', _369 => _369.type]),
16518
+ "cursor_sdk.cloud.env_name": _optionalChain([options, 'access', _370 => _370.cloud, 'access', _371 => _371.env, 'optionalAccess', _372 => _372.name]),
16519
+ "cursor_sdk.cloud.repos": _optionalChain([options, 'access', _373 => _373.cloud, 'access', _374 => _374.repos, 'optionalAccess', _375 => _375.map, 'call', _376 => _376((repo) => repo.url), 'access', _377 => _377.filter, 'call', _378 => _378((url) => typeof url === "string")])
16431
16520
  } : {}
16432
16521
  };
16433
16522
  }
@@ -16437,7 +16526,7 @@ function extractSendMetadata(options) {
16437
16526
  }
16438
16527
  return {
16439
16528
  ...extractModelMetadata(options.model),
16440
- ..._optionalChain([options, 'access', _363 => _363.local, 'optionalAccess', _364 => _364.force]) !== void 0 ? { "cursor_sdk.local.force": options.local.force } : {}
16529
+ ..._optionalChain([options, 'access', _379 => _379.local, 'optionalAccess', _380 => _380.force]) !== void 0 ? { "cursor_sdk.local.force": options.local.force } : {}
16441
16530
  };
16442
16531
  }
16443
16532
  function extractAgentMetadata(agent) {
@@ -16472,7 +16561,7 @@ function extractRunResultMetadata(result) {
16472
16561
  };
16473
16562
  }
16474
16563
  function extractGitMetadata(git) {
16475
- const branches = _optionalChain([git, 'optionalAccess', _365 => _365.branches]);
16564
+ const branches = _optionalChain([git, 'optionalAccess', _381 => _381.branches]);
16476
16565
  if (!branches || branches.length === 0) {
16477
16566
  return {};
16478
16567
  }
@@ -16485,7 +16574,7 @@ function extractGitMetadata(git) {
16485
16574
  };
16486
16575
  }
16487
16576
  function extractModelMetadata(model) {
16488
- if (!_optionalChain([model, 'optionalAccess', _366 => _366.id])) {
16577
+ if (!_optionalChain([model, 'optionalAccess', _382 => _382.id])) {
16489
16578
  return {};
16490
16579
  }
16491
16580
  return {
@@ -16547,7 +16636,7 @@ function formatSubAgentSpanName2(toolCall, args) {
16547
16636
  return description ? `Agent: ${description}` : "Agent: sub-agent";
16548
16637
  }
16549
16638
  function getString(obj, key) {
16550
- const value = _optionalChain([obj, 'optionalAccess', _367 => _367[key]]);
16639
+ const value = _optionalChain([obj, 'optionalAccess', _383 => _383[key]]);
16551
16640
  return typeof value === "string" ? value : void 0;
16552
16641
  }
16553
16642
  function stringifyUnknown(value) {
@@ -16710,7 +16799,7 @@ var OpenAIAgentsTraceProcessor = (_class19 = class _OpenAIAgentsTraceProcessor {
16710
16799
  }
16711
16800
  }
16712
16801
  onTraceStart(trace) {
16713
- if (!_optionalChain([trace, 'optionalAccess', _368 => _368.traceId])) {
16802
+ if (!_optionalChain([trace, 'optionalAccess', _384 => _384.traceId])) {
16714
16803
  return Promise.resolve();
16715
16804
  }
16716
16805
  if (this.traceOrder.length >= this.maxTraces) {
@@ -16746,7 +16835,7 @@ var OpenAIAgentsTraceProcessor = (_class19 = class _OpenAIAgentsTraceProcessor {
16746
16835
  return Promise.resolve();
16747
16836
  }
16748
16837
  async onTraceEnd(trace) {
16749
- const traceData = this.traceSpans.get(_optionalChain([trace, 'optionalAccess', _369 => _369.traceId]));
16838
+ const traceData = this.traceSpans.get(_optionalChain([trace, 'optionalAccess', _385 => _385.traceId]));
16750
16839
  if (!traceData) {
16751
16840
  return;
16752
16841
  }
@@ -16766,7 +16855,7 @@ var OpenAIAgentsTraceProcessor = (_class19 = class _OpenAIAgentsTraceProcessor {
16766
16855
  }
16767
16856
  }
16768
16857
  onSpanStart(span) {
16769
- if (!_optionalChain([span, 'optionalAccess', _370 => _370.spanId]) || !span.traceId) {
16858
+ if (!_optionalChain([span, 'optionalAccess', _386 => _386.spanId]) || !span.traceId) {
16770
16859
  return Promise.resolve();
16771
16860
  }
16772
16861
  const traceData = this.traceSpans.get(span.traceId);
@@ -16785,7 +16874,7 @@ var OpenAIAgentsTraceProcessor = (_class19 = class _OpenAIAgentsTraceProcessor {
16785
16874
  return Promise.resolve();
16786
16875
  }
16787
16876
  onSpanEnd(span) {
16788
- if (!_optionalChain([span, 'optionalAccess', _371 => _371.spanId]) || !span.traceId) {
16877
+ if (!_optionalChain([span, 'optionalAccess', _387 => _387.spanId]) || !span.traceId) {
16789
16878
  return Promise.resolve();
16790
16879
  }
16791
16880
  const traceData = this.traceSpans.get(span.traceId);
@@ -17155,7 +17244,7 @@ var GoogleGenAIPlugin = class extends BasePlugin {
17155
17244
  };
17156
17245
  tracingChannel2.subscribe(handlers);
17157
17246
  this.unsubscribers.push(() => {
17158
- _optionalChain([unbindCurrentSpanStore, 'optionalCall', _372 => _372()]);
17247
+ _optionalChain([unbindCurrentSpanStore, 'optionalCall', _388 => _388()]);
17159
17248
  tracingChannel2.unsubscribe(handlers);
17160
17249
  });
17161
17250
  }
@@ -17252,7 +17341,7 @@ var GoogleGenAIPlugin = class extends BasePlugin {
17252
17341
  };
17253
17342
  tracingChannel2.subscribe(handlers);
17254
17343
  this.unsubscribers.push(() => {
17255
- _optionalChain([unbindCurrentSpanStore, 'optionalCall', _373 => _373()]);
17344
+ _optionalChain([unbindCurrentSpanStore, 'optionalCall', _389 => _389()]);
17256
17345
  tracingChannel2.unsubscribe(handlers);
17257
17346
  });
17258
17347
  }
@@ -17268,10 +17357,10 @@ function ensureSpanState(states, event, create) {
17268
17357
  }
17269
17358
  function bindCurrentSpanStoreToStart2(tracingChannel2, states, create) {
17270
17359
  const state = _internalGetGlobalState();
17271
- const contextManager = _optionalChain([state, 'optionalAccess', _374 => _374.contextManager]);
17360
+ const contextManager = _optionalChain([state, 'optionalAccess', _390 => _390.contextManager]);
17272
17361
  const startChannel = tracingChannel2.start;
17273
17362
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
17274
- if (!_optionalChain([startChannel, 'optionalAccess', _375 => _375.bindStore]) || !currentSpanStore) {
17363
+ if (!_optionalChain([startChannel, 'optionalAccess', _391 => _391.bindStore]) || !currentSpanStore) {
17275
17364
  return void 0;
17276
17365
  }
17277
17366
  startChannel.bindStore(currentSpanStore, (event) => {
@@ -17283,7 +17372,7 @@ function bindCurrentSpanStoreToStart2(tracingChannel2, states, create) {
17283
17372
  return contextManager.wrapSpanForStore(span);
17284
17373
  });
17285
17374
  return () => {
17286
- _optionalChain([startChannel, 'access', _376 => _376.unbindStore, 'optionalCall', _377 => _377(currentSpanStore)]);
17375
+ _optionalChain([startChannel, 'access', _392 => _392.unbindStore, 'optionalCall', _393 => _393(currentSpanStore)]);
17287
17376
  };
17288
17377
  }
17289
17378
  function logErrorAndEndSpan(states, event) {
@@ -17518,7 +17607,7 @@ function serializePart(part) {
17518
17607
  }
17519
17608
  function serializeGenerateContentTools(params) {
17520
17609
  const config = params.config ? tryToDict(params.config) : null;
17521
- const tools = _optionalChain([config, 'optionalAccess', _378 => _378.tools]);
17610
+ const tools = _optionalChain([config, 'optionalAccess', _394 => _394.tools]);
17522
17611
  if (!Array.isArray(tools)) {
17523
17612
  return null;
17524
17613
  }
@@ -17577,7 +17666,7 @@ function extractGenerateContentMetrics(response, startTime) {
17577
17666
  metrics.end = end;
17578
17667
  metrics.duration = end - startTime;
17579
17668
  }
17580
- if (_optionalChain([response, 'optionalAccess', _379 => _379.usageMetadata])) {
17669
+ if (_optionalChain([response, 'optionalAccess', _395 => _395.usageMetadata])) {
17581
17670
  populateUsageMetrics(metrics, response.usageMetadata);
17582
17671
  }
17583
17672
  return metrics;
@@ -17590,7 +17679,7 @@ function extractEmbedContentMetrics(response, startTime) {
17590
17679
  metrics.end = end;
17591
17680
  metrics.duration = end - startTime;
17592
17681
  }
17593
- if (_optionalChain([response, 'optionalAccess', _380 => _380.usageMetadata])) {
17682
+ if (_optionalChain([response, 'optionalAccess', _396 => _396.usageMetadata])) {
17594
17683
  populateUsageMetrics(metrics, response.usageMetadata);
17595
17684
  }
17596
17685
  const embeddingTokenCount = extractEmbedPromptTokenCount(response);
@@ -17604,11 +17693,11 @@ function extractEmbedPromptTokenCount(response) {
17604
17693
  if (!response) {
17605
17694
  return void 0;
17606
17695
  }
17607
- const usagePromptTokens = _optionalChain([response, 'access', _381 => _381.usageMetadata, 'optionalAccess', _382 => _382.promptTokenCount]);
17696
+ const usagePromptTokens = _optionalChain([response, 'access', _397 => _397.usageMetadata, 'optionalAccess', _398 => _398.promptTokenCount]);
17608
17697
  if (typeof usagePromptTokens === "number" && Number.isFinite(usagePromptTokens)) {
17609
17698
  return usagePromptTokens;
17610
17699
  }
17611
- const usageTotalTokens = _optionalChain([response, 'access', _383 => _383.usageMetadata, 'optionalAccess', _384 => _384.totalTokenCount]);
17700
+ const usageTotalTokens = _optionalChain([response, 'access', _399 => _399.usageMetadata, 'optionalAccess', _400 => _400.totalTokenCount]);
17612
17701
  if (typeof usageTotalTokens === "number" && Number.isFinite(usageTotalTokens)) {
17613
17702
  return usageTotalTokens;
17614
17703
  }
@@ -17619,8 +17708,8 @@ function extractEmbedPromptTokenCount(response) {
17619
17708
  let total = 0;
17620
17709
  let sawAny = false;
17621
17710
  for (const embedding of embeddings) {
17622
- const embeddingStats = tryToDict(_optionalChain([tryToDict, 'call', _385 => _385(embedding), 'optionalAccess', _386 => _386.statistics]));
17623
- const tokenCount = _optionalChain([embeddingStats, 'optionalAccess', _387 => _387.tokenCount]);
17711
+ const embeddingStats = tryToDict(_optionalChain([tryToDict, 'call', _401 => _401(embedding), 'optionalAccess', _402 => _402.statistics]));
17712
+ const tokenCount = _optionalChain([embeddingStats, 'optionalAccess', _403 => _403.tokenCount]);
17624
17713
  if (typeof tokenCount === "number" && Number.isFinite(tokenCount)) {
17625
17714
  total += tokenCount;
17626
17715
  sawAny = true;
@@ -17636,7 +17725,7 @@ function summarizeEmbedContentOutput(response) {
17636
17725
  if (embeddings.length === 0) {
17637
17726
  return void 0;
17638
17727
  }
17639
- const firstValues = _optionalChain([embeddings, 'access', _388 => _388[0], 'optionalAccess', _389 => _389.values]);
17728
+ const firstValues = _optionalChain([embeddings, 'access', _404 => _404[0], 'optionalAccess', _405 => _405.values]);
17640
17729
  if (!Array.isArray(firstValues)) {
17641
17730
  return void 0;
17642
17731
  }
@@ -17691,7 +17780,7 @@ function aggregateGenerateContentChunks(chunks, startTime, firstTokenTime) {
17691
17780
  }
17692
17781
  if (chunk.candidates && Array.isArray(chunk.candidates)) {
17693
17782
  for (const candidate of chunk.candidates) {
17694
- if (_optionalChain([candidate, 'access', _390 => _390.content, 'optionalAccess', _391 => _391.parts])) {
17783
+ if (_optionalChain([candidate, 'access', _406 => _406.content, 'optionalAccess', _407 => _407.parts])) {
17695
17784
  for (const part of candidate.content.parts) {
17696
17785
  if (part.text !== void 0) {
17697
17786
  if (part.thought) {
@@ -17722,7 +17811,7 @@ function aggregateGenerateContentChunks(chunks, startTime, firstTokenTime) {
17722
17811
  parts.push({ text });
17723
17812
  }
17724
17813
  parts.push(...otherParts);
17725
- if (parts.length > 0 && _optionalChain([lastResponse, 'optionalAccess', _392 => _392.candidates])) {
17814
+ if (parts.length > 0 && _optionalChain([lastResponse, 'optionalAccess', _408 => _408.candidates])) {
17726
17815
  const candidates = [];
17727
17816
  for (const candidate of lastResponse.candidates) {
17728
17817
  const candidateDict = {
@@ -17779,7 +17868,7 @@ function extractResponseMetadata(response) {
17779
17868
  if (Array.isArray(responseDict.candidates)) {
17780
17869
  for (const candidate of responseDict.candidates) {
17781
17870
  const candidateDict = tryToDict(candidate);
17782
- if (_optionalChain([candidateDict, 'optionalAccess', _393 => _393.groundingMetadata]) !== void 0) {
17871
+ if (_optionalChain([candidateDict, 'optionalAccess', _409 => _409.groundingMetadata]) !== void 0) {
17783
17872
  candidateGroundingMetadata.push(candidateDict.groundingMetadata);
17784
17873
  }
17785
17874
  }
@@ -17860,9 +17949,9 @@ var HuggingFacePlugin = class extends BasePlugin {
17860
17949
  name: "huggingface.chat_completion",
17861
17950
  type: "llm" /* LLM */,
17862
17951
  extractInput: extractChatInputWithMetadata,
17863
- extractOutput: (result) => _optionalChain([result, 'optionalAccess', _394 => _394.choices]),
17952
+ extractOutput: (result) => _optionalChain([result, 'optionalAccess', _410 => _410.choices]),
17864
17953
  extractMetadata: (result) => extractResponseMetadata2(result),
17865
- extractMetrics: (result) => parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _395 => _395.usage]))
17954
+ extractMetrics: (result) => parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _411 => _411.usage]))
17866
17955
  }),
17867
17956
  traceSyncStreamChannel(huggingFaceChannels.chatCompletionStream, {
17868
17957
  name: "huggingface.chat_completion_stream",
@@ -17880,7 +17969,7 @@ var HuggingFacePlugin = class extends BasePlugin {
17880
17969
  extractInput: extractTextGenerationInputWithMetadata,
17881
17970
  extractOutput: (result) => isObject(result) ? { generated_text: result.generated_text } : result,
17882
17971
  extractMetadata: extractTextGenerationMetadata,
17883
- extractMetrics: (result) => extractTextGenerationMetrics(_nullishCoalesce(_optionalChain([result, 'optionalAccess', _396 => _396.details]), () => ( null)))
17972
+ extractMetrics: (result) => extractTextGenerationMetrics(_nullishCoalesce(_optionalChain([result, 'optionalAccess', _412 => _412.details]), () => ( null)))
17884
17973
  }),
17885
17974
  traceSyncStreamChannel(huggingFaceChannels.textGenerationStream, {
17886
17975
  name: "huggingface.text_generation_stream",
@@ -17999,7 +18088,7 @@ function extractTextGenerationMetrics(details) {
17999
18088
  return metrics;
18000
18089
  }
18001
18090
  function extractTextGenerationMetadata(result) {
18002
- if (!isObject(_optionalChain([result, 'optionalAccess', _397 => _397.details]))) {
18091
+ if (!isObject(_optionalChain([result, 'optionalAccess', _413 => _413.details]))) {
18003
18092
  return void 0;
18004
18093
  }
18005
18094
  return typeof result.details.finish_reason === "string" ? {
@@ -18045,7 +18134,7 @@ function patchChatCompletionStream(args) {
18045
18134
  const lastChunk = chunks.at(-1);
18046
18135
  const responseMetadata = extractResponseMetadata2(lastChunk);
18047
18136
  const metrics = {
18048
- ...parseMetricsFromUsage(_optionalChain([lastChunk, 'optionalAccess', _398 => _398.usage])),
18137
+ ...parseMetricsFromUsage(_optionalChain([lastChunk, 'optionalAccess', _414 => _414.usage])),
18049
18138
  ...firstChunkTime !== void 0 ? { time_to_first_token: firstChunkTime - startTime } : {}
18050
18139
  };
18051
18140
  span.log({
@@ -18083,8 +18172,8 @@ function patchTextGenerationStream(args) {
18083
18172
  output: aggregateTextGenerationStreamChunks(chunks),
18084
18173
  ...streamMetadata ? { metadata: streamMetadata } : {},
18085
18174
  metrics: {
18086
- ...extractTextGenerationMetrics(_nullishCoalesce(_optionalChain([lastChunk, 'optionalAccess', _399 => _399.details]), () => ( null))),
18087
- ...parseMetricsFromUsage(_optionalChain([lastChunk, 'optionalAccess', _400 => _400.usage])),
18175
+ ...extractTextGenerationMetrics(_nullishCoalesce(_optionalChain([lastChunk, 'optionalAccess', _415 => _415.details]), () => ( null))),
18176
+ ...parseMetricsFromUsage(_optionalChain([lastChunk, 'optionalAccess', _416 => _416.usage])),
18088
18177
  ...firstChunkTime !== void 0 ? { time_to_first_token: firstChunkTime - startTime } : {}
18089
18178
  }
18090
18179
  });
@@ -18113,14 +18202,14 @@ function aggregateChatCompletionChunks2(chunks) {
18113
18202
  }));
18114
18203
  const delta = isObject(choice.delta) ? choice.delta : void 0;
18115
18204
  const message = isObject(choice.message) ? choice.message : void 0;
18116
- if (typeof _optionalChain([delta, 'optionalAccess', _401 => _401.content]) === "string") {
18205
+ if (typeof _optionalChain([delta, 'optionalAccess', _417 => _417.content]) === "string") {
18117
18206
  existing.content += delta.content;
18118
- } else if (typeof _optionalChain([message, 'optionalAccess', _402 => _402.content]) === "string") {
18207
+ } else if (typeof _optionalChain([message, 'optionalAccess', _418 => _418.content]) === "string") {
18119
18208
  existing.content = message.content;
18120
18209
  }
18121
- if (typeof _optionalChain([delta, 'optionalAccess', _403 => _403.role]) === "string") {
18210
+ if (typeof _optionalChain([delta, 'optionalAccess', _419 => _419.role]) === "string") {
18122
18211
  existing.role = delta.role;
18123
- } else if (typeof _optionalChain([message, 'optionalAccess', _404 => _404.role]) === "string") {
18212
+ } else if (typeof _optionalChain([message, 'optionalAccess', _420 => _420.role]) === "string") {
18124
18213
  existing.role = message.role;
18125
18214
  }
18126
18215
  if (choice.finish_reason !== void 0) {
@@ -18148,7 +18237,7 @@ function aggregateChatCompletionChunks2(chunks) {
18148
18237
  };
18149
18238
  }
18150
18239
  function getChatToolCallDeltas(value) {
18151
- if (!Array.isArray(_optionalChain([value, 'optionalAccess', _405 => _405.tool_calls]))) {
18240
+ if (!Array.isArray(_optionalChain([value, 'optionalAccess', _421 => _421.tool_calls]))) {
18152
18241
  return void 0;
18153
18242
  }
18154
18243
  const toolCalls = value.tool_calls.filter((toolCall) => isObject(toolCall));
@@ -18213,7 +18302,7 @@ function aggregateTextGenerationStreamChunks(chunks) {
18213
18302
  for (const chunk of chunks) {
18214
18303
  if (typeof chunk.generated_text === "string") {
18215
18304
  generatedText = chunk.generated_text;
18216
- } else if (typeof _optionalChain([chunk, 'access', _406 => _406.token, 'optionalAccess', _407 => _407.text]) === "string" && !chunk.token.special) {
18305
+ } else if (typeof _optionalChain([chunk, 'access', _422 => _422.token, 'optionalAccess', _423 => _423.text]) === "string" && !chunk.token.special) {
18217
18306
  generatedText += chunk.token.text;
18218
18307
  } else if (Array.isArray(chunk.choices)) {
18219
18308
  for (const choice of chunk.choices) {
@@ -18237,17 +18326,17 @@ function aggregateTextGenerationStreamChunks(chunks) {
18237
18326
  function extractTextGenerationStreamMetadata(chunks) {
18238
18327
  for (let index = chunks.length - 1; index >= 0; index--) {
18239
18328
  const chunk = chunks[index];
18240
- if (isObject(_optionalChain([chunk, 'optionalAccess', _408 => _408.details])) && typeof chunk.details.finish_reason === "string") {
18329
+ if (isObject(_optionalChain([chunk, 'optionalAccess', _424 => _424.details])) && typeof chunk.details.finish_reason === "string") {
18241
18330
  return {
18242
18331
  finish_reason: chunk.details.finish_reason
18243
18332
  };
18244
18333
  }
18245
- if (!Array.isArray(_optionalChain([chunk, 'optionalAccess', _409 => _409.choices]))) {
18334
+ if (!Array.isArray(_optionalChain([chunk, 'optionalAccess', _425 => _425.choices]))) {
18246
18335
  continue;
18247
18336
  }
18248
18337
  for (let choiceIndex = chunk.choices.length - 1; choiceIndex >= 0; choiceIndex--) {
18249
18338
  const choice = chunk.choices[choiceIndex];
18250
- if (_optionalChain([choice, 'optionalAccess', _410 => _410.finish_reason]) !== void 0) {
18339
+ if (_optionalChain([choice, 'optionalAccess', _426 => _426.finish_reason]) !== void 0) {
18251
18340
  return { finish_reason: choice.finish_reason };
18252
18341
  }
18253
18342
  }
@@ -18323,14 +18412,14 @@ var OpenRouterAgentPlugin = class extends BasePlugin {
18323
18412
  extractMetadata: (result, event) => {
18324
18413
  if (!isObject(result)) {
18325
18414
  return {
18326
- step: _optionalChain([event, 'optionalAccess', _411 => _411.step]),
18327
- step_type: _optionalChain([event, 'optionalAccess', _412 => _412.stepType])
18415
+ step: _optionalChain([event, 'optionalAccess', _427 => _427.step]),
18416
+ step_type: _optionalChain([event, 'optionalAccess', _428 => _428.stepType])
18328
18417
  };
18329
18418
  }
18330
18419
  return {
18331
18420
  ...extractOpenRouterResponseMetadata(result) || {},
18332
- ..._optionalChain([event, 'optionalAccess', _413 => _413.step]) !== void 0 ? { step: event.step } : {},
18333
- ..._optionalChain([event, 'optionalAccess', _414 => _414.stepType]) ? { step_type: event.stepType } : {}
18421
+ ..._optionalChain([event, 'optionalAccess', _429 => _429.step]) !== void 0 ? { step: event.step } : {},
18422
+ ..._optionalChain([event, 'optionalAccess', _430 => _430.stepType]) ? { step_type: event.stepType } : {}
18334
18423
  };
18335
18424
  },
18336
18425
  extractMetrics: (result) => isObject(result) ? parseOpenRouterMetricsFromUsage(result.usage) : {}
@@ -18691,7 +18780,7 @@ function publishToolResult(tracingChannel2, event, result) {
18691
18780
  }
18692
18781
  function getToolCallId(context) {
18693
18782
  const toolContext = context;
18694
- return typeof _optionalChain([toolContext, 'optionalAccess', _415 => _415.toolCall, 'optionalAccess', _416 => _416.id]) === "string" ? toolContext.toolCall.id : void 0;
18783
+ return typeof _optionalChain([toolContext, 'optionalAccess', _431 => _431.toolCall, 'optionalAccess', _432 => _432.id]) === "string" ? toolContext.toolCall.id : void 0;
18695
18784
  }
18696
18785
  var OPENROUTER_WRAPPED_CALL_MODEL_RESULT = /* @__PURE__ */ Symbol(
18697
18786
  "braintrust.openrouter.wrappedCallModelResult"
@@ -19089,9 +19178,9 @@ var OpenRouterPlugin = class extends BasePlugin {
19089
19178
  type: "llm" /* LLM */,
19090
19179
  extractInput: (args) => {
19091
19180
  const request = getOpenRouterRequestArg(args);
19092
- const chatGenerationParams = isObject(_optionalChain([request, 'optionalAccess', _417 => _417.chatGenerationParams])) ? request.chatGenerationParams : {};
19093
- const httpReferer = _optionalChain([request, 'optionalAccess', _418 => _418.httpReferer]);
19094
- const xTitle = _optionalChain([request, 'optionalAccess', _419 => _419.xTitle]);
19181
+ const chatGenerationParams = isObject(_optionalChain([request, 'optionalAccess', _433 => _433.chatGenerationParams])) ? request.chatGenerationParams : {};
19182
+ const httpReferer = _optionalChain([request, 'optionalAccess', _434 => _434.httpReferer]);
19183
+ const xTitle = _optionalChain([request, 'optionalAccess', _435 => _435.xTitle]);
19095
19184
  const { messages, ...metadata } = chatGenerationParams;
19096
19185
  return {
19097
19186
  input: messages,
@@ -19102,7 +19191,7 @@ var OpenRouterPlugin = class extends BasePlugin {
19102
19191
  return isObject(result) ? result.choices : void 0;
19103
19192
  },
19104
19193
  extractMetrics: (result, startTime) => {
19105
- const metrics = parseOpenRouterMetricsFromUsage2(_optionalChain([result, 'optionalAccess', _420 => _420.usage]));
19194
+ const metrics = parseOpenRouterMetricsFromUsage2(_optionalChain([result, 'optionalAccess', _436 => _436.usage]));
19106
19195
  if (startTime) {
19107
19196
  metrics.time_to_first_token = getCurrentUnixTimestamp() - startTime;
19108
19197
  }
@@ -19117,9 +19206,9 @@ var OpenRouterPlugin = class extends BasePlugin {
19117
19206
  type: "llm" /* LLM */,
19118
19207
  extractInput: (args) => {
19119
19208
  const request = getOpenRouterRequestArg(args);
19120
- const requestBody = isObject(_optionalChain([request, 'optionalAccess', _421 => _421.requestBody])) ? request.requestBody : {};
19121
- const httpReferer = _optionalChain([request, 'optionalAccess', _422 => _422.httpReferer]);
19122
- const xTitle = _optionalChain([request, 'optionalAccess', _423 => _423.xTitle]);
19209
+ const requestBody = isObject(_optionalChain([request, 'optionalAccess', _437 => _437.requestBody])) ? request.requestBody : {};
19210
+ const httpReferer = _optionalChain([request, 'optionalAccess', _438 => _438.httpReferer]);
19211
+ const xTitle = _optionalChain([request, 'optionalAccess', _439 => _439.xTitle]);
19123
19212
  const { input, ...metadata } = requestBody;
19124
19213
  return {
19125
19214
  input,
@@ -19134,7 +19223,7 @@ var OpenRouterPlugin = class extends BasePlugin {
19134
19223
  if (!isObject(result)) {
19135
19224
  return void 0;
19136
19225
  }
19137
- const embedding = _optionalChain([result, 'access', _424 => _424.data, 'optionalAccess', _425 => _425[0], 'optionalAccess', _426 => _426.embedding]);
19226
+ const embedding = _optionalChain([result, 'access', _440 => _440.data, 'optionalAccess', _441 => _441[0], 'optionalAccess', _442 => _442.embedding]);
19138
19227
  return Array.isArray(embedding) ? { embedding_length: embedding.length } : void 0;
19139
19228
  },
19140
19229
  extractMetadata: (result) => {
@@ -19154,9 +19243,9 @@ var OpenRouterPlugin = class extends BasePlugin {
19154
19243
  type: "llm" /* LLM */,
19155
19244
  extractInput: (args) => {
19156
19245
  const request = getOpenRouterRequestArg(args);
19157
- const requestBody = isObject(_optionalChain([request, 'optionalAccess', _427 => _427.requestBody])) ? request.requestBody : {};
19158
- const httpReferer = _optionalChain([request, 'optionalAccess', _428 => _428.httpReferer]);
19159
- const xTitle = _nullishCoalesce(_optionalChain([request, 'optionalAccess', _429 => _429.xTitle]), () => ( _optionalChain([request, 'optionalAccess', _430 => _430.appTitle])));
19246
+ const requestBody = isObject(_optionalChain([request, 'optionalAccess', _443 => _443.requestBody])) ? request.requestBody : {};
19247
+ const httpReferer = _optionalChain([request, 'optionalAccess', _444 => _444.httpReferer]);
19248
+ const xTitle = _nullishCoalesce(_optionalChain([request, 'optionalAccess', _445 => _445.xTitle]), () => ( _optionalChain([request, 'optionalAccess', _446 => _446.appTitle])));
19160
19249
  const { documents, query, ...metadata } = requestBody;
19161
19250
  return {
19162
19251
  input: {
@@ -19182,9 +19271,9 @@ var OpenRouterPlugin = class extends BasePlugin {
19182
19271
  type: "llm" /* LLM */,
19183
19272
  extractInput: (args) => {
19184
19273
  const request = getOpenRouterRequestArg(args);
19185
- const openResponsesRequest = isObject(_optionalChain([request, 'optionalAccess', _431 => _431.openResponsesRequest])) ? request.openResponsesRequest : {};
19186
- const httpReferer = _optionalChain([request, 'optionalAccess', _432 => _432.httpReferer]);
19187
- const xTitle = _optionalChain([request, 'optionalAccess', _433 => _433.xTitle]);
19274
+ const openResponsesRequest = isObject(_optionalChain([request, 'optionalAccess', _447 => _447.openResponsesRequest])) ? request.openResponsesRequest : {};
19275
+ const httpReferer = _optionalChain([request, 'optionalAccess', _448 => _448.httpReferer]);
19276
+ const xTitle = _optionalChain([request, 'optionalAccess', _449 => _449.xTitle]);
19188
19277
  const { input, ...metadata } = openResponsesRequest;
19189
19278
  return {
19190
19279
  input,
@@ -19194,7 +19283,7 @@ var OpenRouterPlugin = class extends BasePlugin {
19194
19283
  extractOutput: (result) => extractOpenRouterResponseOutput2(result),
19195
19284
  extractMetadata: (result) => extractOpenRouterResponseMetadata2(result),
19196
19285
  extractMetrics: (result, startTime) => {
19197
- const metrics = parseOpenRouterMetricsFromUsage2(_optionalChain([result, 'optionalAccess', _434 => _434.usage]));
19286
+ const metrics = parseOpenRouterMetricsFromUsage2(_optionalChain([result, 'optionalAccess', _450 => _450.usage]));
19198
19287
  if (startTime) {
19199
19288
  metrics.time_to_first_token = getCurrentUnixTimestamp() - startTime;
19200
19289
  }
@@ -19246,14 +19335,14 @@ var OpenRouterPlugin = class extends BasePlugin {
19246
19335
  extractMetadata: (result, event) => {
19247
19336
  if (!isObject(result)) {
19248
19337
  return {
19249
- step: _optionalChain([event, 'optionalAccess', _435 => _435.step]),
19250
- step_type: _optionalChain([event, 'optionalAccess', _436 => _436.stepType])
19338
+ step: _optionalChain([event, 'optionalAccess', _451 => _451.step]),
19339
+ step_type: _optionalChain([event, 'optionalAccess', _452 => _452.stepType])
19251
19340
  };
19252
19341
  }
19253
19342
  return {
19254
19343
  ...extractOpenRouterResponseMetadata2(result) || {},
19255
- ..._optionalChain([event, 'optionalAccess', _437 => _437.step]) !== void 0 ? { step: event.step } : {},
19256
- ..._optionalChain([event, 'optionalAccess', _438 => _438.stepType]) ? { step_type: event.stepType } : {}
19344
+ ..._optionalChain([event, 'optionalAccess', _453 => _453.step]) !== void 0 ? { step: event.step } : {},
19345
+ ..._optionalChain([event, 'optionalAccess', _454 => _454.stepType]) ? { step_type: event.stepType } : {}
19257
19346
  };
19258
19347
  },
19259
19348
  extractMetrics: (result) => isObject(result) ? parseOpenRouterMetricsFromUsage2(result.usage) : {}
@@ -19633,7 +19722,7 @@ function publishToolResult2(tracingChannel2, event, result) {
19633
19722
  }
19634
19723
  function getToolCallId2(context) {
19635
19724
  const toolContext = context;
19636
- return typeof _optionalChain([toolContext, 'optionalAccess', _439 => _439.toolCall, 'optionalAccess', _440 => _440.id]) === "string" ? toolContext.toolCall.id : void 0;
19725
+ return typeof _optionalChain([toolContext, 'optionalAccess', _455 => _455.toolCall, 'optionalAccess', _456 => _456.id]) === "string" ? toolContext.toolCall.id : void 0;
19637
19726
  }
19638
19727
  function aggregateOpenRouterChatChunks(chunks) {
19639
19728
  let role;
@@ -19649,12 +19738,12 @@ function aggregateOpenRouterChatChunks(chunks) {
19649
19738
  for (const chunk of chunks) {
19650
19739
  metrics = {
19651
19740
  ...metrics,
19652
- ...parseOpenRouterMetricsFromUsage2(_optionalChain([chunk, 'optionalAccess', _441 => _441.usage]))
19741
+ ...parseOpenRouterMetricsFromUsage2(_optionalChain([chunk, 'optionalAccess', _457 => _457.usage]))
19653
19742
  };
19654
- const choice = _optionalChain([chunk, 'optionalAccess', _442 => _442.choices, 'optionalAccess', _443 => _443[0]]);
19655
- const delta = _optionalChain([choice, 'optionalAccess', _444 => _444.delta]);
19743
+ const choice = _optionalChain([chunk, 'optionalAccess', _458 => _458.choices, 'optionalAccess', _459 => _459[0]]);
19744
+ const delta = _optionalChain([choice, 'optionalAccess', _460 => _460.delta]);
19656
19745
  if (!delta) {
19657
- if (_optionalChain([choice, 'optionalAccess', _445 => _445.finish_reason]) !== void 0) {
19746
+ if (_optionalChain([choice, 'optionalAccess', _461 => _461.finish_reason]) !== void 0) {
19658
19747
  finishReason = choice.finish_reason;
19659
19748
  }
19660
19749
  continue;
@@ -19680,7 +19769,7 @@ function aggregateOpenRouterChatChunks(chunks) {
19680
19769
  ...delta.reasoning_details
19681
19770
  ];
19682
19771
  }
19683
- const choiceFinishReason = _nullishCoalesce(_nullishCoalesce(_optionalChain([choice, 'optionalAccess', _446 => _446.finishReason]), () => ( _optionalChain([choice, 'optionalAccess', _447 => _447.finish_reason]))), () => ( void 0));
19772
+ const choiceFinishReason = _nullishCoalesce(_nullishCoalesce(_optionalChain([choice, 'optionalAccess', _462 => _462.finishReason]), () => ( _optionalChain([choice, 'optionalAccess', _463 => _463.finish_reason]))), () => ( void 0));
19684
19773
  const deltaFinishReason = _nullishCoalesce(_nullishCoalesce(delta.finishReason, () => ( delta.finish_reason)), () => ( void 0));
19685
19774
  if (choiceFinishReason !== void 0) {
19686
19775
  finishReason = choiceFinishReason;
@@ -19692,11 +19781,11 @@ function aggregateOpenRouterChatChunks(chunks) {
19692
19781
  continue;
19693
19782
  }
19694
19783
  for (const toolDelta of toolCallDeltas) {
19695
- if (!_optionalChain([toolDelta, 'optionalAccess', _448 => _448.function])) {
19784
+ if (!_optionalChain([toolDelta, 'optionalAccess', _464 => _464.function])) {
19696
19785
  continue;
19697
19786
  }
19698
19787
  const toolIndex = _nullishCoalesce(toolDelta.index, () => ( 0));
19699
- const existingToolCall = _optionalChain([toolCalls, 'optionalAccess', _449 => _449[toolIndex]]);
19788
+ const existingToolCall = _optionalChain([toolCalls, 'optionalAccess', _465 => _465[toolIndex]]);
19700
19789
  if (!existingToolCall || toolDelta.id && existingToolCall.id !== void 0 && existingToolCall.id !== toolDelta.id) {
19701
19790
  const nextToolCalls = [...toolCalls || []];
19702
19791
  nextToolCalls[toolIndex] = {
@@ -19746,7 +19835,7 @@ function aggregateOpenRouterChatChunks(chunks) {
19746
19835
  function aggregateOpenRouterResponseStreamEvents(chunks) {
19747
19836
  let finalResponse;
19748
19837
  for (const chunk of chunks) {
19749
- const response = _optionalChain([chunk, 'optionalAccess', _450 => _450.response]);
19838
+ const response = _optionalChain([chunk, 'optionalAccess', _466 => _466.response]);
19750
19839
  if (!response) {
19751
19840
  continue;
19752
19841
  }
@@ -20176,10 +20265,10 @@ var MistralPlugin = class extends BasePlugin {
20176
20265
  type: "llm" /* LLM */,
20177
20266
  extractInput: extractMessagesInputWithMetadata,
20178
20267
  extractOutput: (result) => {
20179
- return _optionalChain([result, 'optionalAccess', _451 => _451.choices]);
20268
+ return _optionalChain([result, 'optionalAccess', _467 => _467.choices]);
20180
20269
  },
20181
20270
  extractMetadata: (result) => extractMistralResponseMetadata(result),
20182
- extractMetrics: (result, startTime) => extractMistralMetrics(_optionalChain([result, 'optionalAccess', _452 => _452.usage]), startTime)
20271
+ extractMetrics: (result, startTime) => extractMistralMetrics(_optionalChain([result, 'optionalAccess', _468 => _468.usage]), startTime)
20183
20272
  })
20184
20273
  );
20185
20274
  this.unsubscribers.push(
@@ -20199,11 +20288,11 @@ var MistralPlugin = class extends BasePlugin {
20199
20288
  type: "llm" /* LLM */,
20200
20289
  extractInput: extractEmbeddingInputWithMetadata,
20201
20290
  extractOutput: (result) => {
20202
- const embedding = _optionalChain([result, 'optionalAccess', _453 => _453.data, 'optionalAccess', _454 => _454[0], 'optionalAccess', _455 => _455.embedding]);
20291
+ const embedding = _optionalChain([result, 'optionalAccess', _469 => _469.data, 'optionalAccess', _470 => _470[0], 'optionalAccess', _471 => _471.embedding]);
20203
20292
  return Array.isArray(embedding) ? { embedding_length: embedding.length } : void 0;
20204
20293
  },
20205
20294
  extractMetadata: (result) => extractMistralResponseMetadata(result),
20206
- extractMetrics: (result) => parseMistralMetricsFromUsage(_optionalChain([result, 'optionalAccess', _456 => _456.usage]))
20295
+ extractMetrics: (result) => parseMistralMetricsFromUsage(_optionalChain([result, 'optionalAccess', _472 => _472.usage]))
20207
20296
  })
20208
20297
  );
20209
20298
  this.unsubscribers.push(
@@ -20213,7 +20302,7 @@ var MistralPlugin = class extends BasePlugin {
20213
20302
  extractInput: extractClassifierInputWithMetadata,
20214
20303
  extractOutput: extractClassifierOutput,
20215
20304
  extractMetadata: (result) => extractMistralResponseMetadata(result),
20216
- extractMetrics: (result) => parseMistralMetricsFromUsage(_optionalChain([result, 'optionalAccess', _457 => _457.usage]))
20305
+ extractMetrics: (result) => parseMistralMetricsFromUsage(_optionalChain([result, 'optionalAccess', _473 => _473.usage]))
20217
20306
  })
20218
20307
  );
20219
20308
  this.unsubscribers.push(
@@ -20223,7 +20312,7 @@ var MistralPlugin = class extends BasePlugin {
20223
20312
  extractInput: extractClassifierInputWithMetadata,
20224
20313
  extractOutput: extractClassifierOutput,
20225
20314
  extractMetadata: (result) => extractMistralResponseMetadata(result),
20226
- extractMetrics: (result) => parseMistralMetricsFromUsage(_optionalChain([result, 'optionalAccess', _458 => _458.usage]))
20315
+ extractMetrics: (result) => parseMistralMetricsFromUsage(_optionalChain([result, 'optionalAccess', _474 => _474.usage]))
20227
20316
  })
20228
20317
  );
20229
20318
  this.unsubscribers.push(
@@ -20233,7 +20322,7 @@ var MistralPlugin = class extends BasePlugin {
20233
20322
  extractInput: extractClassifierInputWithMetadata,
20234
20323
  extractOutput: extractClassifierOutput,
20235
20324
  extractMetadata: (result) => extractMistralResponseMetadata(result),
20236
- extractMetrics: (result) => parseMistralMetricsFromUsage(_optionalChain([result, 'optionalAccess', _459 => _459.usage]))
20325
+ extractMetrics: (result) => parseMistralMetricsFromUsage(_optionalChain([result, 'optionalAccess', _475 => _475.usage]))
20237
20326
  })
20238
20327
  );
20239
20328
  this.unsubscribers.push(
@@ -20243,7 +20332,7 @@ var MistralPlugin = class extends BasePlugin {
20243
20332
  extractInput: extractClassifierInputWithMetadata,
20244
20333
  extractOutput: extractClassifierOutput,
20245
20334
  extractMetadata: (result) => extractMistralResponseMetadata(result),
20246
- extractMetrics: (result) => parseMistralMetricsFromUsage(_optionalChain([result, 'optionalAccess', _460 => _460.usage]))
20335
+ extractMetrics: (result) => parseMistralMetricsFromUsage(_optionalChain([result, 'optionalAccess', _476 => _476.usage]))
20247
20336
  })
20248
20337
  );
20249
20338
  this.unsubscribers.push(
@@ -20252,10 +20341,10 @@ var MistralPlugin = class extends BasePlugin {
20252
20341
  type: "llm" /* LLM */,
20253
20342
  extractInput: extractPromptInputWithMetadata,
20254
20343
  extractOutput: (result) => {
20255
- return _optionalChain([result, 'optionalAccess', _461 => _461.choices]);
20344
+ return _optionalChain([result, 'optionalAccess', _477 => _477.choices]);
20256
20345
  },
20257
20346
  extractMetadata: (result) => extractMistralResponseMetadata(result),
20258
- extractMetrics: (result, startTime) => extractMistralMetrics(_optionalChain([result, 'optionalAccess', _462 => _462.usage]), startTime)
20347
+ extractMetrics: (result, startTime) => extractMistralMetrics(_optionalChain([result, 'optionalAccess', _478 => _478.usage]), startTime)
20259
20348
  })
20260
20349
  );
20261
20350
  this.unsubscribers.push(
@@ -20275,10 +20364,10 @@ var MistralPlugin = class extends BasePlugin {
20275
20364
  type: "llm" /* LLM */,
20276
20365
  extractInput: extractMessagesInputWithMetadata,
20277
20366
  extractOutput: (result) => {
20278
- return _optionalChain([result, 'optionalAccess', _463 => _463.choices]);
20367
+ return _optionalChain([result, 'optionalAccess', _479 => _479.choices]);
20279
20368
  },
20280
20369
  extractMetadata: (result) => extractMistralResponseMetadata(result),
20281
- extractMetrics: (result, startTime) => extractMistralMetrics(_optionalChain([result, 'optionalAccess', _464 => _464.usage]), startTime)
20370
+ extractMetrics: (result, startTime) => extractMistralMetrics(_optionalChain([result, 'optionalAccess', _480 => _480.usage]), startTime)
20282
20371
  })
20283
20372
  );
20284
20373
  this.unsubscribers.push(
@@ -20533,11 +20622,11 @@ function mergeMistralContentParts(left, right) {
20533
20622
  const merged = [...(left || []).map((part) => structuredClone(part))];
20534
20623
  for (const part of right) {
20535
20624
  const lastPart = merged[merged.length - 1];
20536
- if (part.type === "text" && _optionalChain([lastPart, 'optionalAccess', _465 => _465.type]) === "text" && typeof lastPart.text === "string" && typeof part.text === "string") {
20625
+ if (part.type === "text" && _optionalChain([lastPart, 'optionalAccess', _481 => _481.type]) === "text" && typeof lastPart.text === "string" && typeof part.text === "string") {
20537
20626
  lastPart.text += part.text;
20538
20627
  continue;
20539
20628
  }
20540
- if (part.type === "thinking" && _optionalChain([lastPart, 'optionalAccess', _466 => _466.type]) === "thinking" && Array.isArray(lastPart.thinking) && Array.isArray(part.thinking)) {
20629
+ if (part.type === "thinking" && _optionalChain([lastPart, 'optionalAccess', _482 => _482.type]) === "thinking" && Array.isArray(lastPart.thinking) && Array.isArray(part.thinking)) {
20541
20630
  lastPart.thinking = mergeMistralTextSegments(
20542
20631
  lastPart.thinking,
20543
20632
  part.thinking
@@ -20592,13 +20681,13 @@ function createMergedToolCallDelta(delta) {
20592
20681
  ...delta,
20593
20682
  function: {
20594
20683
  ...delta.function,
20595
- arguments: typeof _optionalChain([delta, 'access', _467 => _467.function, 'optionalAccess', _468 => _468.arguments]) === "string" ? delta.function.arguments : ""
20684
+ arguments: typeof _optionalChain([delta, 'access', _483 => _483.function, 'optionalAccess', _484 => _484.arguments]) === "string" ? delta.function.arguments : ""
20596
20685
  }
20597
20686
  };
20598
20687
  }
20599
20688
  function mergeToolCallDeltaPair(current, delta) {
20600
- const currentArguments = typeof _optionalChain([current, 'access', _469 => _469.function, 'optionalAccess', _470 => _470.arguments]) === "string" ? current.function.arguments : "";
20601
- const deltaArguments = typeof _optionalChain([delta, 'access', _471 => _471.function, 'optionalAccess', _472 => _472.arguments]) === "string" ? delta.function.arguments : "";
20689
+ const currentArguments = typeof _optionalChain([current, 'access', _485 => _485.function, 'optionalAccess', _486 => _486.arguments]) === "string" ? current.function.arguments : "";
20690
+ const deltaArguments = typeof _optionalChain([delta, 'access', _487 => _487.function, 'optionalAccess', _488 => _488.arguments]) === "string" ? delta.function.arguments : "";
20602
20691
  return {
20603
20692
  ...current,
20604
20693
  ...delta,
@@ -20701,7 +20790,7 @@ function aggregateMistralStreamChunks(chunks) {
20701
20790
  let metrics = {};
20702
20791
  let metadata;
20703
20792
  for (const event of chunks) {
20704
- const chunk = isMistralChatCompletionChunk(_optionalChain([event, 'optionalAccess', _473 => _473.data])) ? event.data : void 0;
20793
+ const chunk = isMistralChatCompletionChunk(_optionalChain([event, 'optionalAccess', _489 => _489.data])) ? event.data : void 0;
20705
20794
  if (!chunk) {
20706
20795
  continue;
20707
20796
  }
@@ -20892,7 +20981,7 @@ var GoogleADKPlugin = (_class21 = class extends BasePlugin {constructor(...args5
20892
20981
  };
20893
20982
  tracingChannel2.subscribe(handlers);
20894
20983
  this.unsubscribers.push(() => {
20895
- _optionalChain([unbindCurrentSpanStore, 'optionalCall', _474 => _474()]);
20984
+ _optionalChain([unbindCurrentSpanStore, 'optionalCall', _490 => _490()]);
20896
20985
  tracingChannel2.unsubscribe(handlers);
20897
20986
  });
20898
20987
  }
@@ -20995,7 +21084,7 @@ var GoogleADKPlugin = (_class21 = class extends BasePlugin {constructor(...args5
20995
21084
  };
20996
21085
  tracingChannel2.subscribe(handlers);
20997
21086
  this.unsubscribers.push(() => {
20998
- _optionalChain([unbindCurrentSpanStore, 'optionalCall', _475 => _475()]);
21087
+ _optionalChain([unbindCurrentSpanStore, 'optionalCall', _491 => _491()]);
20999
21088
  tracingChannel2.unsubscribe(handlers);
21000
21089
  });
21001
21090
  }
@@ -21142,10 +21231,10 @@ function bindAsyncIterableToCurrentSpan(stream, span) {
21142
21231
  }
21143
21232
  function bindCurrentSpanStoreToStart3(tracingChannel2, states, create) {
21144
21233
  const state = _internalGetGlobalState();
21145
- const contextManager = _optionalChain([state, 'optionalAccess', _476 => _476.contextManager]);
21234
+ const contextManager = _optionalChain([state, 'optionalAccess', _492 => _492.contextManager]);
21146
21235
  const startChannel = tracingChannel2.start;
21147
21236
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
21148
- if (!_optionalChain([startChannel, 'optionalAccess', _477 => _477.bindStore]) || !currentSpanStore) {
21237
+ if (!_optionalChain([startChannel, 'optionalAccess', _493 => _493.bindStore]) || !currentSpanStore) {
21149
21238
  return void 0;
21150
21239
  }
21151
21240
  startChannel.bindStore(currentSpanStore, (event) => {
@@ -21157,7 +21246,7 @@ function bindCurrentSpanStoreToStart3(tracingChannel2, states, create) {
21157
21246
  return contextManager.wrapSpanForStore(span);
21158
21247
  });
21159
21248
  return () => {
21160
- _optionalChain([startChannel, 'access', _478 => _478.unbindStore, 'optionalCall', _479 => _479(currentSpanStore)]);
21249
+ _optionalChain([startChannel, 'access', _494 => _494.unbindStore, 'optionalCall', _495 => _495(currentSpanStore)]);
21161
21250
  };
21162
21251
  }
21163
21252
  function extractRunnerContextKey(paramsOrContext) {
@@ -21170,9 +21259,9 @@ function extractRunnerContextKey(paramsOrContext) {
21170
21259
  return extractInvocationContextKey(invocationContext);
21171
21260
  }
21172
21261
  function extractInvocationContextKey(parentContext) {
21173
- const session = _optionalChain([parentContext, 'optionalAccess', _480 => _480.session]);
21174
- const userId = _optionalChain([session, 'optionalAccess', _481 => _481.userId]);
21175
- const sessionId = _optionalChain([session, 'optionalAccess', _482 => _482.id]);
21262
+ const session = _optionalChain([parentContext, 'optionalAccess', _496 => _496.session]);
21263
+ const userId = _optionalChain([session, 'optionalAccess', _497 => _497.userId]);
21264
+ const sessionId = _optionalChain([session, 'optionalAccess', _498 => _498.id]);
21176
21265
  if (typeof userId !== "string" || typeof sessionId !== "string") {
21177
21266
  return void 0;
21178
21267
  }
@@ -21229,27 +21318,27 @@ function extractRunnerMetadata(paramsOrContext) {
21229
21318
  metadata["google_adk.session_id"] = directSessionId;
21230
21319
  }
21231
21320
  const session = "session" in paramsOrContext ? paramsOrContext.session : void 0;
21232
- if (metadata["google_adk.user_id"] === void 0 && typeof _optionalChain([session, 'optionalAccess', _483 => _483.userId]) === "string") {
21321
+ if (metadata["google_adk.user_id"] === void 0 && typeof _optionalChain([session, 'optionalAccess', _499 => _499.userId]) === "string") {
21233
21322
  metadata["google_adk.user_id"] = session.userId;
21234
21323
  }
21235
- if (metadata["google_adk.session_id"] === void 0 && typeof _optionalChain([session, 'optionalAccess', _484 => _484.id]) === "string") {
21324
+ if (metadata["google_adk.session_id"] === void 0 && typeof _optionalChain([session, 'optionalAccess', _500 => _500.id]) === "string") {
21236
21325
  metadata["google_adk.session_id"] = session.id;
21237
21326
  }
21238
21327
  return metadata;
21239
21328
  }
21240
21329
  function extractAgentName(agent, parentContext) {
21241
- if (typeof _optionalChain([agent, 'optionalAccess', _485 => _485.name]) === "string" && agent.name.length > 0) {
21330
+ if (typeof _optionalChain([agent, 'optionalAccess', _501 => _501.name]) === "string" && agent.name.length > 0) {
21242
21331
  return agent.name;
21243
21332
  }
21244
21333
  if (!parentContext) {
21245
21334
  return void 0;
21246
21335
  }
21247
21336
  const contextAgent = parentContext.agent;
21248
- return typeof _optionalChain([contextAgent, 'optionalAccess', _486 => _486.name]) === "string" && contextAgent.name.length > 0 ? contextAgent.name : void 0;
21337
+ return typeof _optionalChain([contextAgent, 'optionalAccess', _502 => _502.name]) === "string" && contextAgent.name.length > 0 ? contextAgent.name : void 0;
21249
21338
  }
21250
21339
  function extractModelName(agent, parentContext) {
21251
- const modelAgent = _nullishCoalesce(agent, () => ( _optionalChain([parentContext, 'optionalAccess', _487 => _487.agent])));
21252
- if (!_optionalChain([modelAgent, 'optionalAccess', _488 => _488.model])) {
21340
+ const modelAgent = _nullishCoalesce(agent, () => ( _optionalChain([parentContext, 'optionalAccess', _503 => _503.agent])));
21341
+ if (!_optionalChain([modelAgent, 'optionalAccess', _504 => _504.model])) {
21253
21342
  return;
21254
21343
  }
21255
21344
  if (typeof modelAgent.model === "string") {
@@ -21262,30 +21351,30 @@ function extractModelName(agent, parentContext) {
21262
21351
  }
21263
21352
  function extractToolCallId(req) {
21264
21353
  const toolContext = req.toolContext;
21265
- return _optionalChain([toolContext, 'optionalAccess', _489 => _489.functionCallId]);
21354
+ return _optionalChain([toolContext, 'optionalAccess', _505 => _505.functionCallId]);
21266
21355
  }
21267
21356
  function extractToolName2(req, tool) {
21268
- if (typeof _optionalChain([tool, 'optionalAccess', _490 => _490.name]) === "string" && tool.name.length > 0) {
21357
+ if (typeof _optionalChain([tool, 'optionalAccess', _506 => _506.name]) === "string" && tool.name.length > 0) {
21269
21358
  return tool.name;
21270
21359
  }
21271
21360
  const toolContext = req.toolContext;
21272
- const invocationContext = _optionalChain([toolContext, 'optionalAccess', _491 => _491.invocationContext]);
21273
- const invocationTool = _optionalChain([invocationContext, 'optionalAccess', _492 => _492.tool]);
21274
- const toolName = _optionalChain([invocationTool, 'optionalAccess', _493 => _493.name]);
21361
+ const invocationContext = _optionalChain([toolContext, 'optionalAccess', _507 => _507.invocationContext]);
21362
+ const invocationTool = _optionalChain([invocationContext, 'optionalAccess', _508 => _508.tool]);
21363
+ const toolName = _optionalChain([invocationTool, 'optionalAccess', _509 => _509.name]);
21275
21364
  return typeof toolName === "string" && toolName.length > 0 ? toolName : void 0;
21276
21365
  }
21277
21366
  function extractToolAgentName(req) {
21278
21367
  const toolContext = req.toolContext;
21279
- const directName = _optionalChain([toolContext, 'optionalAccess', _494 => _494.agentName]);
21368
+ const directName = _optionalChain([toolContext, 'optionalAccess', _510 => _510.agentName]);
21280
21369
  if (typeof directName === "string" && directName.length > 0) {
21281
21370
  return directName;
21282
21371
  }
21283
- const invocationContext = _optionalChain([toolContext, 'optionalAccess', _495 => _495.invocationContext]);
21372
+ const invocationContext = _optionalChain([toolContext, 'optionalAccess', _511 => _511.invocationContext]);
21284
21373
  return extractAgentName(void 0, invocationContext);
21285
21374
  }
21286
21375
  function findToolParentSpan(req, activeAgentSpans, activeRunnerSpans) {
21287
21376
  const toolContext = req.toolContext;
21288
- const invocationContext = _optionalChain([toolContext, 'optionalAccess', _496 => _496.invocationContext]);
21377
+ const invocationContext = _optionalChain([toolContext, 'optionalAccess', _512 => _512.invocationContext]);
21289
21378
  const contextKey = extractInvocationContextKey(invocationContext);
21290
21379
  const agentName = extractToolAgentName(req);
21291
21380
  if (contextKey && agentName) {
@@ -21667,7 +21756,7 @@ function extractCohereResponseMetadata(result) {
21667
21756
  RESPONSE_METADATA_ALLOWLIST2
21668
21757
  );
21669
21758
  const meta = isObject(result.meta) ? result.meta : void 0;
21670
- const apiVersion = isObject(_optionalChain([meta, 'optionalAccess', _497 => _497.apiVersion])) && typeof meta.apiVersion.version === "string" && meta.apiVersion.version || isObject(_optionalChain([meta, 'optionalAccess', _498 => _498.api_version])) && typeof meta.api_version.version === "string" && meta.api_version.version;
21759
+ const apiVersion = isObject(_optionalChain([meta, 'optionalAccess', _513 => _513.apiVersion])) && typeof meta.apiVersion.version === "string" && meta.apiVersion.version || isObject(_optionalChain([meta, 'optionalAccess', _514 => _514.api_version])) && typeof meta.api_version.version === "string" && meta.api_version.version;
21671
21760
  const metadata = {
21672
21761
  ...responseMetadata,
21673
21762
  ...apiVersion ? { api_version: apiVersion } : {}
@@ -21828,13 +21917,13 @@ function getToolCallIndex2(toolCall, fallbackIndex) {
21828
21917
  return typeof toolCall.index === "number" && Number.isInteger(toolCall.index) ? toolCall.index : fallbackIndex;
21829
21918
  }
21830
21919
  function appendToolCallDelta(existing, incoming) {
21831
- const currentArguments = isObject(_optionalChain([existing, 'optionalAccess', _499 => _499.function])) && typeof existing.function.arguments === "string" ? existing.function.arguments : "";
21920
+ const currentArguments = isObject(_optionalChain([existing, 'optionalAccess', _515 => _515.function])) && typeof existing.function.arguments === "string" ? existing.function.arguments : "";
21832
21921
  const incomingArguments = isObject(incoming.function) && typeof incoming.function.arguments === "string" ? incoming.function.arguments : "";
21833
21922
  return {
21834
21923
  ...existing,
21835
21924
  ...incoming,
21836
21925
  function: {
21837
- ...isObject(_optionalChain([existing, 'optionalAccess', _500 => _500.function])) ? existing.function : {},
21926
+ ...isObject(_optionalChain([existing, 'optionalAccess', _516 => _516.function])) ? existing.function : {},
21838
21927
  ...isObject(incoming.function) ? incoming.function : {},
21839
21928
  ...incomingArguments ? { arguments: `${currentArguments}${incomingArguments}` } : {}
21840
21929
  }
@@ -22090,7 +22179,7 @@ function aggregateCohereChatStreamChunks(chunks) {
22090
22179
  ...mergedToolCalls.length > 0 ? { toolCalls: mergedToolCalls } : {}
22091
22180
  };
22092
22181
  } else if (mergedToolCalls.length > 0 || role || mergedText.length > 0 || aggregatedContentBlocks.length > 0) {
22093
- const textContent = mergedText.length > 0 ? mergedText : _optionalChain([aggregatedContentBlocks, 'access', _501 => _501[0], 'optionalAccess', _502 => _502.type]) === "text" ? aggregatedContentBlocks[0].text : void 0;
22182
+ const textContent = mergedText.length > 0 ? mergedText : _optionalChain([aggregatedContentBlocks, 'access', _517 => _517[0], 'optionalAccess', _518 => _518.type]) === "text" ? aggregatedContentBlocks[0].text : void 0;
22094
22183
  output = {
22095
22184
  ...role ? { role } : {},
22096
22185
  ...textContent ? { content: textContent } : {},
@@ -22139,7 +22228,7 @@ var GroqPlugin = class extends BasePlugin {
22139
22228
  metadata: { ...metadata, provider: "groq" }
22140
22229
  };
22141
22230
  },
22142
- extractOutput: (result) => _optionalChain([result, 'optionalAccess', _503 => _503.choices]),
22231
+ extractOutput: (result) => _optionalChain([result, 'optionalAccess', _519 => _519.choices]),
22143
22232
  extractMetrics: (result, startTime) => {
22144
22233
  const metrics = parseGroqMetrics(result);
22145
22234
  if (startTime) {
@@ -22162,7 +22251,7 @@ var GroqPlugin = class extends BasePlugin {
22162
22251
  };
22163
22252
  },
22164
22253
  extractOutput: (result) => {
22165
- const embedding = _optionalChain([result, 'optionalAccess', _504 => _504.data, 'optionalAccess', _505 => _505[0], 'optionalAccess', _506 => _506.embedding]);
22254
+ const embedding = _optionalChain([result, 'optionalAccess', _520 => _520.data, 'optionalAccess', _521 => _521[0], 'optionalAccess', _522 => _522.embedding]);
22166
22255
  return Array.isArray(embedding) ? { embedding_length: embedding.length } : void 0;
22167
22256
  },
22168
22257
  extractMetrics: (result) => parseGroqMetrics(result)
@@ -22174,8 +22263,8 @@ var GroqPlugin = class extends BasePlugin {
22174
22263
  }
22175
22264
  };
22176
22265
  function parseGroqMetrics(result) {
22177
- const metrics = parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _507 => _507.usage]));
22178
- const xGroq = _optionalChain([result, 'optionalAccess', _508 => _508.x_groq]);
22266
+ const metrics = parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _523 => _523.usage]));
22267
+ const xGroq = _optionalChain([result, 'optionalAccess', _524 => _524.x_groq]);
22179
22268
  if (!xGroq || typeof xGroq !== "object") {
22180
22269
  return metrics;
22181
22270
  }
@@ -22199,7 +22288,7 @@ function aggregateGroqChatCompletionChunks(chunks, streamResult, endEvent) {
22199
22288
  );
22200
22289
  const reasoning = aggregateGroqReasoning(chunks);
22201
22290
  if (reasoning !== void 0) {
22202
- const message = _optionalChain([aggregated, 'access', _509 => _509.output, 'access', _510 => _510[0], 'optionalAccess', _511 => _511.message]);
22291
+ const message = _optionalChain([aggregated, 'access', _525 => _525.output, 'access', _526 => _526[0], 'optionalAccess', _527 => _527.message]);
22203
22292
  if (message) {
22204
22293
  message.reasoning = reasoning;
22205
22294
  }
@@ -22212,8 +22301,8 @@ function aggregateGroqChatCompletionChunks(chunks, streamResult, endEvent) {
22212
22301
  function aggregateGroqReasoning(chunks) {
22213
22302
  let reasoning = "";
22214
22303
  for (const chunk of chunks) {
22215
- const delta = _optionalChain([chunk, 'access', _512 => _512.choices, 'optionalAccess', _513 => _513[0], 'optionalAccess', _514 => _514.delta]);
22216
- const deltaReasoning = _optionalChain([delta, 'optionalAccess', _515 => _515.reasoning]);
22304
+ const delta = _optionalChain([chunk, 'access', _528 => _528.choices, 'optionalAccess', _529 => _529[0], 'optionalAccess', _530 => _530.delta]);
22305
+ const deltaReasoning = _optionalChain([delta, 'optionalAccess', _531 => _531.reasoning]);
22217
22306
  if (typeof deltaReasoning === "string") {
22218
22307
  reasoning += deltaReasoning;
22219
22308
  }
@@ -22270,8 +22359,8 @@ var GenkitPlugin = class extends BasePlugin {
22270
22359
  type: "llm" /* LLM */,
22271
22360
  extractInput: ([input]) => extractGenerateInput(input),
22272
22361
  extractOutput: extractGenerateOutput,
22273
- extractMetadata: (result, event) => extractGenerateResponseMetadata(result, _optionalChain([event, 'optionalAccess', _516 => _516.arguments, 'optionalAccess', _517 => _517[0]])),
22274
- extractMetrics: (result) => parseGenkitUsageMetrics(_optionalChain([result, 'optionalAccess', _518 => _518.usage]))
22362
+ extractMetadata: (result, event) => extractGenerateResponseMetadata(result, _optionalChain([event, 'optionalAccess', _532 => _532.arguments, 'optionalAccess', _533 => _533[0]])),
22363
+ extractMetrics: (result) => parseGenkitUsageMetrics(_optionalChain([result, 'optionalAccess', _534 => _534.usage]))
22275
22364
  })
22276
22365
  );
22277
22366
  this.unsubscribers.push(
@@ -22288,7 +22377,7 @@ var GenkitPlugin = class extends BasePlugin {
22288
22377
  type: "function" /* FUNCTION */,
22289
22378
  extractInput: ([params]) => extractEmbedInput(params),
22290
22379
  extractOutput: (result) => summarizeEmbeddingResult(result),
22291
- extractMetadata: (_result, event) => extractEmbedMetadata(_optionalChain([event, 'optionalAccess', _519 => _519.arguments, 'optionalAccess', _520 => _520[0]])),
22380
+ extractMetadata: (_result, event) => extractEmbedMetadata(_optionalChain([event, 'optionalAccess', _535 => _535.arguments, 'optionalAccess', _536 => _536[0]])),
22292
22381
  extractMetrics: () => ({})
22293
22382
  })
22294
22383
  );
@@ -22298,7 +22387,7 @@ var GenkitPlugin = class extends BasePlugin {
22298
22387
  type: "function" /* FUNCTION */,
22299
22388
  extractInput: ([params]) => extractEmbedManyInput(params),
22300
22389
  extractOutput: summarizeEmbeddingResult,
22301
- extractMetadata: (_result, event) => extractEmbedMetadata(_optionalChain([event, 'optionalAccess', _521 => _521.arguments, 'optionalAccess', _522 => _522[0]])),
22390
+ extractMetadata: (_result, event) => extractEmbedMetadata(_optionalChain([event, 'optionalAccess', _537 => _537.arguments, 'optionalAccess', _538 => _538[0]])),
22302
22391
  extractMetrics: () => ({})
22303
22392
  })
22304
22393
  );
@@ -22349,7 +22438,7 @@ var GenkitPlugin = class extends BasePlugin {
22349
22438
  };
22350
22439
  tracingChannel2.subscribe(handlers);
22351
22440
  this.unsubscribers.push(() => {
22352
- _optionalChain([unbindCurrentSpanStore, 'optionalCall', _523 => _523()]);
22441
+ _optionalChain([unbindCurrentSpanStore, 'optionalCall', _539 => _539()]);
22353
22442
  tracingChannel2.unsubscribe(handlers);
22354
22443
  });
22355
22444
  }
@@ -22397,7 +22486,7 @@ var GenkitPlugin = class extends BasePlugin {
22397
22486
  };
22398
22487
  tracingChannel2.subscribe(handlers);
22399
22488
  this.unsubscribers.push(() => {
22400
- _optionalChain([unbindCurrentSpanStore, 'optionalCall', _524 => _524()]);
22489
+ _optionalChain([unbindCurrentSpanStore, 'optionalCall', _540 => _540()]);
22401
22490
  tracingChannel2.unsubscribe(handlers);
22402
22491
  });
22403
22492
  }
@@ -22464,10 +22553,10 @@ function ensureActionSpanState(states, event, create) {
22464
22553
  }
22465
22554
  function bindActionCurrentSpanStoreToStart(tracingChannel2, states, create) {
22466
22555
  const state = _internalGetGlobalState();
22467
- const contextManager = _optionalChain([state, 'optionalAccess', _525 => _525.contextManager]);
22556
+ const contextManager = _optionalChain([state, 'optionalAccess', _541 => _541.contextManager]);
22468
22557
  const startChannel = tracingChannel2.start;
22469
22558
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
22470
- if (!_optionalChain([startChannel, 'optionalAccess', _526 => _526.bindStore]) || !currentSpanStore) {
22559
+ if (!_optionalChain([startChannel, 'optionalAccess', _542 => _542.bindStore]) || !currentSpanStore) {
22471
22560
  return void 0;
22472
22561
  }
22473
22562
  startChannel.bindStore(currentSpanStore, (event) => {
@@ -22479,7 +22568,7 @@ function bindActionCurrentSpanStoreToStart(tracingChannel2, states, create) {
22479
22568
  return state2 ? contextManager.wrapSpanForStore(state2.span) : currentSpanStore.getStore();
22480
22569
  });
22481
22570
  return () => {
22482
- _optionalChain([startChannel, 'access', _527 => _527.unbindStore, 'optionalCall', _528 => _528(currentSpanStore)]);
22571
+ _optionalChain([startChannel, 'access', _543 => _543.unbindStore, 'optionalCall', _544 => _544(currentSpanStore)]);
22483
22572
  };
22484
22573
  }
22485
22574
  function normalizeInput(input) {
@@ -22526,25 +22615,25 @@ function extractGenerateOutput(result) {
22526
22615
  }
22527
22616
  function extractGenerateResponseMetadata(result, input) {
22528
22617
  const normalized = input ? normalizeInput(input) : void 0;
22529
- const request = isObject(_optionalChain([result, 'optionalAccess', _529 => _529.request])) ? _optionalChain([result, 'optionalAccess', _530 => _530.request]) : isObject(normalized) ? normalized : void 0;
22618
+ const request = isObject(_optionalChain([result, 'optionalAccess', _545 => _545.request])) ? _optionalChain([result, 'optionalAccess', _546 => _546.request]) : isObject(normalized) ? normalized : void 0;
22530
22619
  return {
22531
22620
  ...genkitProviderMetadata(),
22532
22621
  ...pickDefined({
22533
- model: modelName(_nullishCoalesce(_optionalChain([result, 'optionalAccess', _531 => _531.model]), () => ( _optionalChain([request, 'optionalAccess', _532 => _532.model])))),
22534
- finishReason: _optionalChain([result, 'optionalAccess', _533 => _533.finishReason]),
22535
- finishMessage: _optionalChain([result, 'optionalAccess', _534 => _534.finishMessage])
22622
+ model: modelName(_nullishCoalesce(_optionalChain([result, 'optionalAccess', _547 => _547.model]), () => ( _optionalChain([request, 'optionalAccess', _548 => _548.model])))),
22623
+ finishReason: _optionalChain([result, 'optionalAccess', _549 => _549.finishReason]),
22624
+ finishMessage: _optionalChain([result, 'optionalAccess', _550 => _550.finishMessage])
22536
22625
  })
22537
22626
  };
22538
22627
  }
22539
22628
  function extractEmbedInput(params) {
22540
22629
  return {
22541
- input: processInputAttachments(_optionalChain([params, 'optionalAccess', _535 => _535.content])),
22630
+ input: processInputAttachments(_optionalChain([params, 'optionalAccess', _551 => _551.content])),
22542
22631
  metadata: extractEmbedMetadata(params)
22543
22632
  };
22544
22633
  }
22545
22634
  function extractEmbedManyInput(params) {
22546
22635
  return {
22547
- input: processInputAttachments(_optionalChain([params, 'optionalAccess', _536 => _536.content])),
22636
+ input: processInputAttachments(_optionalChain([params, 'optionalAccess', _552 => _552.content])),
22548
22637
  metadata: extractEmbedMetadata(params)
22549
22638
  };
22550
22639
  }
@@ -22552,7 +22641,7 @@ function extractEmbedMetadata(params) {
22552
22641
  return {
22553
22642
  ...genkitProviderMetadata(),
22554
22643
  ...pickDefined({
22555
- model: modelName(_optionalChain([params, 'optionalAccess', _537 => _537.embedder]))
22644
+ model: modelName(_optionalChain([params, 'optionalAccess', _553 => _553.embedder]))
22556
22645
  })
22557
22646
  };
22558
22647
  }
@@ -22560,7 +22649,7 @@ function summarizeEmbeddingResult(result) {
22560
22649
  if (Array.isArray(result)) {
22561
22650
  return {
22562
22651
  embedding_count: result.length,
22563
- dimensions: Array.isArray(result[0]) || Array.isArray(_optionalChain([result, 'access', _538 => _538[0], 'optionalAccess', _539 => _539.embedding])) ? result[0].length || _optionalChain([result, 'access', _540 => _540[0], 'optionalAccess', _541 => _541.embedding, 'optionalAccess', _542 => _542.length]) : void 0
22652
+ dimensions: Array.isArray(result[0]) || Array.isArray(_optionalChain([result, 'access', _554 => _554[0], 'optionalAccess', _555 => _555.embedding])) ? result[0].length || _optionalChain([result, 'access', _556 => _556[0], 'optionalAccess', _557 => _557.embedding, 'optionalAccess', _558 => _558.length]) : void 0
22564
22653
  };
22565
22654
  }
22566
22655
  if (isObject(result) && Array.isArray(result.embeddings)) {
@@ -22587,7 +22676,7 @@ function patchGenerateStreamResult(result, span, startTime) {
22587
22676
  finishSpan(async () => {
22588
22677
  const streamedText = chunks.map((chunk) => safeGet(chunk, "text")).join("");
22589
22678
  const response = await result.response;
22590
- const metrics = parseGenkitUsageMetrics(_optionalChain([response, 'optionalAccess', _543 => _543.usage]));
22679
+ const metrics = parseGenkitUsageMetrics(_optionalChain([response, 'optionalAccess', _559 => _559.usage]));
22591
22680
  if (firstChunkTime !== void 0) {
22592
22681
  metrics.time_to_first_token = firstChunkTime - startTime;
22593
22682
  }
@@ -22680,22 +22769,22 @@ function extractActionMetadata(self) {
22680
22769
  }
22681
22770
  function extractActionSpanMetadata(args) {
22682
22771
  const options = extractRunInNewSpanOptions(args);
22683
- const labels = isObject(_optionalChain([options, 'optionalAccess', _544 => _544.labels])) ? options.labels : void 0;
22684
- const metadata = isObject(_optionalChain([options, 'optionalAccess', _545 => _545.metadata])) ? options.metadata : void 0;
22685
- const actionType = stringValue(_optionalChain([labels, 'optionalAccess', _546 => _546["genkit:metadata:subtype"]]));
22686
- const name = stringValue(_optionalChain([metadata, 'optionalAccess', _547 => _547.name]));
22772
+ const labels = isObject(_optionalChain([options, 'optionalAccess', _560 => _560.labels])) ? options.labels : void 0;
22773
+ const metadata = isObject(_optionalChain([options, 'optionalAccess', _561 => _561.metadata])) ? options.metadata : void 0;
22774
+ const actionType = stringValue(_optionalChain([labels, 'optionalAccess', _562 => _562["genkit:metadata:subtype"]]));
22775
+ const name = stringValue(_optionalChain([metadata, 'optionalAccess', _563 => _563.name]));
22687
22776
  if (!actionType || !name) {
22688
22777
  return void 0;
22689
22778
  }
22690
22779
  return {
22691
22780
  actionType,
22692
- key: stringValue(_optionalChain([labels, 'optionalAccess', _548 => _548["genkit:key"]])),
22781
+ key: stringValue(_optionalChain([labels, 'optionalAccess', _564 => _564["genkit:key"]])),
22693
22782
  name
22694
22783
  };
22695
22784
  }
22696
22785
  function extractActionSpanInput(args) {
22697
22786
  const options = extractRunInNewSpanOptions(args);
22698
- if (!isObject(_optionalChain([options, 'optionalAccess', _549 => _549.metadata]))) {
22787
+ if (!isObject(_optionalChain([options, 'optionalAccess', _565 => _565.metadata]))) {
22699
22788
  return void 0;
22700
22789
  }
22701
22790
  return options.metadata.input;
@@ -22708,7 +22797,7 @@ function shouldTraceAction(metadata, runStepName) {
22708
22797
  if (runStepName) {
22709
22798
  return true;
22710
22799
  }
22711
- switch (_optionalChain([metadata, 'optionalAccess', _550 => _550.actionType])) {
22800
+ switch (_optionalChain([metadata, 'optionalAccess', _566 => _566.actionType])) {
22712
22801
  case "model":
22713
22802
  case "background-model":
22714
22803
  case "embedder":
@@ -22718,8 +22807,8 @@ function shouldTraceAction(metadata, runStepName) {
22718
22807
  }
22719
22808
  }
22720
22809
  function actionSpanName(metadata, runStepName) {
22721
- const actionType = _optionalChain([metadata, 'optionalAccess', _551 => _551.actionType]);
22722
- const name = _optionalChain([metadata, 'optionalAccess', _552 => _552.name]);
22810
+ const actionType = _optionalChain([metadata, 'optionalAccess', _567 => _567.actionType]);
22811
+ const name = _optionalChain([metadata, 'optionalAccess', _568 => _568.name]);
22723
22812
  if (actionType && name) {
22724
22813
  return `genkit.${actionType}: ${name}`;
22725
22814
  }
@@ -22732,7 +22821,7 @@ function actionSpanName(metadata, runStepName) {
22732
22821
  return "genkit.action";
22733
22822
  }
22734
22823
  function actionSpanType(metadata) {
22735
- switch (_optionalChain([metadata, 'optionalAccess', _553 => _553.actionType])) {
22824
+ switch (_optionalChain([metadata, 'optionalAccess', _569 => _569.actionType])) {
22736
22825
  case "tool":
22737
22826
  case "tool.v2":
22738
22827
  return "tool" /* TOOL */;
@@ -22747,9 +22836,9 @@ function actionMetadataForLog(metadata, runStepName) {
22747
22836
  return {
22748
22837
  ...genkitProviderMetadata(),
22749
22838
  ...pickDefined({
22750
- "genkit.action_type": _optionalChain([metadata, 'optionalAccess', _554 => _554.actionType]),
22751
- "genkit.action_name": _optionalChain([metadata, 'optionalAccess', _555 => _555.name]),
22752
- "genkit.action_key": _optionalChain([metadata, 'optionalAccess', _556 => _556.key]),
22839
+ "genkit.action_type": _optionalChain([metadata, 'optionalAccess', _570 => _570.actionType]),
22840
+ "genkit.action_name": _optionalChain([metadata, 'optionalAccess', _571 => _571.name]),
22841
+ "genkit.action_key": _optionalChain([metadata, 'optionalAccess', _572 => _572.key]),
22753
22842
  "genkit.run_name": runStepName
22754
22843
  })
22755
22844
  };
@@ -23212,10 +23301,10 @@ function injectTracingHooks2(config, state) {
23212
23301
  const existingHooks = _nullishCoalesce(config.hooks, () => ( {}));
23213
23302
  const onSessionEnd = async (input, invocation) => {
23214
23303
  try {
23215
- await _optionalChain([existingHooks, 'access', _557 => _557.onSessionEnd, 'optionalCall', _558 => _558(input, invocation)]);
23304
+ await _optionalChain([existingHooks, 'access', _573 => _573.onSessionEnd, 'optionalCall', _574 => _574(input, invocation)]);
23216
23305
  } finally {
23217
23306
  handleSessionEnd(state, input.reason, input.error);
23218
- _optionalChain([state, 'access', _559 => _559.unsubscribeEvents, 'optionalCall', _560 => _560()]);
23307
+ _optionalChain([state, 'access', _575 => _575.unsubscribeEvents, 'optionalCall', _576 => _576()]);
23219
23308
  }
23220
23309
  };
23221
23310
  config.hooks = {
@@ -23254,7 +23343,7 @@ function makeSessionHandlers(sessionStates, configArgIndex, includeProviderMetad
23254
23343
  if (config.model) {
23255
23344
  metadata["github_copilot.model"] = config.model;
23256
23345
  }
23257
- if (includeProviderMetadata && _optionalChain([config, 'access', _561 => _561.provider, 'optionalAccess', _562 => _562.type])) {
23346
+ if (includeProviderMetadata && _optionalChain([config, 'access', _577 => _577.provider, 'optionalAccess', _578 => _578.type])) {
23258
23347
  metadata["github_copilot.provider_type"] = config.provider.type;
23259
23348
  }
23260
23349
  if (Object.keys(metadata).length > 0) {
@@ -23556,33 +23645,33 @@ function traceFlueOperation(channel2, args) {
23556
23645
  const run = () => {
23557
23646
  try {
23558
23647
  originalResult = args.run();
23559
- _optionalChain([tracingChannel2, 'access', _563 => _563.end, 'optionalAccess', _564 => _564.publish, 'call', _565 => _565(context)]);
23648
+ _optionalChain([tracingChannel2, 'access', _579 => _579.end, 'optionalAccess', _580 => _580.publish, 'call', _581 => _581(context)]);
23560
23649
  } catch (error) {
23561
23650
  context.error = normalizeError3(error);
23562
- _optionalChain([tracingChannel2, 'access', _566 => _566.error, 'optionalAccess', _567 => _567.publish, 'call', _568 => _568(context)]);
23563
- _optionalChain([tracingChannel2, 'access', _569 => _569.end, 'optionalAccess', _570 => _570.publish, 'call', _571 => _571(context)]);
23651
+ _optionalChain([tracingChannel2, 'access', _582 => _582.error, 'optionalAccess', _583 => _583.publish, 'call', _584 => _584(context)]);
23652
+ _optionalChain([tracingChannel2, 'access', _585 => _585.end, 'optionalAccess', _586 => _586.publish, 'call', _587 => _587(context)]);
23564
23653
  throw error;
23565
23654
  }
23566
23655
  traced2 = Promise.resolve(originalResult).then(
23567
23656
  (result) => {
23568
23657
  context.result = result;
23569
- _optionalChain([tracingChannel2, 'access', _572 => _572.asyncStart, 'optionalAccess', _573 => _573.publish, 'call', _574 => _574(context)]);
23570
- _optionalChain([tracingChannel2, 'access', _575 => _575.asyncEnd, 'optionalAccess', _576 => _576.publish, 'call', _577 => _577(context)]);
23658
+ _optionalChain([tracingChannel2, 'access', _588 => _588.asyncStart, 'optionalAccess', _589 => _589.publish, 'call', _590 => _590(context)]);
23659
+ _optionalChain([tracingChannel2, 'access', _591 => _591.asyncEnd, 'optionalAccess', _592 => _592.publish, 'call', _593 => _593(context)]);
23571
23660
  return result;
23572
23661
  },
23573
23662
  (error) => {
23574
23663
  context.error = normalizeError3(error);
23575
- _optionalChain([tracingChannel2, 'access', _578 => _578.error, 'optionalAccess', _579 => _579.publish, 'call', _580 => _580(context)]);
23576
- _optionalChain([tracingChannel2, 'access', _581 => _581.asyncStart, 'optionalAccess', _582 => _582.publish, 'call', _583 => _583(context)]);
23577
- _optionalChain([tracingChannel2, 'access', _584 => _584.asyncEnd, 'optionalAccess', _585 => _585.publish, 'call', _586 => _586(context)]);
23664
+ _optionalChain([tracingChannel2, 'access', _594 => _594.error, 'optionalAccess', _595 => _595.publish, 'call', _596 => _596(context)]);
23665
+ _optionalChain([tracingChannel2, 'access', _597 => _597.asyncStart, 'optionalAccess', _598 => _598.publish, 'call', _599 => _599(context)]);
23666
+ _optionalChain([tracingChannel2, 'access', _600 => _600.asyncEnd, 'optionalAccess', _601 => _601.publish, 'call', _602 => _602(context)]);
23578
23667
  throw error;
23579
23668
  }
23580
23669
  );
23581
23670
  };
23582
- if (_optionalChain([tracingChannel2, 'access', _587 => _587.start, 'optionalAccess', _588 => _588.runStores])) {
23671
+ if (_optionalChain([tracingChannel2, 'access', _603 => _603.start, 'optionalAccess', _604 => _604.runStores])) {
23583
23672
  tracingChannel2.start.runStores(context, run);
23584
23673
  } else {
23585
- _optionalChain([tracingChannel2, 'access', _589 => _589.start, 'optionalAccess', _590 => _590.publish, 'call', _591 => _591(context)]);
23674
+ _optionalChain([tracingChannel2, 'access', _605 => _605.start, 'optionalAccess', _606 => _606.publish, 'call', _607 => _607(context)]);
23586
23675
  run();
23587
23676
  }
23588
23677
  return { originalResult, traced: traced2 };
@@ -23729,7 +23818,7 @@ var FluePlugin = (_class22 = class extends BasePlugin {constructor(...args6) { s
23729
23818
  };
23730
23819
  tracingChannel2.subscribe(handlers);
23731
23820
  this.unsubscribers.push(() => {
23732
- _optionalChain([unbindCurrentSpanStore, 'optionalCall', _592 => _592()]);
23821
+ _optionalChain([unbindCurrentSpanStore, 'optionalCall', _608 => _608()]);
23733
23822
  tracingChannel2.unsubscribe(handlers);
23734
23823
  });
23735
23824
  }
@@ -23773,7 +23862,7 @@ var FluePlugin = (_class22 = class extends BasePlugin {constructor(...args6) { s
23773
23862
  };
23774
23863
  tracingChannel2.subscribe(handlers);
23775
23864
  this.unsubscribers.push(() => {
23776
- _optionalChain([unbindCurrentSpanStore, 'optionalCall', _593 => _593()]);
23865
+ _optionalChain([unbindCurrentSpanStore, 'optionalCall', _609 => _609()]);
23777
23866
  tracingChannel2.unsubscribe(handlers);
23778
23867
  });
23779
23868
  }
@@ -23804,7 +23893,7 @@ var FluePlugin = (_class22 = class extends BasePlugin {constructor(...args6) { s
23804
23893
  bindCurrentSpanStoreToOperationStart(tracingChannel2, ensureState2) {
23805
23894
  const state = _internalGetGlobalState();
23806
23895
  const startChannel = tracingChannel2.start;
23807
- const contextManager = _optionalChain([state, 'optionalAccess', _594 => _594.contextManager]);
23896
+ const contextManager = _optionalChain([state, 'optionalAccess', _610 => _610.contextManager]);
23808
23897
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
23809
23898
  if (!currentSpanStore || !startChannel) {
23810
23899
  return void 0;
@@ -23861,7 +23950,7 @@ var FluePlugin = (_class22 = class extends BasePlugin {constructor(...args6) { s
23861
23950
  };
23862
23951
  const metrics = {
23863
23952
  ...buildDurationMetrics3(state.startTime),
23864
- ...metricsFromUsage(_optionalChain([result, 'optionalAccess', _595 => _595.usage]))
23953
+ ...metricsFromUsage(_optionalChain([result, 'optionalAccess', _611 => _611.usage]))
23865
23954
  };
23866
23955
  safeLog3(state.span, {
23867
23956
  metadata,
@@ -24159,7 +24248,7 @@ var FluePlugin = (_class22 = class extends BasePlugin {constructor(...args6) { s
24159
24248
  }
24160
24249
  handleCompactionStart(event) {
24161
24250
  const operationState = this.operationStateForEvent(event);
24162
- const parent = _nullishCoalesce(_optionalChain([operationState, 'optionalAccess', _596 => _596.span]), () => ( this.parentSpanForEvent(event)));
24251
+ const parent = _nullishCoalesce(_optionalChain([operationState, 'optionalAccess', _612 => _612.span]), () => ( this.parentSpanForEvent(event)));
24163
24252
  const metadata = {
24164
24253
  ...extractEventMetadata(event),
24165
24254
  ...event.reason ? { "flue.compaction_reason": event.reason } : {},
@@ -24277,9 +24366,9 @@ var FluePlugin = (_class22 = class extends BasePlugin {constructor(...args6) { s
24277
24366
  }
24278
24367
  }
24279
24368
  if (event.taskId) {
24280
- return _optionalChain([this, 'access', _597 => _597.tasksById, 'access', _598 => _598.get, 'call', _599 => _599(event.taskId), 'optionalAccess', _600 => _600.span]);
24369
+ return _optionalChain([this, 'access', _613 => _613.tasksById, 'access', _614 => _614.get, 'call', _615 => _615(event.taskId), 'optionalAccess', _616 => _616.span]);
24281
24370
  }
24282
- return _optionalChain([this, 'access', _601 => _601.operationStateForEvent, 'call', _602 => _602(event), 'optionalAccess', _603 => _603.span]);
24371
+ return _optionalChain([this, 'access', _617 => _617.operationStateForEvent, 'call', _618 => _618(event), 'optionalAccess', _619 => _619.span]);
24283
24372
  }
24284
24373
  promotePendingOperationForEvent(event) {
24285
24374
  if (!event.operationId) {
@@ -24310,7 +24399,7 @@ var FluePlugin = (_class22 = class extends BasePlugin {constructor(...args6) { s
24310
24399
  activeOperationForEventScope(event) {
24311
24400
  for (const scope of operationScopeNames(event)) {
24312
24401
  const operations = this.activeOperationsByScope.get(scope);
24313
- if (_optionalChain([operations, 'optionalAccess', _604 => _604.length])) {
24402
+ if (_optionalChain([operations, 'optionalAccess', _620 => _620.length])) {
24314
24403
  return operations[operations.length - 1];
24315
24404
  }
24316
24405
  }
@@ -24329,7 +24418,7 @@ var FluePlugin = (_class22 = class extends BasePlugin {constructor(...args6) { s
24329
24418
  takePendingOperationForEvent(event) {
24330
24419
  const key = operationKey(event.session, event.operationKind);
24331
24420
  const queue2 = this.pendingOperationsByKey.get(key);
24332
- if (_optionalChain([queue2, 'optionalAccess', _605 => _605.length])) {
24421
+ if (_optionalChain([queue2, 'optionalAccess', _621 => _621.length])) {
24333
24422
  return queue2.shift();
24334
24423
  }
24335
24424
  for (const [candidateKey, candidateQueue] of this.pendingOperationsByKey) {
@@ -24353,7 +24442,7 @@ function isInstrumentedOperation(operation) {
24353
24442
  return operation === "prompt" || operation === "skill" || operation === "task" || operation === "compact";
24354
24443
  }
24355
24444
  function getSessionName(session) {
24356
- return typeof _optionalChain([session, 'optionalAccess', _606 => _606.name]) === "string" ? session.name : void 0;
24445
+ return typeof _optionalChain([session, 'optionalAccess', _622 => _622.name]) === "string" ? session.name : void 0;
24357
24446
  }
24358
24447
  function operationKey(sessionName, operation) {
24359
24448
  return `${_nullishCoalesce(sessionName, () => ( "unknown"))}::${operation}`;
@@ -24448,7 +24537,7 @@ function extractOperationInput(operation, args) {
24448
24537
  return args[0];
24449
24538
  case "skill":
24450
24539
  return {
24451
- args: _optionalChain([getOptionObject, 'call', _607 => _607(args[1]), 'optionalAccess', _608 => _608.args]),
24540
+ args: _optionalChain([getOptionObject, 'call', _623 => _623(args[1]), 'optionalAccess', _624 => _624.args]),
24452
24541
  name: args[0]
24453
24542
  };
24454
24543
  case "compact":
@@ -24459,16 +24548,16 @@ function extractOperationInputMetadata(operation, args) {
24459
24548
  const options = getOptionObject(args[1]);
24460
24549
  return {
24461
24550
  ...operation === "skill" && typeof args[0] === "string" ? { "flue.skill_name": args[0] } : {},
24462
- ..._optionalChain([options, 'optionalAccess', _609 => _609.model]) ? { model: options.model, "flue.model": options.model } : {},
24463
- ..._optionalChain([options, 'optionalAccess', _610 => _610.role]) ? { "flue.role": options.role } : {},
24464
- ..._optionalChain([options, 'optionalAccess', _611 => _611.thinkingLevel]) ? { "flue.thinking_level": options.thinkingLevel } : {},
24465
- ...typeof _optionalChain([options, 'optionalAccess', _612 => _612.cwd]) === "string" ? { "flue.cwd": options.cwd } : {},
24466
- ...Array.isArray(_optionalChain([options, 'optionalAccess', _613 => _613.tools])) ? {
24551
+ ..._optionalChain([options, 'optionalAccess', _625 => _625.model]) ? { model: options.model, "flue.model": options.model } : {},
24552
+ ..._optionalChain([options, 'optionalAccess', _626 => _626.role]) ? { "flue.role": options.role } : {},
24553
+ ..._optionalChain([options, 'optionalAccess', _627 => _627.thinkingLevel]) ? { "flue.thinking_level": options.thinkingLevel } : {},
24554
+ ...typeof _optionalChain([options, 'optionalAccess', _628 => _628.cwd]) === "string" ? { "flue.cwd": options.cwd } : {},
24555
+ ...Array.isArray(_optionalChain([options, 'optionalAccess', _629 => _629.tools])) ? {
24467
24556
  "flue.tools_count": options.tools.length,
24468
24557
  tools: summarizeTools(options.tools)
24469
24558
  } : {},
24470
- ...Array.isArray(_optionalChain([options, 'optionalAccess', _614 => _614.images])) ? { "flue.images_count": options.images.length } : {},
24471
- ..._optionalChain([options, 'optionalAccess', _615 => _615.result]) || _optionalChain([options, 'optionalAccess', _616 => _616.schema]) ? { "flue.result_schema": true } : {}
24559
+ ...Array.isArray(_optionalChain([options, 'optionalAccess', _630 => _630.images])) ? { "flue.images_count": options.images.length } : {},
24560
+ ..._optionalChain([options, 'optionalAccess', _631 => _631.result]) || _optionalChain([options, 'optionalAccess', _632 => _632.schema]) ? { "flue.result_schema": true } : {}
24472
24561
  };
24473
24562
  }
24474
24563
  function getOptionObject(value) {
@@ -24496,7 +24585,7 @@ function summarizeTools(tools) {
24496
24585
  });
24497
24586
  }
24498
24587
  function extractPromptResponseMetadata(result) {
24499
- const modelId = _optionalChain([result, 'optionalAccess', _617 => _617.model]) && typeof result.model.id === "string" ? result.model.id : void 0;
24588
+ const modelId = _optionalChain([result, 'optionalAccess', _633 => _633.model]) && typeof result.model.id === "string" ? result.model.id : void 0;
24500
24589
  return modelId ? {
24501
24590
  model: modelId,
24502
24591
  "flue.model": modelId
@@ -24516,12 +24605,12 @@ function extractOperationOutput(result) {
24516
24605
  }
24517
24606
  function metricsFromUsage(usage) {
24518
24607
  return {
24519
- ...typeof _optionalChain([usage, 'optionalAccess', _618 => _618.input]) === "number" ? { prompt_tokens: usage.input } : {},
24520
- ...typeof _optionalChain([usage, 'optionalAccess', _619 => _619.output]) === "number" ? { completion_tokens: usage.output } : {},
24521
- ...typeof _optionalChain([usage, 'optionalAccess', _620 => _620.cacheRead]) === "number" ? { prompt_cached_tokens: usage.cacheRead } : {},
24522
- ...typeof _optionalChain([usage, 'optionalAccess', _621 => _621.cacheWrite]) === "number" ? { prompt_cache_creation_tokens: usage.cacheWrite } : {},
24523
- ...typeof _optionalChain([usage, 'optionalAccess', _622 => _622.totalTokens]) === "number" ? { tokens: usage.totalTokens } : {},
24524
- ...typeof _optionalChain([usage, 'optionalAccess', _623 => _623.cost, 'optionalAccess', _624 => _624.total]) === "number" ? { estimated_cost: usage.cost.total } : {}
24608
+ ...typeof _optionalChain([usage, 'optionalAccess', _634 => _634.input]) === "number" ? { prompt_tokens: usage.input } : {},
24609
+ ...typeof _optionalChain([usage, 'optionalAccess', _635 => _635.output]) === "number" ? { completion_tokens: usage.output } : {},
24610
+ ...typeof _optionalChain([usage, 'optionalAccess', _636 => _636.cacheRead]) === "number" ? { prompt_cached_tokens: usage.cacheRead } : {},
24611
+ ...typeof _optionalChain([usage, 'optionalAccess', _637 => _637.cacheWrite]) === "number" ? { prompt_cache_creation_tokens: usage.cacheWrite } : {},
24612
+ ...typeof _optionalChain([usage, 'optionalAccess', _638 => _638.totalTokens]) === "number" ? { tokens: usage.totalTokens } : {},
24613
+ ...typeof _optionalChain([usage, 'optionalAccess', _639 => _639.cost, 'optionalAccess', _640 => _640.total]) === "number" ? { estimated_cost: usage.cost.total } : {}
24525
24614
  };
24526
24615
  }
24527
24616
  function buildDurationMetrics3(startTime) {
@@ -24556,7 +24645,7 @@ function toAssistantOutput(text, finishReason, reasoning, toolCalls) {
24556
24645
  content: text,
24557
24646
  ...reasoning ? { reasoning } : {},
24558
24647
  role: "assistant",
24559
- ..._optionalChain([toolCalls, 'optionalAccess', _625 => _625.length]) ? {
24648
+ ..._optionalChain([toolCalls, 'optionalAccess', _641 => _641.length]) ? {
24560
24649
  tool_calls: toolCalls.map((toolCall) => ({
24561
24650
  function: {
24562
24651
  arguments: toolCall.args === void 0 ? "{}" : JSON.stringify(toolCall.args),
@@ -24610,11 +24699,11 @@ var BraintrustLangChainCallbackHandler = (_class23 = class {
24610
24699
  __init82() {this.firstTokenTimes = /* @__PURE__ */ new Map()}
24611
24700
  __init83() {this.ttftMs = /* @__PURE__ */ new Map()}
24612
24701
  constructor(options) {;_class23.prototype.__init78.call(this);_class23.prototype.__init79.call(this);_class23.prototype.__init80.call(this);_class23.prototype.__init81.call(this);_class23.prototype.__init82.call(this);_class23.prototype.__init83.call(this);
24613
- this.parent = _optionalChain([options, 'optionalAccess', _626 => _626.parent]);
24702
+ this.parent = _optionalChain([options, 'optionalAccess', _642 => _642.parent]);
24614
24703
  this.options = {
24615
- debug: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _627 => _627.debug]), () => ( false)),
24616
- excludeMetadataProps: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _628 => _628.excludeMetadataProps]), () => ( /^(l[sc]_|langgraph_|__pregel_|checkpoint_ns)/)),
24617
- logger: _optionalChain([options, 'optionalAccess', _629 => _629.logger])
24704
+ debug: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _643 => _643.debug]), () => ( false)),
24705
+ excludeMetadataProps: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _644 => _644.excludeMetadataProps]), () => ( /^(l[sc]_|langgraph_|__pregel_|checkpoint_ns)/)),
24706
+ logger: _optionalChain([options, 'optionalAccess', _645 => _645.logger])
24618
24707
  };
24619
24708
  }
24620
24709
  startSpan({
@@ -24628,7 +24717,7 @@ var BraintrustLangChainCallbackHandler = (_class23 = class {
24628
24717
  if (!parentRunId) {
24629
24718
  this.rootRunId = runId;
24630
24719
  }
24631
- const tags = _optionalChain([args, 'access', _630 => _630.event, 'optionalAccess', _631 => _631.tags]);
24720
+ const tags = _optionalChain([args, 'access', _646 => _646.event, 'optionalAccess', _647 => _647.tags]);
24632
24721
  const spanAttributes = args.spanAttributes || {};
24633
24722
  spanAttributes.type = args.type || spanAttributes.type || "task";
24634
24723
  args.type = spanAttributes.type;
@@ -24648,7 +24737,7 @@ var BraintrustLangChainCallbackHandler = (_class23 = class {
24648
24737
  tags: void 0,
24649
24738
  metadata: {
24650
24739
  ...tags ? { tags } : {},
24651
- ..._optionalChain([args, 'access', _632 => _632.event, 'optionalAccess', _633 => _633.metadata]),
24740
+ ..._optionalChain([args, 'access', _648 => _648.event, 'optionalAccess', _649 => _649.metadata]),
24652
24741
  braintrust: {
24653
24742
  integration_name: "langchain-js",
24654
24743
  sdk_language: "javascript"
@@ -24750,7 +24839,7 @@ var BraintrustLangChainCallbackHandler = (_class23 = class {
24750
24839
  });
24751
24840
  }
24752
24841
  async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, runName) {
24753
- if (_optionalChain([tags, 'optionalAccess', _634 => _634.includes, 'call', _635 => _635("langsmith:hidden")])) {
24842
+ if (_optionalChain([tags, 'optionalAccess', _650 => _650.includes, 'call', _651 => _651("langsmith:hidden")])) {
24754
24843
  this.skippedRuns.add(runId);
24755
24844
  return;
24756
24845
  }
@@ -24860,7 +24949,7 @@ function getSerializedName(serialized) {
24860
24949
  if (typeof serialized.name === "string") {
24861
24950
  return serialized.name;
24862
24951
  }
24863
- const lastIdPart = _optionalChain([serialized, 'access', _636 => _636.id, 'optionalAccess', _637 => _637.at, 'call', _638 => _638(-1)]);
24952
+ const lastIdPart = _optionalChain([serialized, 'access', _652 => _652.id, 'optionalAccess', _653 => _653.at, 'call', _654 => _654(-1)]);
24864
24953
  return typeof lastIdPart === "string" ? lastIdPart : void 0;
24865
24954
  }
24866
24955
  function cleanObject(obj) {
@@ -25009,7 +25098,7 @@ function isCallbackManager(value) {
25009
25098
  return typeof maybeManager.addHandler === "function";
25010
25099
  }
25011
25100
  function hasBraintrustHandler(manager) {
25012
- return _nullishCoalesce(_optionalChain([manager, 'access', _639 => _639.handlers, 'optionalAccess', _640 => _640.some, 'call', _641 => _641((handler) => {
25101
+ return _nullishCoalesce(_optionalChain([manager, 'access', _655 => _655.handlers, 'optionalAccess', _656 => _656.some, 'call', _657 => _657((handler) => {
25013
25102
  if (typeof handler !== "object" || handler === null) {
25014
25103
  return false;
25015
25104
  }
@@ -25073,7 +25162,7 @@ var BraintrustPlugin = (_class25 = class extends BasePlugin {
25073
25162
  this.config = config;
25074
25163
  }
25075
25164
  onEnable() {
25076
- const integrations = this.config.integrations || {};
25165
+ const integrations = _nullishCoalesce(this.config.integrations, () => ( {}));
25077
25166
  if (integrations.openai !== false) {
25078
25167
  this.openaiPlugin = new OpenAIPlugin();
25079
25168
  this.openaiPlugin.enable();
@@ -25138,7 +25227,7 @@ var BraintrustPlugin = (_class25 = class extends BasePlugin {
25138
25227
  this.genkitPlugin = new GenkitPlugin();
25139
25228
  this.genkitPlugin.enable();
25140
25229
  }
25141
- if (getIntegrationConfig(integrations, "gitHubCopilot") !== false) {
25230
+ if (integrations.gitHubCopilot !== false) {
25142
25231
  this.gitHubCopilotPlugin = new GitHubCopilotPlugin();
25143
25232
  this.gitHubCopilotPlugin.enable();
25144
25233
  }
@@ -25251,6 +25340,7 @@ var envIntegrationAliases = {
25251
25340
  cursorsdk: "cursorSDK",
25252
25341
  flue: "flue",
25253
25342
  "flue-runtime": "flue",
25343
+ mastra: "mastra",
25254
25344
  "openai-agents": "openAIAgents",
25255
25345
  openaiagents: "openAIAgents",
25256
25346
  "openai-agents-core": "openAIAgents",
@@ -25293,6 +25383,7 @@ function getDefaultInstrumentationIntegrations() {
25293
25383
  cursor: true,
25294
25384
  cursorSDK: true,
25295
25385
  flue: true,
25386
+ mastra: true,
25296
25387
  openAIAgents: true,
25297
25388
  openrouter: true,
25298
25389
  openrouterAgent: true,
@@ -25317,6 +25408,9 @@ function readDisabledInstrumentationEnvConfig(disabledList) {
25317
25408
  }
25318
25409
  return { integrations };
25319
25410
  }
25411
+ function isInstrumentationIntegrationDisabled(integrations, ...names) {
25412
+ return names.some((name) => _optionalChain([integrations, 'optionalAccess', _658 => _658[name]]) === false);
25413
+ }
25320
25414
 
25321
25415
  // src/instrumentation/registry.ts
25322
25416
  var REGISTRY_STATE_KEY = /* @__PURE__ */ Symbol.for("braintrust.registry");
@@ -25410,12 +25504,318 @@ var PluginRegistry = (_class26 = class {constructor() { _class26.prototype.__ini
25410
25504
  }, _class26);
25411
25505
  var registry = new PluginRegistry();
25412
25506
 
25507
+ // src/auto-instrumentations/loader/mastra-observability-patch.ts
25508
+ var MASTRA_EXPORTER_FACTORY_GLOBAL = "__braintrustMastraExporterFactory";
25509
+ function installMastraExporterFactory(factory) {
25510
+ const globals = globalThis;
25511
+ globals[MASTRA_EXPORTER_FACTORY_GLOBAL] ??= factory;
25512
+ }
25513
+ var EXPORTER_FACTORY_KEY = JSON.stringify(MASTRA_EXPORTER_FACTORY_GLOBAL);
25514
+ var OBSERVABILITY_APPEND_BODY = `
25515
+ ;(function __braintrustWrapObservability() {
25516
+ // Top-level so we can both read and reassign the var binding the original
25517
+ // entry declared.
25518
+ if (typeof Observability === "undefined") return;
25519
+ if (Observability.__braintrustWrapped) return;
25520
+ function __braintrustEnsureExporter(rawConfig) {
25521
+ try {
25522
+ var factory = globalThis[${EXPORTER_FACTORY_KEY}];
25523
+ if (typeof factory !== "function") return rawConfig;
25524
+ var config = rawConfig && typeof rawConfig === "object" ? rawConfig : {};
25525
+ var configsIn = config.configs && typeof config.configs === "object" ? config.configs : null;
25526
+ var configsOut = {};
25527
+ var hadEntries = false;
25528
+ if (configsIn) {
25529
+ for (var name in configsIn) {
25530
+ if (!Object.prototype.hasOwnProperty.call(configsIn, name)) continue;
25531
+ hadEntries = true;
25532
+ var inst = configsIn[name] || {};
25533
+ var existing = Array.isArray(inst.exporters) ? inst.exporters : [];
25534
+ var hasOurs = existing.some(function (e) { return e && e.name === "braintrust"; });
25535
+ configsOut[name] = Object.assign({}, inst, {
25536
+ exporters: hasOurs ? existing : existing.concat([factory()]),
25537
+ });
25538
+ }
25539
+ }
25540
+ if (!hadEntries) {
25541
+ configsOut.default = {
25542
+ serviceName: "mastra",
25543
+ exporters: [factory()],
25544
+ };
25545
+ }
25546
+ return Object.assign({}, config, { configs: configsOut });
25547
+ } catch (e) {
25548
+ return rawConfig;
25549
+ }
25550
+ }
25551
+ var __OriginalObservability = Observability;
25552
+ Observability = new Proxy(__OriginalObservability, {
25553
+ construct: function (target, args, newTarget) {
25554
+ var nextArgs = args.slice();
25555
+ nextArgs[0] = __braintrustEnsureExporter(nextArgs[0]);
25556
+ return Reflect.construct(target, nextArgs, newTarget);
25557
+ },
25558
+ });
25559
+ Observability.__braintrustWrapped = true;
25560
+ if (typeof exports !== "undefined" && exports && typeof exports === "object") {
25561
+ try {
25562
+ Object.defineProperty(exports, "Observability", {
25563
+ enumerable: true,
25564
+ configurable: true,
25565
+ get: function () { return Observability; },
25566
+ });
25567
+ } catch (e) {}
25568
+ }
25569
+ })();
25570
+ `;
25571
+
25572
+ // src/wrappers/mastra.ts
25573
+ var MASTRA_BRAINTRUST_EXPORTER_NAME = "braintrust";
25574
+ var SPAN_TYPE_MAP = {
25575
+ agent_run: "task" /* TASK */,
25576
+ model_generation: "llm" /* LLM */,
25577
+ model_step: "llm" /* LLM */,
25578
+ model_chunk: "llm" /* LLM */,
25579
+ tool_call: "tool" /* TOOL */,
25580
+ mcp_tool_call: "tool" /* TOOL */,
25581
+ workflow_run: "task" /* TASK */,
25582
+ workflow_step: "function" /* FUNCTION */,
25583
+ workflow_conditional: "function" /* FUNCTION */,
25584
+ workflow_conditional_eval: "function" /* FUNCTION */,
25585
+ workflow_parallel: "function" /* FUNCTION */,
25586
+ workflow_loop: "function" /* FUNCTION */,
25587
+ workflow_sleep: "function" /* FUNCTION */,
25588
+ workflow_wait_event: "function" /* FUNCTION */,
25589
+ memory_operation: "function" /* FUNCTION */,
25590
+ workspace_action: "function" /* FUNCTION */,
25591
+ rag_ingestion: "task" /* TASK */,
25592
+ rag_embedding: "llm" /* LLM */,
25593
+ rag_vector_operation: "function" /* FUNCTION */,
25594
+ rag_action: "function" /* FUNCTION */,
25595
+ graph_action: "function" /* FUNCTION */,
25596
+ scorer_run: "score" /* SCORE */,
25597
+ scorer_step: "score" /* SCORE */,
25598
+ processor_run: "function" /* FUNCTION */,
25599
+ generic: "function" /* FUNCTION */
25600
+ };
25601
+ function spanTypeFor(mastraType) {
25602
+ return _nullishCoalesce(SPAN_TYPE_MAP[mastraType], () => ( "function")) /* FUNCTION */;
25603
+ }
25604
+ function epochSeconds(value) {
25605
+ if (value === void 0) return void 0;
25606
+ const ms = value instanceof Date ? value.getTime() : typeof value === "number" ? value : Date.parse(value);
25607
+ return Number.isFinite(ms) ? ms / 1e3 : void 0;
25608
+ }
25609
+ function modelMetrics(attributes) {
25610
+ if (!isObject(attributes)) return void 0;
25611
+ const usage = isObject(attributes.usage) ? attributes.usage : void 0;
25612
+ if (!usage) return void 0;
25613
+ const out = {};
25614
+ if (typeof usage.inputTokens === "number")
25615
+ out.prompt_tokens = usage.inputTokens;
25616
+ if (typeof usage.outputTokens === "number")
25617
+ out.completion_tokens = usage.outputTokens;
25618
+ if (typeof usage.inputTokens === "number" && typeof usage.outputTokens === "number") {
25619
+ out.tokens = usage.inputTokens + usage.outputTokens;
25620
+ }
25621
+ const inputDetails = isObject(usage.inputDetails) ? usage.inputDetails : void 0;
25622
+ const outputDetails = isObject(usage.outputDetails) ? usage.outputDetails : void 0;
25623
+ if (inputDetails && typeof inputDetails.cacheRead === "number") {
25624
+ out.prompt_cached_tokens = inputDetails.cacheRead;
25625
+ }
25626
+ if (inputDetails && typeof inputDetails.cacheWrite === "number") {
25627
+ out.prompt_cache_creation_tokens = inputDetails.cacheWrite;
25628
+ }
25629
+ if (outputDetails && typeof outputDetails.reasoning === "number") {
25630
+ out.completion_reasoning_tokens = outputDetails.reasoning;
25631
+ }
25632
+ return Object.keys(out).length > 0 ? out : void 0;
25633
+ }
25634
+ function buildMetadata(exported) {
25635
+ const out = {};
25636
+ if (exported.entityId !== void 0) out.entity_id = exported.entityId;
25637
+ if (exported.entityName !== void 0) out.entity_name = exported.entityName;
25638
+ if (exported.entityType !== void 0) out.entity_type = exported.entityType;
25639
+ if (exported.metadata && isObject(exported.metadata)) {
25640
+ Object.assign(out, exported.metadata);
25641
+ }
25642
+ if (exported.attributes && isObject(exported.attributes)) {
25643
+ for (const [key, value] of Object.entries(exported.attributes)) {
25644
+ if (key === "usage") continue;
25645
+ if (value !== void 0) out[key] = value;
25646
+ }
25647
+ }
25648
+ if (exported.tags && exported.tags.length > 0) {
25649
+ out.tags = exported.tags;
25650
+ }
25651
+ if (exported.requestContext && isObject(exported.requestContext)) {
25652
+ out.request_context = exported.requestContext;
25653
+ }
25654
+ return out;
25655
+ }
25656
+ var BraintrustObservabilityExporter = (_class27 = class {
25657
+ __init107() {this.name = MASTRA_BRAINTRUST_EXPORTER_NAME}
25658
+ __init108() {this.spans = /* @__PURE__ */ new Map()}
25659
+ // Captured at the first SPAN_STARTED event. Mastra's observability bus may
25660
+ // dispatch later events outside the user's AsyncLocalStorage context, where
25661
+ // `currentSpan()` returns NOOP_SPAN — which would make our `startSpan()`
25662
+ // calls go to a no-op logger and silently drop. Anchoring on the parent
25663
+ // we observe while still in-context keeps the whole Mastra subtree under
25664
+ // the user's traced scenario.
25665
+
25666
+ constructor() {;_class27.prototype.__init107.call(this);_class27.prototype.__init108.call(this);
25667
+ _internalSetInitialState();
25668
+ }
25669
+ async exportTracingEvent(event) {
25670
+ const exported = event.exportedSpan;
25671
+ if (exported.isInternal === true) return;
25672
+ try {
25673
+ switch (event.type) {
25674
+ case "span_started":
25675
+ this.onStart(exported);
25676
+ break;
25677
+ case "span_updated":
25678
+ this.onUpdate(exported);
25679
+ break;
25680
+ case "span_ended":
25681
+ this.onEnd(exported);
25682
+ break;
25683
+ }
25684
+ } catch (err) {
25685
+ logExporterError(err);
25686
+ }
25687
+ }
25688
+ async flush() {
25689
+ const state = _internalGetGlobalState();
25690
+ if (state) {
25691
+ await state.bgLogger().flush();
25692
+ }
25693
+ }
25694
+ async shutdown() {
25695
+ await this.flush();
25696
+ this.spans.clear();
25697
+ }
25698
+ onStart(exported) {
25699
+ if (this.spans.has(exported.id)) return;
25700
+ const args = {
25701
+ name: exported.name,
25702
+ spanAttributes: { type: spanTypeFor(exported.type) },
25703
+ startTime: epochSeconds(exported.startTime)
25704
+ };
25705
+ const parentRecord = exported.parentSpanId ? this.spans.get(exported.parentSpanId) : void 0;
25706
+ if (!this.capturedParent) {
25707
+ const probe = currentSpan();
25708
+ if (probe && probe.spanId) {
25709
+ this.capturedParent = probe;
25710
+ }
25711
+ }
25712
+ const span = parentRecord ? parentRecord.span.startSpan(args) : this.capturedParent ? this.capturedParent.startSpan(args) : startSpan(args);
25713
+ const record = { span, hasLoggedInput: false };
25714
+ this.logPayload(record, exported);
25715
+ this.spans.set(exported.id, record);
25716
+ if (exported.isEvent === true) {
25717
+ span.end({ endTime: args.startTime });
25718
+ this.spans.delete(exported.id);
25719
+ }
25720
+ }
25721
+ onUpdate(exported) {
25722
+ const record = this.spans.get(exported.id);
25723
+ if (!record) return;
25724
+ this.logPayload(record, exported);
25725
+ }
25726
+ onEnd(exported) {
25727
+ const record = this.spans.get(exported.id);
25728
+ if (!record) return;
25729
+ this.logPayload(record, exported);
25730
+ if (exported.errorInfo) {
25731
+ record.span.log({
25732
+ error: exported.errorInfo.message || exported.errorInfo.name || "Unknown Mastra error"
25733
+ });
25734
+ }
25735
+ record.span.end({ endTime: epochSeconds(exported.endTime) });
25736
+ this.spans.delete(exported.id);
25737
+ }
25738
+ logPayload(record, exported) {
25739
+ const event = {};
25740
+ if (exported.input !== void 0) {
25741
+ event.input = exported.input;
25742
+ record.hasLoggedInput = true;
25743
+ }
25744
+ if (exported.output !== void 0) {
25745
+ event.output = exported.output;
25746
+ }
25747
+ const metadata = buildMetadata(exported);
25748
+ if (Object.keys(metadata).length > 0) {
25749
+ event.metadata = metadata;
25750
+ }
25751
+ const metrics = modelMetrics(exported.attributes);
25752
+ if (metrics) {
25753
+ event.metrics = metrics;
25754
+ }
25755
+ if (Object.keys(event).length > 0) {
25756
+ record.span.log(event);
25757
+ }
25758
+ }
25759
+ }, _class27);
25760
+ function logExporterError(err) {
25761
+ debugLogger.warn("Mastra exporter failure:", err);
25762
+ }
25763
+
25413
25764
  // src/node/config.ts
25765
+ var BRAINTRUST_ENV_SEARCH_PARENT_LIMIT = 64;
25414
25766
  function configureNode() {
25415
25767
  isomorph_default.buildType = "node";
25416
25768
  isomorph_default.getRepoInfo = getRepoInfo;
25417
25769
  isomorph_default.getPastNAncestors = getPastNAncestors;
25418
- isomorph_default.getEnv = (name) => process.env[name];
25770
+ isomorph_default.getEnv = (name) => {
25771
+ const value = process.env[name];
25772
+ return name === "BRAINTRUST_API_KEY" && !_optionalChain([value, 'optionalAccess', _659 => _659.trim, 'call', _660 => _660()]) ? void 0 : value;
25773
+ };
25774
+ isomorph_default.getBraintrustApiKey = async () => {
25775
+ const value = process.env.BRAINTRUST_API_KEY;
25776
+ if (_optionalChain([value, 'optionalAccess', _661 => _661.trim, 'call', _662 => _662()])) {
25777
+ return value;
25778
+ }
25779
+ const envPaths = [];
25780
+ for (let dir2 = process.cwd(), depth = 0; depth <= BRAINTRUST_ENV_SEARCH_PARENT_LIMIT; dir2 = path.dirname(dir2), depth++) {
25781
+ envPaths.push(path.join(dir2, ".env.braintrust"));
25782
+ if (path.dirname(dir2) === dir2) {
25783
+ break;
25784
+ }
25785
+ }
25786
+ const pending = /* @__PURE__ */ new Map();
25787
+ envPaths.forEach((envPath, index) => {
25788
+ pending.set(
25789
+ index,
25790
+ fs.readFile(envPath, "utf8").then(
25791
+ (contents) => ({ contents, envPath, index }),
25792
+ (error) => ({ error, envPath, index })
25793
+ )
25794
+ );
25795
+ });
25796
+ const results = [];
25797
+ let nearestUnresolvedIndex = 0;
25798
+ while (pending.size > 0) {
25799
+ const result = await Promise.race(pending.values());
25800
+ pending.delete(result.index);
25801
+ results[result.index] = result;
25802
+ while (results[nearestUnresolvedIndex]) {
25803
+ const nearestResult = results[nearestUnresolvedIndex];
25804
+ if ("contents" in nearestResult) {
25805
+ const parsed = dotenv.parse(nearestResult.contents);
25806
+ const apiKey = parsed.BRAINTRUST_API_KEY;
25807
+ return _optionalChain([apiKey, 'optionalAccess', _663 => _663.trim, 'call', _664 => _664()]) ? apiKey : void 0;
25808
+ }
25809
+ const e = nearestResult.error;
25810
+ if (typeof e === "object" && e !== null && "code" in e && e.code === "ENOENT") {
25811
+ nearestUnresolvedIndex++;
25812
+ continue;
25813
+ }
25814
+ return void 0;
25815
+ }
25816
+ }
25817
+ return void 0;
25818
+ };
25419
25819
  isomorph_default.getCallerLocation = getCallerLocation;
25420
25820
  isomorph_default.newAsyncLocalStorage = () => new (0, _nodeasync_hooks.AsyncLocalStorage)();
25421
25821
  isomorph_default.newTracingChannel = (nameOrChannels) => diagnostics_channel.tracingChannel(nameOrChannels);
@@ -25446,6 +25846,12 @@ function configureNode() {
25446
25846
  isomorph_default.gunzip = _nodeutil.promisify.call(void 0, zlib.gunzip);
25447
25847
  isomorph_default.hash = (data) => crypto.createHash("sha256").update(data).digest("hex");
25448
25848
  _internalSetInitialState();
25849
+ const disabled = readDisabledInstrumentationEnvConfig(
25850
+ isomorph_default.getEnv("BRAINTRUST_DISABLE_INSTRUMENTATION")
25851
+ ).integrations;
25852
+ if (!isInstrumentationIntegrationDisabled(disabled, "mastra")) {
25853
+ installMastraExporterFactory(() => new BraintrustObservabilityExporter());
25854
+ }
25449
25855
  registry.enable();
25450
25856
  }
25451
25857
 
@@ -26570,8 +26976,12 @@ async function invoke(args) {
26570
26976
 
26571
26977
  // src/trace.ts
26572
26978
  var SpanFetcher = class _SpanFetcher extends ObjectFetcher {
26573
- constructor(objectType, _objectId, rootSpanId, _state, spanTypeFilter) {
26574
- const filterExpr = _SpanFetcher.buildFilter(rootSpanId, spanTypeFilter);
26979
+ constructor(objectType, _objectId, rootSpanId, _state, spanTypeFilter, includeScorers = false) {
26980
+ const filterExpr = _SpanFetcher.buildFilter(
26981
+ rootSpanId,
26982
+ spanTypeFilter,
26983
+ includeScorers
26984
+ );
26575
26985
  super(objectType, void 0, void 0, {
26576
26986
  filter: filterExpr
26577
26987
  });
@@ -26580,16 +26990,17 @@ var SpanFetcher = class _SpanFetcher extends ObjectFetcher {
26580
26990
  this._state = _state;
26581
26991
  this.spanTypeFilter = spanTypeFilter;
26582
26992
  }
26583
- static buildFilter(rootSpanId, spanTypeFilter) {
26993
+ static buildFilter(rootSpanId, spanTypeFilter, includeScorers = false) {
26584
26994
  const children = [
26585
26995
  // Base filter: root_span_id = 'value'
26586
26996
  {
26587
26997
  op: "eq",
26588
26998
  left: { op: "ident", name: ["root_span_id"] },
26589
26999
  right: { op: "literal", value: rootSpanId }
26590
- },
26591
- // Exclude span_attributes.purpose = 'score'
26592
- {
27000
+ }
27001
+ ];
27002
+ if (!includeScorers) {
27003
+ children.push({
26593
27004
  op: "or",
26594
27005
  children: [
26595
27006
  {
@@ -26602,8 +27013,8 @@ var SpanFetcher = class _SpanFetcher extends ObjectFetcher {
26602
27013
  right: { op: "literal", value: "scorer" }
26603
27014
  }
26604
27015
  ]
26605
- }
26606
- ];
27016
+ });
27017
+ }
26607
27018
  if (spanTypeFilter && spanTypeFilter.length > 0) {
26608
27019
  children.push({
26609
27020
  op: "in",
@@ -26623,41 +27034,55 @@ var SpanFetcher = class _SpanFetcher extends ObjectFetcher {
26623
27034
  return this._state;
26624
27035
  }
26625
27036
  };
26626
- var CachedSpanFetcher = (_class27 = class {
26627
- __init107() {this.spanCache = /* @__PURE__ */ new Map()}
26628
- __init108() {this.allFetched = false}
27037
+ var CachedSpanFetcher = (_class28 = class {
27038
+ __init109() {this.spanCache = /* @__PURE__ */ new Map()}
27039
+ __init110() {this.allFetched = false}
26629
27040
 
26630
- constructor(objectTypeOrFetchFn, objectId, rootSpanId, getState) {;_class27.prototype.__init107.call(this);_class27.prototype.__init108.call(this);
27041
+ constructor(objectTypeOrFetchFn, objectId, rootSpanId, getState) {;_class28.prototype.__init109.call(this);_class28.prototype.__init110.call(this);
26631
27042
  if (typeof objectTypeOrFetchFn === "function") {
26632
- this.fetchFn = objectTypeOrFetchFn;
27043
+ this.fetchFn = (spanType) => objectTypeOrFetchFn(spanType);
26633
27044
  } else {
26634
27045
  const objectType = objectTypeOrFetchFn;
26635
- this.fetchFn = async (spanType) => {
27046
+ this.fetchFn = async (spanType, includeScorers) => {
26636
27047
  const state = await getState();
26637
27048
  const fetcher = new SpanFetcher(
26638
27049
  objectType,
26639
27050
  objectId,
26640
27051
  rootSpanId,
26641
27052
  state,
26642
- spanType
27053
+ spanType,
27054
+ includeScorers
26643
27055
  );
26644
27056
  const rows = await fetcher.fetchedData();
26645
- return rows.filter((row) => _optionalChain([row, 'access', _642 => _642.span_attributes, 'optionalAccess', _643 => _643.purpose]) !== "scorer").map((row) => ({
27057
+ return rows.map((row) => ({
26646
27058
  input: row.input,
26647
27059
  output: row.output,
27060
+ expected: row.expected,
27061
+ error: row.error,
27062
+ scores: row.scores,
27063
+ metrics: row.metrics,
26648
27064
  metadata: row.metadata,
26649
27065
  span_id: row.span_id,
26650
27066
  span_parents: row.span_parents,
27067
+ is_root: row.is_root,
26651
27068
  span_attributes: row.span_attributes,
26652
27069
  id: row.id,
26653
27070
  _xact_id: row._xact_id,
26654
27071
  _pagination_key: row._pagination_key,
26655
- root_span_id: row.root_span_id
27072
+ root_span_id: row.root_span_id,
27073
+ created: row.created,
27074
+ tags: row.tags
26656
27075
  }));
26657
27076
  };
26658
27077
  }
26659
27078
  }
26660
- async getSpans({ spanType } = {}) {
27079
+ async getSpans({
27080
+ spanType,
27081
+ includeScorers = false
27082
+ } = {}) {
27083
+ if (includeScorers) {
27084
+ return this.fetchFn(spanType, true);
27085
+ }
26661
27086
  if (this.allFetched) {
26662
27087
  return this.getFromCache(spanType);
26663
27088
  }
@@ -26674,9 +27099,9 @@ var CachedSpanFetcher = (_class27 = class {
26674
27099
  return this.getFromCache(spanType);
26675
27100
  }
26676
27101
  async fetchSpans(spanType) {
26677
- const spans = await this.fetchFn(spanType);
27102
+ const spans = await this.fetchFn(spanType, false);
26678
27103
  for (const span of spans) {
26679
- const type = _nullishCoalesce(_optionalChain([span, 'access', _644 => _644.span_attributes, 'optionalAccess', _645 => _645.type]), () => ( ""));
27104
+ const type = _nullishCoalesce(_optionalChain([span, 'access', _665 => _665.span_attributes, 'optionalAccess', _666 => _666.type]), () => ( ""));
26680
27105
  const existing = _nullishCoalesce(this.spanCache.get(type), () => ( []));
26681
27106
  existing.push(span);
26682
27107
  this.spanCache.set(type, existing);
@@ -26693,24 +27118,24 @@ var CachedSpanFetcher = (_class27 = class {
26693
27118
  }
26694
27119
  return result;
26695
27120
  }
26696
- }, _class27);
26697
- var LocalTrace = (_class28 = class {
27121
+ }, _class28);
27122
+ var LocalTrace = (_class29 = class {
26698
27123
 
26699
27124
 
26700
27125
 
26701
27126
 
26702
27127
 
26703
- __init109() {this.spansFlushed = false}
26704
- __init110() {this.spansFlushPromise = null}
27128
+ __init111() {this.spansFlushed = false}
27129
+ __init112() {this.spansFlushPromise = null}
26705
27130
 
26706
- __init111() {this.threadCache = /* @__PURE__ */ new Map()}
27131
+ __init113() {this.threadCache = /* @__PURE__ */ new Map()}
26707
27132
  constructor({
26708
27133
  objectType,
26709
27134
  objectId,
26710
27135
  rootSpanId,
26711
27136
  ensureSpansFlushed,
26712
27137
  state
26713
- }) {;_class28.prototype.__init109.call(this);_class28.prototype.__init110.call(this);_class28.prototype.__init111.call(this);
27138
+ }) {;_class29.prototype.__init111.call(this);_class29.prototype.__init112.call(this);_class29.prototype.__init113.call(this);
26714
27139
  this.objectType = objectType;
26715
27140
  this.objectId = objectId;
26716
27141
  this.rootSpanId = rootSpanId;
@@ -26752,34 +27177,43 @@ var LocalTrace = (_class28 = class {
26752
27177
  * First checks the local span cache for recently logged spans, then falls
26753
27178
  * back to CachedSpanFetcher which handles BTQL fetching and caching.
26754
27179
  */
26755
- async getSpans({ spanType } = {}) {
27180
+ async getSpans({
27181
+ spanType,
27182
+ includeScorers = false
27183
+ } = {}) {
26756
27184
  const cachedSpans = this.state.spanCache.getByRootSpanId(this.rootSpanId);
26757
27185
  if (cachedSpans && cachedSpans.length > 0) {
26758
- let spans = cachedSpans.filter(
26759
- (span) => _optionalChain([span, 'access', _646 => _646.span_attributes, 'optionalAccess', _647 => _647.purpose]) !== "scorer"
27186
+ let spans = includeScorers ? cachedSpans : cachedSpans.filter(
27187
+ (span) => _optionalChain([span, 'access', _667 => _667.span_attributes, 'optionalAccess', _668 => _668.purpose]) !== "scorer"
26760
27188
  );
26761
27189
  if (spanType && spanType.length > 0) {
26762
27190
  spans = spans.filter(
26763
- (span) => spanType.includes(_nullishCoalesce(_optionalChain([span, 'access', _648 => _648.span_attributes, 'optionalAccess', _649 => _649.type]), () => ( "")))
27191
+ (span) => spanType.includes(_nullishCoalesce(_optionalChain([span, 'access', _669 => _669.span_attributes, 'optionalAccess', _670 => _670.type]), () => ( "")))
26764
27192
  );
26765
27193
  }
26766
27194
  return spans.map((span) => ({
26767
27195
  input: span.input,
26768
27196
  output: span.output,
27197
+ expected: span.expected,
27198
+ error: span.error,
27199
+ scores: span.scores,
27200
+ metrics: span.metrics,
26769
27201
  metadata: span.metadata,
26770
27202
  span_id: span.span_id,
26771
27203
  span_parents: span.span_parents,
26772
- span_attributes: span.span_attributes
27204
+ is_root: span.is_root,
27205
+ span_attributes: span.span_attributes,
27206
+ tags: span.tags
26773
27207
  }));
26774
27208
  }
26775
- return this.cachedFetcher.getSpans({ spanType });
27209
+ return this.cachedFetcher.getSpans({ spanType, includeScorers });
26776
27210
  }
26777
27211
  /**
26778
27212
  * Get the thread (preprocessed messages) for this trace.
26779
27213
  * Calls the API with the project_default preprocessor (which falls back to "thread").
26780
27214
  */
26781
27215
  async getThread(options) {
26782
- const cacheKey = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _650 => _650.preprocessor]), () => ( "project_default"));
27216
+ const cacheKey = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _671 => _671.preprocessor]), () => ( "project_default"));
26783
27217
  if (!this.threadCache.has(cacheKey)) {
26784
27218
  const promise = this.fetchThread(options);
26785
27219
  this.threadCache.set(cacheKey, promise);
@@ -26790,7 +27224,7 @@ var LocalTrace = (_class28 = class {
26790
27224
  await this.ensureSpansReady();
26791
27225
  await this.state.login({});
26792
27226
  const result = await invoke({
26793
- globalFunction: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _651 => _651.preprocessor]), () => ( "project_default")),
27227
+ globalFunction: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _672 => _672.preprocessor]), () => ( "project_default")),
26794
27228
  functionType: "preprocessor",
26795
27229
  input: {
26796
27230
  trace_ref: {
@@ -26821,7 +27255,7 @@ var LocalTrace = (_class28 = class {
26821
27255
  }
26822
27256
  await this.spansFlushPromise;
26823
27257
  }
26824
- }, _class28);
27258
+ }, _class29);
26825
27259
 
26826
27260
  // src/reporters/progress.ts
26827
27261
  var SimpleProgressReporter = class {
@@ -26966,10 +27400,10 @@ function validateParametersWithJsonSchema(parameters, schema) {
26966
27400
  const ajv = new (0, _ajv2.default)({ coerceTypes: true, useDefaults: true, strict: false });
26967
27401
  const validate = ajv.compile(schema);
26968
27402
  if (!validate(parameters)) {
26969
- const errorMessages = _optionalChain([validate, 'access', _652 => _652.errors, 'optionalAccess', _653 => _653.map, 'call', _654 => _654((err) => {
27403
+ const errorMessages = _optionalChain([validate, 'access', _673 => _673.errors, 'optionalAccess', _674 => _674.map, 'call', _675 => _675((err) => {
26970
27404
  const path2 = err.instancePath || "root";
26971
27405
  return `${path2}: ${err.message}`;
26972
- }), 'access', _655 => _655.join, 'call', _656 => _656(", ")]);
27406
+ }), 'access', _676 => _676.join, 'call', _677 => _677(", ")]);
26973
27407
  throw Error(`Invalid parameters: ${errorMessages}`);
26974
27408
  }
26975
27409
  return rehydrateRemoteParameters(parameters, schema);
@@ -27309,7 +27743,7 @@ async function runEvaluator(experiment, evaluator, progressReporter, filters, st
27309
27743
  }
27310
27744
  async function runEvaluatorInternal(experiment, evaluator, progressReporter, filters, stream, parameters, collectResults, enableCache) {
27311
27745
  if (enableCache) {
27312
- _optionalChain([(_nullishCoalesce(evaluator.state, () => ( _internalGetGlobalState()))), 'optionalAccess', _657 => _657.spanCache, 'optionalAccess', _658 => _658.start, 'call', _659 => _659()]);
27746
+ _optionalChain([(_nullishCoalesce(evaluator.state, () => ( _internalGetGlobalState()))), 'optionalAccess', _678 => _678.spanCache, 'optionalAccess', _679 => _679.start, 'call', _680 => _680()]);
27313
27747
  }
27314
27748
  try {
27315
27749
  if (typeof evaluator.data === "string") {
@@ -27420,7 +27854,7 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
27420
27854
  objectType: parentComponents ? spanObjectTypeV3ToTypedString(
27421
27855
  parentComponents.data.object_type
27422
27856
  ) : "experiment",
27423
- objectId: await _asyncNullishCoalesce(await _asyncOptionalChain([parentComponents, 'optionalAccess', async _660 => _660.data, 'access', async _661 => _661.object_id]), async () => ( (experimentIdPromise ? await _asyncNullishCoalesce(await experimentIdPromise, async () => ( "")) : ""))),
27857
+ objectId: await _asyncNullishCoalesce(await _asyncOptionalChain([parentComponents, 'optionalAccess', async _681 => _681.data, 'access', async _682 => _682.object_id]), async () => ( (experimentIdPromise ? await _asyncNullishCoalesce(await experimentIdPromise, async () => ( "")) : ""))),
27424
27858
  rootSpanId: rootSpan.rootSpanId,
27425
27859
  ensureSpansFlushed,
27426
27860
  state
@@ -27450,10 +27884,10 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
27450
27884
  span,
27451
27885
  parameters: _nullishCoalesce(parameters, () => ( {})),
27452
27886
  reportProgress: (event) => {
27453
- _optionalChain([stream, 'optionalCall', _662 => _662({
27887
+ _optionalChain([stream, 'optionalCall', _683 => _683({
27454
27888
  ...event,
27455
27889
  id: rootSpan.id,
27456
- origin: _optionalChain([baseEvent, 'access', _663 => _663.event, 'optionalAccess', _664 => _664.origin]),
27890
+ origin: _optionalChain([baseEvent, 'access', _684 => _684.event, 'optionalAccess', _685 => _685.origin]),
27457
27891
  name: evaluator.evalName,
27458
27892
  object_type: "task"
27459
27893
  })]);
@@ -27641,7 +28075,7 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
27641
28075
  tags: tags.length ? tags : void 0,
27642
28076
  metadata,
27643
28077
  error,
27644
- origin: _optionalChain([baseEvent, 'access', _665 => _665.event, 'optionalAccess', _666 => _666.origin])
28078
+ origin: _optionalChain([baseEvent, 'access', _686 => _686.event, 'optionalAccess', _687 => _687.origin])
27645
28079
  };
27646
28080
  collectedResults.push({
27647
28081
  ...baseResult,
@@ -27681,7 +28115,7 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
27681
28115
  break;
27682
28116
  }
27683
28117
  scheduledTrials++;
27684
- _optionalChain([progressReporter, 'access', _667 => _667.setTotal, 'optionalCall', _668 => _668(evaluator.evalName, scheduledTrials)]);
28118
+ _optionalChain([progressReporter, 'access', _688 => _688.setTotal, 'optionalCall', _689 => _689(evaluator.evalName, scheduledTrials)]);
27685
28119
  q.pushAsync({ datum, trialIndex }).catch((e) => {
27686
28120
  if (queueErrors.length < 5) {
27687
28121
  queueErrors.push(e);
@@ -27766,9 +28200,9 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
27766
28200
  );
27767
28201
  } finally {
27768
28202
  if (enableCache) {
27769
- const spanCache = _optionalChain([(_nullishCoalesce(evaluator.state, () => ( _internalGetGlobalState()))), 'optionalAccess', _669 => _669.spanCache]);
27770
- _optionalChain([spanCache, 'optionalAccess', _670 => _670.dispose, 'call', _671 => _671()]);
27771
- _optionalChain([spanCache, 'optionalAccess', _672 => _672.stop, 'call', _673 => _673()]);
28203
+ const spanCache = _optionalChain([(_nullishCoalesce(evaluator.state, () => ( _internalGetGlobalState()))), 'optionalAccess', _690 => _690.spanCache]);
28204
+ _optionalChain([spanCache, 'optionalAccess', _691 => _691.dispose, 'call', _692 => _692()]);
28205
+ _optionalChain([spanCache, 'optionalAccess', _693 => _693.stop, 'call', _694 => _694()]);
27772
28206
  }
27773
28207
  }
27774
28208
  }
@@ -28008,7 +28442,7 @@ async function cachedLogin(options) {
28008
28442
  }
28009
28443
  function makeCheckAuthorized(allowedOrgName) {
28010
28444
  return async (req, _res, next) => {
28011
- if (!_optionalChain([req, 'access', _674 => _674.ctx, 'optionalAccess', _675 => _675.token])) {
28445
+ if (!_optionalChain([req, 'access', _695 => _695.ctx, 'optionalAccess', _696 => _696.token])) {
28012
28446
  return next(_httperrors2.default.call(void 0, 401, "Unauthorized"));
28013
28447
  }
28014
28448
  try {
@@ -28021,7 +28455,7 @@ function makeCheckAuthorized(allowedOrgName) {
28021
28455
  return next(_httperrors2.default.call(void 0, 403, errorMessage2));
28022
28456
  }
28023
28457
  const state = await cachedLogin({
28024
- apiKey: _optionalChain([req, 'access', _676 => _676.ctx, 'optionalAccess', _677 => _677.token]),
28458
+ apiKey: _optionalChain([req, 'access', _697 => _697.ctx, 'optionalAccess', _698 => _698.token]),
28025
28459
  orgName
28026
28460
  });
28027
28461
  req.ctx.state = state;
@@ -28213,17 +28647,17 @@ var ProjectBuilder = class {
28213
28647
  }
28214
28648
  };
28215
28649
  var projects = new ProjectBuilder();
28216
- var Project2 = (_class29 = class {
28650
+ var Project2 = (_class30 = class {
28217
28651
 
28218
28652
 
28219
28653
 
28220
28654
 
28221
28655
 
28222
28656
 
28223
- __init112() {this._publishableCodeFunctions = []}
28224
- __init113() {this._publishablePrompts = []}
28225
- __init114() {this._publishableParameters = []}
28226
- constructor(args) {;_class29.prototype.__init112.call(this);_class29.prototype.__init113.call(this);_class29.prototype.__init114.call(this);
28657
+ __init114() {this._publishableCodeFunctions = []}
28658
+ __init115() {this._publishablePrompts = []}
28659
+ __init116() {this._publishableParameters = []}
28660
+ constructor(args) {;_class30.prototype.__init114.call(this);_class30.prototype.__init115.call(this);_class30.prototype.__init116.call(this);
28227
28661
  _initializeSpanContext();
28228
28662
  this.name = "name" in args ? args.name : void 0;
28229
28663
  this.id = "id" in args ? args.id : void 0;
@@ -28275,12 +28709,12 @@ var Project2 = (_class29 = class {
28275
28709
  functions: functionDefinitions
28276
28710
  });
28277
28711
  }
28278
- }, _class29);
28279
- var ToolBuilder = (_class30 = class {
28280
- constructor(project) {;_class30.prototype.__init115.call(this);
28712
+ }, _class30);
28713
+ var ToolBuilder = (_class31 = class {
28714
+ constructor(project) {;_class31.prototype.__init117.call(this);
28281
28715
  this.project = project;
28282
28716
  }
28283
- __init115() {this.taskCounter = 0}
28717
+ __init117() {this.taskCounter = 0}
28284
28718
  // This type definition is just a catch all so that the implementation can be
28285
28719
  // less specific than the two more specific declarations above.
28286
28720
  create(opts) {
@@ -28305,12 +28739,12 @@ var ToolBuilder = (_class30 = class {
28305
28739
  this.project.addCodeFunction(tool);
28306
28740
  return tool;
28307
28741
  }
28308
- }, _class30);
28309
- var ScorerBuilder = (_class31 = class {
28310
- constructor(project) {;_class31.prototype.__init116.call(this);
28742
+ }, _class31);
28743
+ var ScorerBuilder = (_class32 = class {
28744
+ constructor(project) {;_class32.prototype.__init118.call(this);
28311
28745
  this.project = project;
28312
28746
  }
28313
- __init116() {this.taskCounter = 0}
28747
+ __init118() {this.taskCounter = 0}
28314
28748
  create(opts) {
28315
28749
  this.taskCounter++;
28316
28750
  let resolvedName = opts.name;
@@ -28364,7 +28798,7 @@ var ScorerBuilder = (_class31 = class {
28364
28798
  this.project.addPrompt(codePrompt);
28365
28799
  }
28366
28800
  }
28367
- }, _class31);
28801
+ }, _class32);
28368
28802
  var CodeFunction = class {
28369
28803
  constructor(project, opts) {
28370
28804
  this.project = project;
@@ -28666,9 +29100,9 @@ function serializeRemoteEvalParametersContainer(parameters) {
28666
29100
  source: null
28667
29101
  };
28668
29102
  }
28669
- var ProjectNameIdMap = (_class32 = class {constructor() { _class32.prototype.__init117.call(this);_class32.prototype.__init118.call(this); }
28670
- __init117() {this.nameToId = {}}
28671
- __init118() {this.idToName = {}}
29103
+ var ProjectNameIdMap = (_class33 = class {constructor() { _class33.prototype.__init119.call(this);_class33.prototype.__init120.call(this); }
29104
+ __init119() {this.nameToId = {}}
29105
+ __init120() {this.idToName = {}}
28672
29106
  async getId(projectName) {
28673
29107
  if (!(projectName in this.nameToId)) {
28674
29108
  const response = await _internalGetGlobalState().appConn().post_json("api/project/register", {
@@ -28701,7 +29135,7 @@ var ProjectNameIdMap = (_class32 = class {constructor() { _class32.prototype.__i
28701
29135
  }
28702
29136
  return this.getId(project.name);
28703
29137
  }
28704
- }, _class32);
29138
+ }, _class33);
28705
29139
 
28706
29140
  // dev/server.ts
28707
29141
  function runDevServer(evaluators, opts) {
@@ -28776,7 +29210,7 @@ function runDevServer(evaluators, opts) {
28776
29210
  scores,
28777
29211
  stream
28778
29212
  } = evalBodySchema.parse(req.body);
28779
- if (!_optionalChain([req, 'access', _678 => _678.ctx, 'optionalAccess', _679 => _679.state])) {
29213
+ if (!_optionalChain([req, 'access', _699 => _699.ctx, 'optionalAccess', _700 => _700.state])) {
28780
29214
  res.status(500).json({ error: "Braintrust state not initialized in request" });
28781
29215
  return;
28782
29216
  }
@@ -28827,12 +29261,12 @@ function runDevServer(evaluators, opts) {
28827
29261
  ...evaluator,
28828
29262
  data: evalData.data,
28829
29263
  scores: (_nullishCoalesce(evaluator.scores, () => ( []))).concat(
28830
- _nullishCoalesce(_optionalChain([scores, 'optionalAccess', _680 => _680.map, 'call', _681 => _681(
29264
+ _nullishCoalesce(_optionalChain([scores, 'optionalAccess', _701 => _701.map, 'call', _702 => _702(
28831
29265
  (score) => makeScorer(
28832
29266
  state,
28833
29267
  score.name,
28834
29268
  score.function_id,
28835
- _optionalChain([req, 'access', _682 => _682.ctx, 'optionalAccess', _683 => _683.projectId])
29269
+ _optionalChain([req, 'access', _703 => _703.ctx, 'optionalAccess', _704 => _704.projectId])
28836
29270
  )
28837
29271
  )]), () => ( []))
28838
29272
  ),