braintrust 3.25.0 → 3.26.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 (78) hide show
  1. package/NOTICE +6 -0
  2. package/dev/dist/index.d.mts +130 -2
  3. package/dev/dist/index.d.ts +130 -2
  4. package/dev/dist/index.js +2455 -1116
  5. package/dev/dist/index.mjs +1599 -260
  6. package/dist/apply-auto-instrumentation.js +439 -398
  7. package/dist/apply-auto-instrumentation.mjs +242 -201
  8. package/dist/auto-instrumentations/bundler/esbuild.cjs +853 -337
  9. package/dist/auto-instrumentations/bundler/esbuild.d.mts +4 -4
  10. package/dist/auto-instrumentations/bundler/esbuild.d.ts +4 -4
  11. package/dist/auto-instrumentations/bundler/esbuild.mjs +5 -8
  12. package/dist/auto-instrumentations/bundler/next.cjs +852 -356
  13. package/dist/auto-instrumentations/bundler/next.mjs +6 -29
  14. package/dist/auto-instrumentations/bundler/rollup.cjs +853 -337
  15. package/dist/auto-instrumentations/bundler/rollup.d.mts +4 -4
  16. package/dist/auto-instrumentations/bundler/rollup.d.ts +4 -4
  17. package/dist/auto-instrumentations/bundler/rollup.mjs +5 -8
  18. package/dist/auto-instrumentations/bundler/vite.cjs +853 -337
  19. package/dist/auto-instrumentations/bundler/vite.d.mts +4 -4
  20. package/dist/auto-instrumentations/bundler/vite.d.ts +4 -4
  21. package/dist/auto-instrumentations/bundler/vite.mjs +5 -8
  22. package/dist/auto-instrumentations/bundler/webpack-loader.cjs +1006 -266
  23. package/dist/auto-instrumentations/bundler/webpack-loader.d.ts +20 -12
  24. package/dist/auto-instrumentations/bundler/webpack.cjs +853 -337
  25. package/dist/auto-instrumentations/bundler/webpack.d.mts +4 -4
  26. package/dist/auto-instrumentations/bundler/webpack.d.ts +4 -4
  27. package/dist/auto-instrumentations/bundler/webpack.mjs +5 -4
  28. package/dist/auto-instrumentations/{chunk-JPVCUKTY.mjs → chunk-6E22MYSW.mjs} +165 -73
  29. package/dist/auto-instrumentations/{chunk-VT6DDNKM.mjs → chunk-AKKPLXTP.mjs} +631 -194
  30. package/dist/auto-instrumentations/chunk-NRE4QUQR.mjs +509 -0
  31. package/dist/auto-instrumentations/{chunk-7P6563SW.mjs → chunk-V5LEODRX.mjs} +2 -6
  32. package/dist/auto-instrumentations/{chunk-M6DLIJ2Z.mjs → chunk-XYN63IG5.mjs} +124 -194
  33. package/dist/auto-instrumentations/{chunk-CZ24KNHT.mjs → chunk-XZHHE4Y3.mjs} +77 -68
  34. package/dist/auto-instrumentations/hook.mjs +247 -182
  35. package/dist/auto-instrumentations/index.cjs +557 -48
  36. package/dist/auto-instrumentations/index.d.mts +6 -2
  37. package/dist/auto-instrumentations/index.d.ts +6 -2
  38. package/dist/auto-instrumentations/index.mjs +6 -1
  39. package/dist/auto-instrumentations/loader/cjs-patch.cjs +492 -195
  40. package/dist/auto-instrumentations/loader/cjs-patch.d.mts +2 -2
  41. package/dist/auto-instrumentations/loader/cjs-patch.d.ts +2 -2
  42. package/dist/auto-instrumentations/loader/cjs-patch.mjs +3 -2
  43. package/dist/auto-instrumentations/loader/esm-hook.mjs +1 -1
  44. package/dist/auto-instrumentations/plugin-B-aZh7EP.d.ts +30 -0
  45. package/dist/auto-instrumentations/plugin-Bnj4E_6B.d.mts +30 -0
  46. package/dist/auto-instrumentations/{types-RNPaKi9o.d.mts → types-C1fVeiCp.d.mts} +1 -1
  47. package/dist/auto-instrumentations/{types-RNPaKi9o.d.ts → types-C1fVeiCp.d.ts} +1 -1
  48. package/dist/browser.d.mts +817 -197
  49. package/dist/browser.d.ts +817 -197
  50. package/dist/browser.js +1883 -265
  51. package/dist/browser.mjs +1883 -265
  52. package/dist/{chunk-ABR2QWDP.mjs → chunk-PN7EWK66.mjs} +581 -133
  53. package/dist/{chunk-GSIDVFE6.js → chunk-VRZZQPAA.js} +1670 -736
  54. package/dist/{chunk-P25IOOU4.js → chunk-VYNNEKSA.js} +586 -138
  55. package/dist/{chunk-2SANLSWX.mjs → chunk-XIZOM2HO.mjs} +1052 -118
  56. package/dist/cli.js +1601 -263
  57. package/dist/edge-light.d.mts +1 -1
  58. package/dist/edge-light.d.ts +1 -1
  59. package/dist/edge-light.js +1883 -268
  60. package/dist/edge-light.mjs +1883 -268
  61. package/dist/index.d.mts +817 -197
  62. package/dist/index.d.ts +817 -197
  63. package/dist/index.js +695 -435
  64. package/dist/index.mjs +264 -4
  65. package/dist/instrumentation/index.d.mts +130 -6
  66. package/dist/instrumentation/index.d.ts +130 -6
  67. package/dist/instrumentation/index.js +1510 -80
  68. package/dist/instrumentation/index.mjs +1510 -80
  69. package/dist/vitest-evals-reporter.js +16 -16
  70. package/dist/vitest-evals-reporter.mjs +2 -2
  71. package/dist/workerd.d.mts +1 -1
  72. package/dist/workerd.d.ts +1 -1
  73. package/dist/workerd.js +1883 -268
  74. package/dist/workerd.mjs +1883 -268
  75. package/licenses/node-diagnostics-channel/LICENSE +19 -0
  76. package/package.json +34 -35
  77. package/dist/auto-instrumentations/plugin-D0KHwSJv.d.mts +0 -44
  78. package/dist/auto-instrumentations/plugin-G6fgxk1b.d.ts +0 -44
package/dist/cli.js CHANGED
@@ -1236,7 +1236,7 @@ var require_package = __commonJS({
1236
1236
  "package.json"(exports2, module2) {
1237
1237
  module2.exports = {
1238
1238
  name: "braintrust",
1239
- version: "3.25.0",
1239
+ version: "3.26.0",
1240
1240
  description: "SDK for integrating Braintrust",
1241
1241
  repository: {
1242
1242
  type: "git",
@@ -1434,7 +1434,7 @@ var require_package = __commonJS({
1434
1434
  "eslint-plugin-node-import": "^1.0.5",
1435
1435
  openai: "6.25.0",
1436
1436
  rollup: "^4.60.3",
1437
- tar: "^7.5.19",
1437
+ tar: "^7.5.22",
1438
1438
  tinybench: "^4.0.1",
1439
1439
  "ts-declaration-location": "^1.0.7",
1440
1440
  tsup: "^8.5.1",
@@ -1460,7 +1460,6 @@ var require_package = __commonJS({
1460
1460
  "cli-progress": "^3.12.0",
1461
1461
  "cli-table3": "^0.6.5",
1462
1462
  cors: "^2.8.5",
1463
- "dc-browser": "^1.0.4",
1464
1463
  dotenv: "^16.4.5",
1465
1464
  esbuild: "0.28.1",
1466
1465
  esquery: "^1.7.0",
@@ -1524,84 +1523,528 @@ var import_pluralize4 = __toESM(require("pluralize"));
1524
1523
  // src/logger.ts
1525
1524
  var import_uuid2 = require("uuid");
1526
1525
 
1527
- // src/isomorph.ts
1528
- var DefaultAsyncLocalStorage = class {
1529
- constructor() {
1530
- }
1531
- enterWith(_) {
1532
- }
1533
- run(_, callback) {
1534
- return callback();
1526
+ // src/global-instrumentation-hooks.ts
1527
+ var GLOBAL_INSTRUMENTATION_HOOKS_KEY = "__braintrust_instrumentation_hooks";
1528
+ var GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION = 1;
1529
+ var GLOBAL_INSTRUMENTATION_HOOKS_REGISTRY_BRAND = "braintrust.global-instrumentation-hooks.registry";
1530
+ var GLOBAL_INSTRUMENTATION_HOOK_BRAND = "braintrust.global-instrumentation-hooks.hook";
1531
+ var registryBrand = Symbol.for(GLOBAL_INSTRUMENTATION_HOOKS_REGISTRY_BRAND);
1532
+ var hookBrand = Symbol.for(GLOBAL_INSTRUMENTATION_HOOK_BRAND);
1533
+ var errorReporter;
1534
+ function setGlobalHookErrorReporter(reporter) {
1535
+ const previousReporter = errorReporter;
1536
+ errorReporter = reporter;
1537
+ return () => {
1538
+ if (errorReporter === reporter) {
1539
+ errorReporter = previousReporter;
1540
+ }
1541
+ };
1542
+ }
1543
+ function reportError(error2) {
1544
+ try {
1545
+ errorReporter?.(error2);
1546
+ } catch {
1535
1547
  }
1536
- getStore() {
1537
- return void 0;
1548
+ }
1549
+ function setContextValue(context2, key, value) {
1550
+ try {
1551
+ context2[key] = value;
1552
+ } catch (error2) {
1553
+ reportError(error2);
1538
1554
  }
1539
- };
1540
- var DefaultChannel = class {
1555
+ }
1556
+ function wrapStoreRun(store, message, next, transform) {
1557
+ return () => {
1558
+ let context2;
1559
+ try {
1560
+ context2 = transform ? transform(message) : message;
1561
+ } catch (error2) {
1562
+ reportError(error2);
1563
+ return next();
1564
+ }
1565
+ let called = false;
1566
+ let result;
1567
+ let providerError;
1568
+ let providerThrew = false;
1569
+ const runNext = () => {
1570
+ if (called) {
1571
+ reportError(
1572
+ new Error(
1573
+ "Instrumentation store invoked its callback more than once"
1574
+ )
1575
+ );
1576
+ if (providerThrew) {
1577
+ throw providerError;
1578
+ }
1579
+ return result;
1580
+ }
1581
+ called = true;
1582
+ try {
1583
+ result = next();
1584
+ return result;
1585
+ } catch (error2) {
1586
+ providerThrew = true;
1587
+ providerError = error2;
1588
+ throw error2;
1589
+ }
1590
+ };
1591
+ try {
1592
+ store.run(context2, runNext);
1593
+ } catch (error2) {
1594
+ if (!providerThrew || error2 !== providerError) {
1595
+ reportError(error2);
1596
+ }
1597
+ }
1598
+ if (!called) {
1599
+ reportError(
1600
+ new Error("Instrumentation store did not invoke its callback")
1601
+ );
1602
+ return runNext();
1603
+ }
1604
+ if (providerThrew) {
1605
+ throw providerError;
1606
+ }
1607
+ return result;
1608
+ };
1609
+ }
1610
+ var HookChannel = class {
1541
1611
  constructor(name) {
1542
1612
  this.name = name;
1543
1613
  }
1544
1614
  name;
1545
- hasSubscribers = false;
1546
- subscribe(_subscription) {
1615
+ subscribers = [];
1616
+ stores = /* @__PURE__ */ new Map();
1617
+ get hasSubscribers() {
1618
+ return this.subscribers.length > 0 || this.stores.size > 0;
1547
1619
  }
1548
- unsubscribe(_subscription) {
1549
- return false;
1620
+ subscribe(subscription) {
1621
+ if (typeof subscription !== "function") {
1622
+ throw new TypeError("subscription must be a function");
1623
+ }
1624
+ this.subscribers = [...this.subscribers, subscription];
1550
1625
  }
1551
- bindStore(_store, _transform) {
1626
+ unsubscribe(subscription) {
1627
+ const index = this.subscribers.indexOf(subscription);
1628
+ if (index === -1) {
1629
+ return false;
1630
+ }
1631
+ this.subscribers = [
1632
+ ...this.subscribers.slice(0, index),
1633
+ ...this.subscribers.slice(index + 1)
1634
+ ];
1635
+ return true;
1552
1636
  }
1553
- unbindStore(_store) {
1554
- return false;
1637
+ bindStore(store, transform) {
1638
+ if (!store || typeof store.run !== "function") {
1639
+ throw new TypeError("store must have a run method");
1640
+ }
1641
+ this.stores.set(
1642
+ store,
1643
+ transform
1644
+ );
1555
1645
  }
1556
- publish(_message) {
1646
+ unbindStore(store) {
1647
+ return this.stores.delete(store);
1557
1648
  }
1558
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1559
- runStores(_message, fn, thisArg, ...args) {
1560
- return fn.apply(thisArg, args);
1649
+ publish(message) {
1650
+ const subscribers = this.subscribers;
1651
+ for (const subscriber of subscribers) {
1652
+ try {
1653
+ subscriber(message, this.name);
1654
+ } catch (error2) {
1655
+ reportError(error2);
1656
+ }
1657
+ }
1658
+ }
1659
+ runStores(message, fn, thisArg, ...args) {
1660
+ let run2 = () => {
1661
+ this.publish(message);
1662
+ return Reflect.apply(fn, thisArg, args);
1663
+ };
1664
+ for (const [store, transform] of this.stores.entries()) {
1665
+ run2 = wrapStoreRun(store, message, run2, transform);
1666
+ }
1667
+ return run2();
1561
1668
  }
1562
1669
  };
1563
- var DefaultTracingChannel = class {
1670
+ var traceEvents = [
1671
+ "start",
1672
+ "end",
1673
+ "asyncStart",
1674
+ "asyncEnd",
1675
+ "error"
1676
+ ];
1677
+ var TracingHook = class {
1564
1678
  start;
1565
1679
  end;
1566
1680
  asyncStart;
1567
1681
  asyncEnd;
1568
1682
  error;
1569
1683
  constructor(nameOrChannels) {
1684
+ Object.defineProperty(this, hookBrand, {
1685
+ configurable: false,
1686
+ enumerable: false,
1687
+ value: GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION,
1688
+ writable: false
1689
+ });
1570
1690
  if (typeof nameOrChannels === "string") {
1571
- this.start = new DefaultChannel(`tracing:${nameOrChannels}:start`);
1572
- this.end = new DefaultChannel(`tracing:${nameOrChannels}:end`);
1573
- this.asyncStart = new DefaultChannel(
1574
- `tracing:${nameOrChannels}:asyncStart`
1575
- );
1576
- this.asyncEnd = new DefaultChannel(`tracing:${nameOrChannels}:asyncEnd`);
1577
- this.error = new DefaultChannel(`tracing:${nameOrChannels}:error`);
1691
+ this.start = new HookChannel(`tracing:${nameOrChannels}:start`);
1692
+ this.end = new HookChannel(`tracing:${nameOrChannels}:end`);
1693
+ this.asyncStart = new HookChannel(`tracing:${nameOrChannels}:asyncStart`);
1694
+ this.asyncEnd = new HookChannel(`tracing:${nameOrChannels}:asyncEnd`);
1695
+ this.error = new HookChannel(`tracing:${nameOrChannels}:error`);
1578
1696
  return;
1579
1697
  }
1580
- this.start = nameOrChannels.start ?? new DefaultChannel("tracing:start");
1581
- this.end = nameOrChannels.end ?? new DefaultChannel("tracing:end");
1582
- this.asyncStart = nameOrChannels.asyncStart ?? new DefaultChannel("tracing:asyncStart");
1583
- this.asyncEnd = nameOrChannels.asyncEnd ?? new DefaultChannel("tracing:asyncEnd");
1584
- this.error = nameOrChannels.error ?? new DefaultChannel("tracing:error");
1698
+ this.start = nameOrChannels.start ?? new HookChannel("tracing:start");
1699
+ this.end = nameOrChannels.end ?? new HookChannel("tracing:end");
1700
+ this.asyncStart = nameOrChannels.asyncStart ?? new HookChannel("tracing:asyncStart");
1701
+ this.asyncEnd = nameOrChannels.asyncEnd ?? new HookChannel("tracing:asyncEnd");
1702
+ this.error = nameOrChannels.error ?? new HookChannel("tracing:error");
1585
1703
  }
1586
1704
  get hasSubscribers() {
1587
1705
  return this.start.hasSubscribers || this.end.hasSubscribers || this.asyncStart.hasSubscribers || this.asyncEnd.hasSubscribers || this.error.hasSubscribers;
1588
1706
  }
1589
- subscribe(_handlers) {
1707
+ subscribe(handlers) {
1708
+ for (const eventName of traceEvents) {
1709
+ const handler = handlers[eventName];
1710
+ if (handler) {
1711
+ this[eventName].subscribe(handler);
1712
+ }
1713
+ }
1590
1714
  }
1591
- unsubscribe(_handlers) {
1715
+ unsubscribe(handlers) {
1716
+ let done = true;
1717
+ for (const eventName of traceEvents) {
1718
+ const handler = handlers[eventName];
1719
+ if (handler && !this[eventName].unsubscribe(handler)) {
1720
+ done = false;
1721
+ }
1722
+ }
1723
+ return done;
1724
+ }
1725
+ traceSync(fn, message = {}, thisArg, ...args) {
1726
+ if (!this.hasSubscribers) {
1727
+ return Reflect.apply(fn, thisArg, args);
1728
+ }
1729
+ const context2 = message;
1730
+ return this.start.runStores(message, () => {
1731
+ try {
1732
+ const result = Reflect.apply(fn, thisArg, args);
1733
+ setContextValue(context2, "result", result);
1734
+ return result;
1735
+ } catch (error2) {
1736
+ setContextValue(context2, "error", error2);
1737
+ this.error.publish(message);
1738
+ throw error2;
1739
+ } finally {
1740
+ this.end.publish(message);
1741
+ }
1742
+ });
1743
+ }
1744
+ tracePromise(fn, message = {}, thisArg, ...args) {
1745
+ if (!this.hasSubscribers) {
1746
+ return Reflect.apply(fn, thisArg, args);
1747
+ }
1748
+ const context2 = message;
1749
+ return this.start.runStores(message, () => {
1750
+ let result;
1751
+ try {
1752
+ result = Reflect.apply(fn, thisArg, args);
1753
+ } catch (error2) {
1754
+ setContextValue(context2, "error", error2);
1755
+ this.error.publish(message);
1756
+ this.end.publish(message);
1757
+ throw error2;
1758
+ }
1759
+ this.end.publish(message);
1760
+ if (!result || typeof result !== "object" && typeof result !== "function") {
1761
+ setContextValue(context2, "result", result);
1762
+ this.asyncStart.publish(message);
1763
+ this.asyncEnd.publish(message);
1764
+ return result;
1765
+ }
1766
+ let terminalPublished = false;
1767
+ const finishUnobservedResult = (error2) => {
1768
+ reportError(error2);
1769
+ if (!terminalPublished) {
1770
+ terminalPublished = true;
1771
+ setContextValue(context2, "result", result);
1772
+ this.asyncStart.publish(message);
1773
+ this.asyncEnd.publish(message);
1774
+ }
1775
+ return result;
1776
+ };
1777
+ let then;
1778
+ try {
1779
+ then = result.then;
1780
+ } catch (error2) {
1781
+ return finishUnobservedResult(error2);
1782
+ }
1783
+ if (typeof then !== "function") {
1784
+ setContextValue(context2, "result", result);
1785
+ this.asyncStart.publish(message);
1786
+ this.asyncEnd.publish(message);
1787
+ return result;
1788
+ }
1789
+ const resolve2 = (resolved) => {
1790
+ if (!terminalPublished) {
1791
+ terminalPublished = true;
1792
+ setContextValue(context2, "result", resolved);
1793
+ this.asyncStart.publish(message);
1794
+ this.asyncEnd.publish(message);
1795
+ }
1796
+ return resolved;
1797
+ };
1798
+ let rejectionThrown = false;
1799
+ let rejectionError;
1800
+ const reject2 = (error2) => {
1801
+ if (!terminalPublished) {
1802
+ terminalPublished = true;
1803
+ setContextValue(context2, "error", error2);
1804
+ this.error.publish(message);
1805
+ this.asyncStart.publish(message);
1806
+ this.asyncEnd.publish(message);
1807
+ }
1808
+ rejectionThrown = true;
1809
+ rejectionError = error2;
1810
+ throw error2;
1811
+ };
1812
+ let isPlainPromise;
1813
+ try {
1814
+ isPlainPromise = result instanceof Promise && result.constructor === Promise;
1815
+ } catch (error2) {
1816
+ return finishUnobservedResult(error2);
1817
+ }
1818
+ try {
1819
+ if (isPlainPromise) {
1820
+ return Reflect.apply(then, result, [resolve2, reject2]);
1821
+ }
1822
+ Reflect.apply(then, result, [
1823
+ resolve2,
1824
+ (error2) => {
1825
+ try {
1826
+ reject2(error2);
1827
+ } catch {
1828
+ }
1829
+ }
1830
+ ]);
1831
+ } catch (error2) {
1832
+ if (rejectionThrown && error2 === rejectionError) {
1833
+ return result;
1834
+ }
1835
+ return finishUnobservedResult(error2);
1836
+ }
1837
+ return result;
1838
+ });
1839
+ }
1840
+ traceCallback(fn, position = -1, message = {}, thisArg, ...args) {
1841
+ if (!this.hasSubscribers) {
1842
+ return Reflect.apply(fn, thisArg, args);
1843
+ }
1844
+ const context2 = message;
1845
+ const callArgs = args.length > 0 ? args : context2.arguments ?? args;
1846
+ const callback = Array.prototype.at.call(callArgs, position);
1847
+ if (typeof callback !== "function") {
1848
+ return Reflect.apply(fn, thisArg, args);
1849
+ }
1850
+ const { asyncStart, asyncEnd, error: errorChannel } = this;
1851
+ function wrappedCallback(error2, result) {
1852
+ if (error2) {
1853
+ setContextValue(context2, "error", error2);
1854
+ errorChannel.publish(message);
1855
+ } else {
1856
+ setContextValue(context2, "result", result);
1857
+ }
1858
+ return asyncStart.runStores(message, () => {
1859
+ try {
1860
+ return Reflect.apply(callback, this, arguments);
1861
+ } finally {
1862
+ asyncEnd.publish(message);
1863
+ }
1864
+ });
1865
+ }
1866
+ Array.prototype.splice.call(callArgs, position, 1, wrappedCallback);
1867
+ return this.start.runStores(message, () => {
1868
+ try {
1869
+ return Reflect.apply(fn, thisArg, args);
1870
+ } catch (error2) {
1871
+ setContextValue(context2, "error", error2);
1872
+ this.error.publish(message);
1873
+ throw error2;
1874
+ } finally {
1875
+ this.end.publish(message);
1876
+ }
1877
+ });
1878
+ }
1879
+ };
1880
+ var inertChannel = Object.freeze({
1881
+ name: "braintrust:inert",
1882
+ hasSubscribers: false,
1883
+ subscribe() {
1884
+ },
1885
+ unsubscribe() {
1592
1886
  return false;
1887
+ },
1888
+ bindStore() {
1889
+ },
1890
+ unbindStore() {
1891
+ return false;
1892
+ },
1893
+ publish() {
1894
+ },
1895
+ runStores(_message, fn, thisArg, ...args) {
1896
+ return Reflect.apply(fn, thisArg, args);
1593
1897
  }
1594
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1595
- traceSync(fn, _message, thisArg, ...args) {
1596
- return fn.apply(thisArg, args);
1898
+ });
1899
+ var inertTracingHook = new TracingHook({
1900
+ start: inertChannel,
1901
+ end: inertChannel,
1902
+ asyncStart: inertChannel,
1903
+ asyncEnd: inertChannel,
1904
+ error: inertChannel
1905
+ });
1906
+ function isHookChannel(value) {
1907
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
1908
+ return false;
1597
1909
  }
1598
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1599
- tracePromise(fn, _message, thisArg, ...args) {
1600
- return fn.apply(thisArg, args);
1910
+ try {
1911
+ const channel2 = value;
1912
+ return typeof channel2.hasSubscribers === "boolean" && typeof channel2.subscribe === "function" && typeof channel2.unsubscribe === "function" && typeof channel2.bindStore === "function" && typeof channel2.unbindStore === "function" && typeof channel2.publish === "function" && typeof channel2.runStores === "function";
1913
+ } catch {
1914
+ return false;
1601
1915
  }
1602
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1603
- traceCallback(fn, _position, _message, thisArg, ...args) {
1604
- return fn.apply(thisArg, args);
1916
+ }
1917
+ function hasTracingHookShape(value) {
1918
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
1919
+ return false;
1920
+ }
1921
+ try {
1922
+ const hook = value;
1923
+ return typeof hook.hasSubscribers === "boolean" && typeof hook.subscribe === "function" && typeof hook.unsubscribe === "function" && typeof hook.traceSync === "function" && typeof hook.tracePromise === "function" && typeof hook.traceCallback === "function" && isHookChannel(hook.start) && isHookChannel(hook.end) && isHookChannel(hook.asyncStart) && isHookChannel(hook.asyncEnd) && isHookChannel(hook.error);
1924
+ } catch {
1925
+ return false;
1926
+ }
1927
+ }
1928
+ function isCompatibleTracingHook(value) {
1929
+ try {
1930
+ return value[hookBrand] === GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION && hasTracingHookShape(value);
1931
+ } catch {
1932
+ return false;
1933
+ }
1934
+ }
1935
+ function isCompatibleHookRegistry(value) {
1936
+ try {
1937
+ return value instanceof Map && value[registryBrand] === GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION;
1938
+ } catch {
1939
+ return false;
1940
+ }
1941
+ }
1942
+ function getHookRegistry() {
1943
+ let descriptor;
1944
+ try {
1945
+ descriptor = Object.getOwnPropertyDescriptor(
1946
+ globalThis,
1947
+ GLOBAL_INSTRUMENTATION_HOOKS_KEY
1948
+ );
1949
+ } catch (error2) {
1950
+ reportError(error2);
1951
+ return void 0;
1952
+ }
1953
+ if (descriptor && "value" in descriptor && isCompatibleHookRegistry(descriptor.value) && (descriptor.configurable || descriptor.enumerable === false)) {
1954
+ if (descriptor.configurable || descriptor.writable) {
1955
+ try {
1956
+ Object.defineProperty(globalThis, GLOBAL_INSTRUMENTATION_HOOKS_KEY, {
1957
+ configurable: false,
1958
+ enumerable: false,
1959
+ value: descriptor.value,
1960
+ writable: false
1961
+ });
1962
+ } catch (error2) {
1963
+ reportError(error2);
1964
+ return void 0;
1965
+ }
1966
+ }
1967
+ return descriptor.value;
1968
+ }
1969
+ if (descriptor && !descriptor.configurable) {
1970
+ reportError(new Error("Incompatible global instrumentation hook registry"));
1971
+ return void 0;
1972
+ }
1973
+ const registry2 = /* @__PURE__ */ new Map();
1974
+ try {
1975
+ Object.defineProperty(registry2, registryBrand, {
1976
+ configurable: false,
1977
+ enumerable: false,
1978
+ value: GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION,
1979
+ writable: false
1980
+ });
1981
+ } catch (error2) {
1982
+ reportError(error2);
1983
+ return void 0;
1984
+ }
1985
+ try {
1986
+ Object.defineProperty(globalThis, GLOBAL_INSTRUMENTATION_HOOKS_KEY, {
1987
+ configurable: false,
1988
+ enumerable: false,
1989
+ value: registry2,
1990
+ writable: false
1991
+ });
1992
+ return registry2;
1993
+ } catch (error2) {
1994
+ reportError(error2);
1995
+ return void 0;
1996
+ }
1997
+ }
1998
+ function newGlobalTracingChannel(nameOrChannels) {
1999
+ if (typeof nameOrChannels !== "string") {
2000
+ return new TracingHook(nameOrChannels);
2001
+ }
2002
+ const registry2 = getHookRegistry();
2003
+ if (!registry2) {
2004
+ return inertTracingHook;
2005
+ }
2006
+ let existing;
2007
+ try {
2008
+ existing = Map.prototype.get.call(registry2, nameOrChannels);
2009
+ } catch (error2) {
2010
+ reportError(error2);
2011
+ return inertTracingHook;
2012
+ }
2013
+ if (isCompatibleTracingHook(existing)) {
2014
+ return existing;
2015
+ }
2016
+ if (existing !== void 0) {
2017
+ reportError(
2018
+ new Error(`Invalid global instrumentation hook: ${nameOrChannels}`)
2019
+ );
2020
+ try {
2021
+ Map.prototype.delete.call(registry2, nameOrChannels);
2022
+ } catch (error2) {
2023
+ reportError(error2);
2024
+ return inertTracingHook;
2025
+ }
2026
+ }
2027
+ const hook = new TracingHook(nameOrChannels);
2028
+ try {
2029
+ Map.prototype.set.call(registry2, nameOrChannels, hook);
2030
+ } catch (error2) {
2031
+ reportError(error2);
2032
+ return inertTracingHook;
2033
+ }
2034
+ return hook;
2035
+ }
2036
+
2037
+ // src/isomorph.ts
2038
+ var DefaultAsyncLocalStorage = class {
2039
+ constructor() {
2040
+ }
2041
+ enterWith(_) {
2042
+ }
2043
+ run(_, callback) {
2044
+ return callback();
2045
+ }
2046
+ getStore() {
2047
+ return void 0;
1605
2048
  }
1606
2049
  };
1607
2050
  var iso = {
@@ -1614,7 +2057,7 @@ var iso = {
1614
2057
  getCallerLocation: () => void 0,
1615
2058
  newAsyncLocalStorage: () => new DefaultAsyncLocalStorage(),
1616
2059
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
1617
- newTracingChannel: (nameOrChannels) => new DefaultTracingChannel(nameOrChannels),
2060
+ newTracingChannel: (nameOrChannels) => newGlobalTracingChannel(nameOrChannels),
1618
2061
  processOn: (_0, _1) => {
1619
2062
  },
1620
2063
  basename: (filepath) => filepath.split(/[\\/]/).pop() || filepath,
@@ -1727,6 +2170,9 @@ var debugLogger = {
1727
2170
  return createDebugLogger(state);
1728
2171
  }
1729
2172
  };
2173
+ setGlobalHookErrorReporter((error2) => {
2174
+ debugLogger.error("Global instrumentation hook error:", error2);
2175
+ });
1730
2176
 
1731
2177
  // src/queue.ts
1732
2178
  var DEFAULT_QUEUE_SIZE = 15e3;
@@ -3538,7 +3984,8 @@ var ApiKey = import_v36.z.object({
3538
3984
  user_email: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
3539
3985
  user_given_name: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
3540
3986
  user_family_name: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
3541
- org_id: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional()
3987
+ org_id: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
3988
+ expires_at: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional()
3542
3989
  });
3543
3990
  var TriggeredFunctionState = import_v36.z.object({
3544
3991
  triggered_xact_id: import_v36.z.string(),
@@ -3658,6 +4105,7 @@ var TopicMapData = import_v36.z.object({
3658
4105
  topic_names: import_v36.z.record(import_v36.z.string()).optional(),
3659
4106
  generation_settings: TopicMapGenerationSettings.optional(),
3660
4107
  disable_reconciliation: import_v36.z.boolean().optional(),
4108
+ reconcile_mode: import_v36.z.enum(["evolve", "names_only"]).optional(),
3661
4109
  distance_threshold: import_v36.z.number().optional(),
3662
4110
  btql_filter: import_v36.z.string().optional(),
3663
4111
  automation_btql_filter: import_v36.z.string().optional()
@@ -4238,7 +4686,12 @@ var ModelParams = import_v36.z.union([
4238
4686
  }).partial().passthrough()
4239
4687
  ]);
4240
4688
  var PromptOptionsNullish = import_v36.z.union([
4241
- import_v36.z.object({ model: import_v36.z.string(), params: ModelParams, position: import_v36.z.string() }).partial(),
4689
+ import_v36.z.object({
4690
+ model: import_v36.z.string(),
4691
+ params: ModelParams,
4692
+ position: import_v36.z.string(),
4693
+ endpoint_name: import_v36.z.union([import_v36.z.string(), import_v36.z.null()])
4694
+ }).partial(),
4242
4695
  import_v36.z.null()
4243
4696
  ]);
4244
4697
  var PromptParserNullish = import_v36.z.union([
@@ -4252,11 +4705,25 @@ var PromptParserNullish = import_v36.z.union([
4252
4705
  }),
4253
4706
  import_v36.z.null()
4254
4707
  ]);
4708
+ var PreprocessorSavedFunctionId = import_v36.z.union([
4709
+ import_v36.z.object({
4710
+ type: import_v36.z.literal("function"),
4711
+ id: import_v36.z.string(),
4712
+ version: import_v36.z.string().optional()
4713
+ }),
4714
+ import_v36.z.object({
4715
+ type: import_v36.z.literal("global"),
4716
+ name: import_v36.z.string(),
4717
+ function_type: import_v36.z.literal("preprocessor").optional().default("preprocessor")
4718
+ }),
4719
+ import_v36.z.null()
4720
+ ]);
4255
4721
  var PromptDataNullish = import_v36.z.union([
4256
4722
  import_v36.z.object({
4257
4723
  prompt: PromptBlockDataNullish,
4258
4724
  options: PromptOptionsNullish,
4259
4725
  parser: PromptParserNullish,
4726
+ preprocessor: PreprocessorSavedFunctionId,
4260
4727
  tool_functions: import_v36.z.union([import_v36.z.array(SavedFunctionId), import_v36.z.null()]),
4261
4728
  template_format: import_v36.z.union([
4262
4729
  import_v36.z.enum(["mustache", "nunjucks", "none"]),
@@ -4458,6 +4925,7 @@ var PromptData = import_v36.z.object({
4458
4925
  prompt: PromptBlockDataNullish,
4459
4926
  options: PromptOptionsNullish,
4460
4927
  parser: PromptParserNullish,
4928
+ preprocessor: PreprocessorSavedFunctionId,
4461
4929
  tool_functions: import_v36.z.union([import_v36.z.array(SavedFunctionId), import_v36.z.null()]),
4462
4930
  template_format: import_v36.z.union([
4463
4931
  import_v36.z.enum(["mustache", "nunjucks", "none"]),
@@ -4620,7 +5088,8 @@ var InvokeFunction = FunctionId.and(
4620
5088
  mode: StreamingMode,
4621
5089
  strict: import_v36.z.union([import_v36.z.boolean(), import_v36.z.null()]),
4622
5090
  mcp_auth: import_v36.z.record(import_v36.z.object({ oauth_token: import_v36.z.string() }).partial()),
4623
- overrides: import_v36.z.union([import_v36.z.object({}).partial().passthrough(), import_v36.z.null()])
5091
+ overrides: import_v36.z.union([import_v36.z.object({}).partial().passthrough(), import_v36.z.null()]),
5092
+ endpoint_name: import_v36.z.union([import_v36.z.string(), import_v36.z.null()])
4624
5093
  }).partial()
4625
5094
  );
4626
5095
  var MCPServer = import_v36.z.object({
@@ -4684,6 +5153,24 @@ var Organization = import_v36.z.object({
4684
5153
  created: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
4685
5154
  image_rendering_mode: ImageRenderingMode.optional()
4686
5155
  });
5156
+ var RetentionObjectType = import_v36.z.enum([
5157
+ "project_logs",
5158
+ "experiment",
5159
+ "dataset"
5160
+ ]);
5161
+ var OrgAutomation = import_v36.z.object({
5162
+ id: import_v36.z.string().uuid(),
5163
+ org_id: import_v36.z.string().uuid(),
5164
+ user_id: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
5165
+ created: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
5166
+ name: import_v36.z.string(),
5167
+ description: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
5168
+ config: import_v36.z.object({
5169
+ event_type: import_v36.z.literal("retention"),
5170
+ object_type: RetentionObjectType,
5171
+ retention_days: import_v36.z.number().int().gte(0)
5172
+ })
5173
+ });
4687
5174
  var ProjectSettings = import_v36.z.union([
4688
5175
  import_v36.z.object({
4689
5176
  comparison_key: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]),
@@ -4710,6 +5197,7 @@ var ProjectSettings = import_v36.z.union([
4710
5197
  import_v36.z.null()
4711
5198
  ]),
4712
5199
  disable_realtime_queries: import_v36.z.union([import_v36.z.boolean(), import_v36.z.null()]),
5200
+ monitor_charts_use_metrics_start: import_v36.z.union([import_v36.z.boolean(), import_v36.z.null()]),
4713
5201
  default_preprocessor: NullableSavedFunctionId
4714
5202
  }).partial(),
4715
5203
  import_v36.z.null()
@@ -4724,11 +5212,6 @@ var Project = import_v36.z.object({
4724
5212
  user_id: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
4725
5213
  settings: ProjectSettings.optional()
4726
5214
  });
4727
- var RetentionObjectType = import_v36.z.enum([
4728
- "project_logs",
4729
- "experiment",
4730
- "dataset"
4731
- ]);
4732
5215
  var TopicAutomationFacetModel = import_v36.z.union([
4733
5216
  import_v36.z.enum(["brain-facet-latest", "brain-facet-1", "brain-facet-2"]),
4734
5217
  import_v36.z.null()
@@ -4839,7 +5322,7 @@ var ProjectAutomation = import_v36.z.object({
4839
5322
  import_v36.z.object({
4840
5323
  event_type: import_v36.z.literal("retention"),
4841
5324
  object_type: RetentionObjectType,
4842
- retention_days: import_v36.z.number().gte(0)
5325
+ retention_days: import_v36.z.number().int().gte(0)
4843
5326
  }),
4844
5327
  import_v36.z.object({
4845
5328
  event_type: import_v36.z.literal("environment_update"),
@@ -5011,7 +5494,12 @@ var Prompt = import_v36.z.object({
5011
5494
  metadata: import_v36.z.union([import_v36.z.object({}).partial().passthrough(), import_v36.z.null()]).optional(),
5012
5495
  function_type: FunctionTypeEnumNullish.optional()
5013
5496
  });
5014
- var PromptOptions = import_v36.z.object({ model: import_v36.z.string(), params: ModelParams, position: import_v36.z.string() }).partial();
5497
+ var PromptOptions = import_v36.z.object({
5498
+ model: import_v36.z.string(),
5499
+ params: ModelParams,
5500
+ position: import_v36.z.string(),
5501
+ endpoint_name: import_v36.z.union([import_v36.z.string(), import_v36.z.null()])
5502
+ }).partial();
5015
5503
  var PromptSessionEvent = import_v36.z.object({
5016
5504
  id: import_v36.z.string(),
5017
5505
  _xact_id: import_v36.z.string(),
@@ -5094,7 +5582,8 @@ var RunEval = import_v36.z.object({
5094
5582
  stop_token: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
5095
5583
  extra_messages: import_v36.z.string().optional(),
5096
5584
  tags: import_v36.z.array(import_v36.z.string()).optional(),
5097
- mcp_auth: import_v36.z.record(import_v36.z.object({ oauth_token: import_v36.z.string() }).partial()).optional()
5585
+ mcp_auth: import_v36.z.record(import_v36.z.object({ oauth_token: import_v36.z.string() }).partial()).optional(),
5586
+ endpoint_name: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional()
5098
5587
  });
5099
5588
  var ServiceToken = import_v36.z.object({
5100
5589
  id: import_v36.z.string().uuid(),
@@ -5104,7 +5593,8 @@ var ServiceToken = import_v36.z.object({
5104
5593
  service_account_id: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
5105
5594
  service_account_email: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
5106
5595
  service_account_name: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
5107
- org_id: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional()
5596
+ org_id: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
5597
+ expires_at: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional()
5108
5598
  });
5109
5599
  var SpanIFrame = import_v36.z.object({
5110
5600
  id: import_v36.z.string().uuid(),
@@ -5226,6 +5716,13 @@ var ViewOptions = import_v36.z.union([
5226
5716
  }),
5227
5717
  import_v36.z.null()
5228
5718
  ]),
5719
+ pointSizeMetric: import_v36.z.union([
5720
+ import_v36.z.object({
5721
+ type: import_v36.z.enum(["none", "score", "metric", "metadata"]),
5722
+ value: import_v36.z.string()
5723
+ }),
5724
+ import_v36.z.null()
5725
+ ]),
5229
5726
  xAxisAggregation: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]),
5230
5727
  chartAnnotations: import_v36.z.union([
5231
5728
  import_v36.z.array(import_v36.z.object({ id: import_v36.z.string(), text: import_v36.z.string() })),
@@ -6367,6 +6864,8 @@ var INSTRUMENTATION_NAMES = {
6367
6864
  BEDROCK_RUNTIME: "bedrock-runtime",
6368
6865
  BRAINTRUST_JS_LOGGER: "braintrust-js-logger",
6369
6866
  CLAUDE_AGENT_SDK: "claude-agent-sdk",
6867
+ CLOUDFLARE_AI_CHAT: "cloudflare-ai-chat",
6868
+ CLOUDFLARE_AGENTS: "cloudflare-agents",
6370
6869
  COHERE: "cohere",
6371
6870
  CURSOR_SDK: "cursor-sdk",
6372
6871
  EVE: "eve",
@@ -6392,7 +6891,7 @@ var INSTRUMENTATION_NAMES = {
6392
6891
  var INTERNAL_SPAN_INSTRUMENTATION_NAME = /* @__PURE__ */ Symbol.for(
6393
6892
  "braintrust.spanInstrumentationName"
6394
6893
  );
6395
- var SDK_VERSION = true ? "3.25.0" : "0.0.0";
6894
+ var SDK_VERSION = true ? "3.26.0" : "0.0.0";
6396
6895
  function withSpanInstrumentationName(args, instrumentationName) {
6397
6896
  return {
6398
6897
  ...args,
@@ -6587,12 +7086,13 @@ function applyMaskingToField(maskingFunction, data, fieldName) {
6587
7086
  var INITIAL_SPAN_WRITE_AS_MERGE = /* @__PURE__ */ Symbol(
6588
7087
  "braintrust.initial-span-write-as-merge"
6589
7088
  );
7089
+ var INTERNAL_SPAN_CONTEXT = /* @__PURE__ */ Symbol("braintrust.internal-span-context");
6590
7090
  var BRAINTRUST_CURRENT_SPAN_STORE = /* @__PURE__ */ Symbol.for(
6591
7091
  "braintrust.currentSpanStore"
6592
7092
  );
6593
7093
  var ContextManager = class {
6594
7094
  /**
6595
- * Returns the value to store in the ALS bound to a TracingChannel's start event.
7095
+ * Returns the value to store in the ALS bound to a global hook's start event.
6596
7096
  * In default mode this is the Span itself; in OTEL mode it is the OTEL Context
6597
7097
  * containing the span so that OTEL's own ALS stores a proper Context object.
6598
7098
  */
@@ -9654,6 +10154,12 @@ function _internalStartSpanWithInitialMerge(args) {
9654
10154
  [INITIAL_SPAN_WRITE_AS_MERGE]: true
9655
10155
  }).span;
9656
10156
  }
10157
+ function _internalStartSpanWithContext(args, context2) {
10158
+ return startSpanAndIsLogger({
10159
+ ...args,
10160
+ [INTERNAL_SPAN_CONTEXT]: context2
10161
+ }).span;
10162
+ }
9657
10163
  async function flush(options) {
9658
10164
  const state = options?.state ?? _globalState;
9659
10165
  return await state.bgLogger().flush();
@@ -10506,7 +11012,7 @@ var SpanImpl = class _SpanImpl {
10506
11012
  start: args.startTime ?? getCurrentUnixTimestamp()
10507
11013
  },
10508
11014
  context: mergeSpanOriginContext(
10509
- { ...callerLocation },
11015
+ { ...callerLocation, ...args[INTERNAL_SPAN_CONTEXT] },
10510
11016
  instrumentationName,
10511
11017
  this._state.spanOriginEnvironment
10512
11018
  ),
@@ -14469,96 +14975,7 @@ var fancyReporter = {
14469
14975
 
14470
14976
  // src/node/config.ts
14471
14977
  var import_node_async_hooks = require("node:async_hooks");
14472
- var diagnostics_channel = __toESM(require("node:diagnostics_channel"));
14473
14978
  var path = __toESM(require("node:path"));
14474
-
14475
- // src/auto-instrumentations/patch-tracing-channel.ts
14476
- function patchTracingChannel(tracingChannelFn) {
14477
- const dummyChannel = tracingChannelFn("__braintrust_probe__");
14478
- const TracingChannel = dummyChannel?.constructor;
14479
- if (!TracingChannel?.prototype) {
14480
- return;
14481
- }
14482
- if (!Object.getOwnPropertyDescriptor(TracingChannel.prototype, "hasSubscribers")) {
14483
- Object.defineProperty(TracingChannel.prototype, "hasSubscribers", {
14484
- configurable: true,
14485
- enumerable: false,
14486
- get() {
14487
- return Boolean(
14488
- this.start?.hasSubscribers || this.end?.hasSubscribers || this.asyncStart?.hasSubscribers || this.asyncEnd?.hasSubscribers || this.error?.hasSubscribers
14489
- );
14490
- }
14491
- });
14492
- }
14493
- if (TracingChannel.prototype.tracePromise) {
14494
- TracingChannel.prototype.tracePromise = function(fn, context2 = {}, thisArg, ...args) {
14495
- const start = this.start;
14496
- const end = this.end;
14497
- const asyncStart = this.asyncStart;
14498
- const asyncEnd = this.asyncEnd;
14499
- const error2 = this.error;
14500
- function publishRejected(err) {
14501
- context2.error = err;
14502
- error2?.publish(context2);
14503
- asyncStart?.publish(context2);
14504
- asyncEnd?.publish(context2);
14505
- }
14506
- function publishResolved(result) {
14507
- context2.result = result;
14508
- asyncStart?.publish(context2);
14509
- asyncEnd?.publish(context2);
14510
- }
14511
- return start.runStores(context2, () => {
14512
- try {
14513
- const result = Reflect.apply(fn, thisArg, args);
14514
- end?.publish(context2);
14515
- if (result && (typeof result === "object" || typeof result === "function") && typeof result.then === "function") {
14516
- if (result.constructor === Promise) {
14517
- return result.then(
14518
- (res) => {
14519
- publishResolved(res);
14520
- return res;
14521
- },
14522
- (err) => {
14523
- publishRejected(err);
14524
- return Promise.reject(err);
14525
- }
14526
- );
14527
- }
14528
- void result.then(
14529
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
14530
- (resolved) => {
14531
- try {
14532
- publishResolved(resolved);
14533
- } catch {
14534
- }
14535
- },
14536
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
14537
- (err) => {
14538
- try {
14539
- publishRejected(err);
14540
- } catch {
14541
- }
14542
- }
14543
- );
14544
- return result;
14545
- }
14546
- context2.result = result;
14547
- asyncStart?.publish(context2);
14548
- asyncEnd?.publish(context2);
14549
- return result;
14550
- } catch (err) {
14551
- context2.error = err;
14552
- error2?.publish(context2);
14553
- end?.publish(context2);
14554
- throw err;
14555
- }
14556
- });
14557
- };
14558
- }
14559
- }
14560
-
14561
- // src/node/config.ts
14562
14979
  var fs = __toESM(require("node:fs/promises"));
14563
14980
  var os = __toESM(require("node:os"));
14564
14981
  var fsSync = __toESM(require("node:fs"));
@@ -15447,8 +15864,8 @@ function runWithAutoInstrumentationSuppressed(callback) {
15447
15864
  callback
15448
15865
  );
15449
15866
  }
15450
- function bindAutoInstrumentationSuppressionToStart(tracingChannel2) {
15451
- const startChannel = tracingChannel2.start;
15867
+ function bindAutoInstrumentationSuppressionToStart(tracingChannel) {
15868
+ const startChannel = tracingChannel.start;
15452
15869
  if (!startChannel) {
15453
15870
  return void 0;
15454
15871
  }
@@ -15559,9 +15976,9 @@ function ensureSpanStateForEvent(states, config3, event, channelName, instrument
15559
15976
  states.set(key, created);
15560
15977
  return created;
15561
15978
  }
15562
- function bindCurrentSpanStoreToStart(tracingChannel2, states, config3, channelName, instrumentationName) {
15979
+ function bindCurrentSpanStoreToStart(tracingChannel, states, config3, channelName, instrumentationName) {
15563
15980
  const state = _internalGetGlobalState();
15564
- const startChannel = tracingChannel2.start;
15981
+ const startChannel = tracingChannel.start;
15565
15982
  const contextManager = state?.contextManager;
15566
15983
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
15567
15984
  if (!currentSpanStore || !startChannel) {
@@ -15644,11 +16061,11 @@ function runStreamingErrorHook(args) {
15644
16061
  }
15645
16062
  }
15646
16063
  function traceAsyncChannel(channel2, config3) {
15647
- const tracingChannel2 = channel2.tracingChannel();
16064
+ const tracingChannel = channel2.tracingChannel();
15648
16065
  const states = /* @__PURE__ */ new WeakMap();
15649
16066
  const channelName = channel2.channelName;
15650
16067
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart(
15651
- tracingChannel2,
16068
+ tracingChannel,
15652
16069
  states,
15653
16070
  config3,
15654
16071
  channelName,
@@ -15704,18 +16121,18 @@ function traceAsyncChannel(channel2, config3) {
15704
16121
  logErrorAndEnd(states, event, channelName);
15705
16122
  }
15706
16123
  };
15707
- tracingChannel2.subscribe(handlers);
16124
+ tracingChannel.subscribe(handlers);
15708
16125
  return () => {
15709
16126
  unbindCurrentSpanStore?.();
15710
- tracingChannel2.unsubscribe(handlers);
16127
+ tracingChannel.unsubscribe(handlers);
15711
16128
  };
15712
16129
  }
15713
16130
  function traceStreamingChannel(channel2, config3) {
15714
- const tracingChannel2 = channel2.tracingChannel();
16131
+ const tracingChannel = channel2.tracingChannel();
15715
16132
  const states = /* @__PURE__ */ new WeakMap();
15716
16133
  const channelName = channel2.channelName;
15717
16134
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart(
15718
- tracingChannel2,
16135
+ tracingChannel,
15719
16136
  states,
15720
16137
  config3,
15721
16138
  channelName,
@@ -15926,18 +16343,18 @@ function traceStreamingChannel(channel2, config3) {
15926
16343
  }
15927
16344
  }
15928
16345
  };
15929
- tracingChannel2.subscribe(handlers);
16346
+ tracingChannel.subscribe(handlers);
15930
16347
  return () => {
15931
16348
  unbindCurrentSpanStore?.();
15932
- tracingChannel2.unsubscribe(handlers);
16349
+ tracingChannel.unsubscribe(handlers);
15933
16350
  };
15934
16351
  }
15935
16352
  function traceSyncStreamChannel(channel2, config3) {
15936
- const tracingChannel2 = channel2.tracingChannel();
16353
+ const tracingChannel = channel2.tracingChannel();
15937
16354
  const states = /* @__PURE__ */ new WeakMap();
15938
16355
  const channelName = channel2.channelName;
15939
16356
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart(
15940
- tracingChannel2,
16357
+ tracingChannel,
15941
16358
  states,
15942
16359
  config3,
15943
16360
  channelName,
@@ -16050,10 +16467,10 @@ function traceSyncStreamChannel(channel2, config3) {
16050
16467
  logErrorAndEnd(states, event, channelName);
16051
16468
  }
16052
16469
  };
16053
- tracingChannel2.subscribe(handlers);
16470
+ tracingChannel.subscribe(handlers);
16054
16471
  return () => {
16055
16472
  unbindCurrentSpanStore?.();
16056
- tracingChannel2.unsubscribe(handlers);
16473
+ tracingChannel.unsubscribe(handlers);
16057
16474
  };
16058
16475
  }
16059
16476
  function unsubscribeAll(unsubscribers) {
@@ -16233,7 +16650,7 @@ function defineChannels(pkg, channels, options) {
16233
16650
  const fullChannelName = `orchestrion:${pkg}:${spec.channelName}`;
16234
16651
  if (spec.kind === "async") {
16235
16652
  const asyncSpec = spec;
16236
- const tracingChannel3 = () => isomorph_default.newTracingChannel(
16653
+ const tracingChannel2 = () => isomorph_default.newTracingChannel(
16237
16654
  fullChannelName
16238
16655
  );
16239
16656
  return [
@@ -16241,8 +16658,8 @@ function defineChannels(pkg, channels, options) {
16241
16658
  {
16242
16659
  ...asyncSpec,
16243
16660
  instrumentationName,
16244
- tracingChannel: tracingChannel3,
16245
- tracePromise: (fn, context2) => tracingChannel3().tracePromise(
16661
+ tracingChannel: tracingChannel2,
16662
+ tracePromise: (fn, context2) => tracingChannel2().tracePromise(
16246
16663
  fn,
16247
16664
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
16248
16665
  context2
@@ -16251,7 +16668,7 @@ function defineChannels(pkg, channels, options) {
16251
16668
  ];
16252
16669
  }
16253
16670
  const syncSpec = spec;
16254
- const tracingChannel2 = () => isomorph_default.newTracingChannel(
16671
+ const tracingChannel = () => isomorph_default.newTracingChannel(
16255
16672
  fullChannelName
16256
16673
  );
16257
16674
  return [
@@ -16259,8 +16676,8 @@ function defineChannels(pkg, channels, options) {
16259
16676
  {
16260
16677
  ...syncSpec,
16261
16678
  instrumentationName,
16262
- tracingChannel: tracingChannel2,
16263
- traceSync: (fn, context2) => tracingChannel2().traceSync(
16679
+ tracingChannel,
16680
+ traceSync: (fn, context2) => tracingChannel().traceSync(
16264
16681
  fn,
16265
16682
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
16266
16683
  context2
@@ -17592,7 +18009,7 @@ var AnthropicPlugin = class extends BasePlugin {
17592
18009
  );
17593
18010
  }
17594
18011
  subscribeToAnthropicToolRunner() {
17595
- const tracingChannel2 = anthropicChannels.betaMessagesToolRunner.tracingChannel();
18012
+ const tracingChannel = anthropicChannels.betaMessagesToolRunner.tracingChannel();
17596
18013
  const states = /* @__PURE__ */ new WeakMap();
17597
18014
  const handlers = {
17598
18015
  start: (event) => {
@@ -17649,9 +18066,9 @@ var AnthropicPlugin = class extends BasePlugin {
17649
18066
  states.delete(event);
17650
18067
  }
17651
18068
  };
17652
- tracingChannel2.subscribe(handlers);
18069
+ tracingChannel.subscribe(handlers);
17653
18070
  this.unsubscribers.push(() => {
17654
- tracingChannel2.unsubscribe(handlers);
18071
+ tracingChannel.unsubscribe(handlers);
17655
18072
  });
17656
18073
  }
17657
18074
  };
@@ -18563,8 +18980,8 @@ function registerHarnessSessionParent(session, parent) {
18563
18980
  function currentHarnessTurnParent() {
18564
18981
  return harnessTurnParentStore?.getStore() ?? wrapperTurnParents.get(currentSpan());
18565
18982
  }
18566
- function bindHarnessTurnParentToStart(tracingChannel2, parentFromEvent) {
18567
- const startChannel = tracingChannel2.start;
18983
+ function bindHarnessTurnParentToStart(tracingChannel, parentFromEvent) {
18984
+ const startChannel = tracingChannel.start;
18568
18985
  if (!startChannel) {
18569
18986
  return () => {
18570
18987
  };
@@ -24030,7 +24447,7 @@ var CursorSDKPlugin = class extends BasePlugin {
24030
24447
  this.subscribeToAgentFactory(cursorSDKChannels.resume);
24031
24448
  }
24032
24449
  subscribeToAgentFactory(channel2) {
24033
- const tracingChannel2 = channel2.tracingChannel();
24450
+ const tracingChannel = channel2.tracingChannel();
24034
24451
  const handlers = {
24035
24452
  asyncEnd: (event) => {
24036
24453
  patchCursorAgentInPlace(event.result);
@@ -24038,9 +24455,9 @@ var CursorSDKPlugin = class extends BasePlugin {
24038
24455
  error: () => {
24039
24456
  }
24040
24457
  };
24041
- tracingChannel2.subscribe(handlers);
24458
+ tracingChannel.subscribe(handlers);
24042
24459
  this.unsubscribers.push(() => {
24043
- tracingChannel2.unsubscribe(handlers);
24460
+ tracingChannel.unsubscribe(handlers);
24044
24461
  });
24045
24462
  }
24046
24463
  subscribeToPrompt() {
@@ -25396,10 +25813,10 @@ var GoogleGenAIPlugin = class extends BasePlugin {
25396
25813
  this.subscribeToInteractionsCreateChannel();
25397
25814
  }
25398
25815
  subscribeToGenerateContentChannel() {
25399
- const tracingChannel2 = googleGenAIChannels.generateContent.tracingChannel();
25816
+ const tracingChannel = googleGenAIChannels.generateContent.tracingChannel();
25400
25817
  const states = /* @__PURE__ */ new WeakMap();
25401
25818
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart2(
25402
- tracingChannel2,
25819
+ tracingChannel,
25403
25820
  states,
25404
25821
  (event) => {
25405
25822
  const params = event.arguments[0];
@@ -25473,14 +25890,14 @@ var GoogleGenAIPlugin = class extends BasePlugin {
25473
25890
  logErrorAndEndSpan(states, event);
25474
25891
  }
25475
25892
  };
25476
- tracingChannel2.subscribe(handlers);
25893
+ tracingChannel.subscribe(handlers);
25477
25894
  this.unsubscribers.push(() => {
25478
25895
  unbindCurrentSpanStore?.();
25479
- tracingChannel2.unsubscribe(handlers);
25896
+ tracingChannel.unsubscribe(handlers);
25480
25897
  });
25481
25898
  }
25482
25899
  subscribeToGenerateContentStreamChannel() {
25483
- const tracingChannel2 = googleGenAIChannels.generateContentStream.tracingChannel();
25900
+ const tracingChannel = googleGenAIChannels.generateContentStream.tracingChannel();
25484
25901
  const handlers = {
25485
25902
  start: (event) => {
25486
25903
  const streamEvent = event;
@@ -25501,16 +25918,16 @@ var GoogleGenAIPlugin = class extends BasePlugin {
25501
25918
  error: () => {
25502
25919
  }
25503
25920
  };
25504
- tracingChannel2.subscribe(handlers);
25921
+ tracingChannel.subscribe(handlers);
25505
25922
  this.unsubscribers.push(() => {
25506
- tracingChannel2.unsubscribe(handlers);
25923
+ tracingChannel.unsubscribe(handlers);
25507
25924
  });
25508
25925
  }
25509
25926
  subscribeToEmbedContentChannel() {
25510
- const tracingChannel2 = googleGenAIChannels.embedContent.tracingChannel();
25927
+ const tracingChannel = googleGenAIChannels.embedContent.tracingChannel();
25511
25928
  const states = /* @__PURE__ */ new WeakMap();
25512
25929
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart2(
25513
- tracingChannel2,
25930
+ tracingChannel,
25514
25931
  states,
25515
25932
  (event) => {
25516
25933
  const params = event.arguments[0];
@@ -25580,10 +25997,10 @@ var GoogleGenAIPlugin = class extends BasePlugin {
25580
25997
  logErrorAndEndSpan(states, event);
25581
25998
  }
25582
25999
  };
25583
- tracingChannel2.subscribe(handlers);
26000
+ tracingChannel.subscribe(handlers);
25584
26001
  this.unsubscribers.push(() => {
25585
26002
  unbindCurrentSpanStore?.();
25586
- tracingChannel2.unsubscribe(handlers);
26003
+ tracingChannel.unsubscribe(handlers);
25587
26004
  });
25588
26005
  }
25589
26006
  subscribeToInteractionsCreateChannel() {
@@ -25619,10 +26036,10 @@ function ensureSpanState(states, event, create) {
25619
26036
  states.set(event, created);
25620
26037
  return created;
25621
26038
  }
25622
- function bindCurrentSpanStoreToStart2(tracingChannel2, states, create) {
26039
+ function bindCurrentSpanStoreToStart2(tracingChannel, states, create) {
25623
26040
  const state = _internalGetGlobalState();
25624
26041
  const contextManager = state?.contextManager;
25625
- const startChannel = tracingChannel2.start;
26042
+ const startChannel = tracingChannel.start;
25626
26043
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
25627
26044
  if (!startChannel?.bindStore || !currentSpanStore) {
25628
26045
  return void 0;
@@ -26125,11 +26542,11 @@ function summarizeEmbedContentOutput(response) {
26125
26542
  };
26126
26543
  }
26127
26544
  function populateUsageMetrics(metrics, usage) {
26128
- if (usage.promptTokenCount !== void 0) {
26129
- metrics.prompt_tokens = usage.promptTokenCount;
26545
+ if (usage.promptTokenCount !== void 0 || usage.toolUsePromptTokenCount !== void 0) {
26546
+ metrics.prompt_tokens = (usage.promptTokenCount ?? 0) + (usage.toolUsePromptTokenCount ?? 0);
26130
26547
  }
26131
- if (usage.candidatesTokenCount !== void 0) {
26132
- metrics.completion_tokens = usage.candidatesTokenCount;
26548
+ if (usage.candidatesTokenCount !== void 0 || usage.thoughtsTokenCount !== void 0) {
26549
+ metrics.completion_tokens = (usage.candidatesTokenCount ?? 0) + (usage.thoughtsTokenCount ?? 0);
26133
26550
  }
26134
26551
  if (usage.totalTokenCount !== void 0) {
26135
26552
  metrics.tokens = usage.totalTokenCount;
@@ -26140,13 +26557,26 @@ function populateUsageMetrics(metrics, usage) {
26140
26557
  if (usage.thoughtsTokenCount !== void 0) {
26141
26558
  metrics.completion_reasoning_tokens = usage.thoughtsTokenCount;
26142
26559
  }
26560
+ for (const detail of usage.promptTokensDetails ?? []) {
26561
+ if (detail.modality === "AUDIO" && detail.tokenCount !== void 0) {
26562
+ metrics.prompt_audio_tokens = (metrics.prompt_audio_tokens ?? 0) + detail.tokenCount;
26563
+ }
26564
+ }
26565
+ for (const detail of usage.candidatesTokensDetails ?? []) {
26566
+ if (detail.modality === "AUDIO" && detail.tokenCount !== void 0) {
26567
+ metrics.completion_audio_tokens = (metrics.completion_audio_tokens ?? 0) + detail.tokenCount;
26568
+ }
26569
+ if (detail.modality === "IMAGE" && detail.tokenCount !== void 0) {
26570
+ metrics.completion_image_tokens = (metrics.completion_image_tokens ?? 0) + detail.tokenCount;
26571
+ }
26572
+ }
26143
26573
  }
26144
26574
  function populateInteractionUsageMetrics(metrics, usage) {
26145
26575
  if (typeof usage.total_input_tokens === "number") {
26146
26576
  metrics.prompt_tokens = usage.total_input_tokens;
26147
26577
  }
26148
26578
  if (typeof usage.total_output_tokens === "number") {
26149
- metrics.completion_tokens = usage.total_output_tokens;
26579
+ metrics.completion_tokens = usage.total_output_tokens + (typeof usage.total_thought_tokens === "number" ? usage.total_thought_tokens : 0);
26150
26580
  }
26151
26581
  if (typeof usage.total_tokens === "number") {
26152
26582
  metrics.tokens = usage.total_tokens;
@@ -26157,6 +26587,24 @@ function populateInteractionUsageMetrics(metrics, usage) {
26157
26587
  if (typeof usage.total_thought_tokens === "number") {
26158
26588
  metrics.completion_reasoning_tokens = usage.total_thought_tokens;
26159
26589
  }
26590
+ for (const detail of Array.isArray(usage.input_tokens_by_modality) ? usage.input_tokens_by_modality : []) {
26591
+ if (typeof detail?.modality === "string" && detail.modality.toLowerCase() === "audio" && typeof detail.tokens === "number") {
26592
+ metrics.prompt_audio_tokens = (metrics.prompt_audio_tokens ?? 0) + detail.tokens;
26593
+ }
26594
+ }
26595
+ for (const detail of Array.isArray(usage.output_tokens_by_modality) ? usage.output_tokens_by_modality : []) {
26596
+ if (typeof detail?.modality !== "string" || typeof detail.tokens !== "number") {
26597
+ continue;
26598
+ }
26599
+ switch (detail.modality.toLowerCase()) {
26600
+ case "audio":
26601
+ metrics.completion_audio_tokens = (metrics.completion_audio_tokens ?? 0) + detail.tokens;
26602
+ break;
26603
+ case "image":
26604
+ metrics.completion_image_tokens = (metrics.completion_image_tokens ?? 0) + detail.tokens;
26605
+ break;
26606
+ }
26607
+ }
26160
26608
  }
26161
26609
  function aggregateGenerateContentChunks(chunks, startTime, firstTokenTime) {
26162
26610
  const end = getCurrentUnixTimestamp();
@@ -26895,6 +27343,299 @@ function extractTextGenerationStreamMetadata(chunks) {
26895
27343
  return void 0;
26896
27344
  }
26897
27345
 
27346
+ // src/instrumentation/plugins/huggingface-transformers-channels.ts
27347
+ var SUPPORTED_TASKS = /* @__PURE__ */ new Set([
27348
+ "text-generation",
27349
+ "text2text-generation",
27350
+ "summarization",
27351
+ "feature-extraction",
27352
+ "question-answering"
27353
+ ]);
27354
+ var pipelineInfo = /* @__PURE__ */ new WeakMap();
27355
+ function isSupportedHuggingFaceTransformersTask(task) {
27356
+ return typeof task === "string" && SUPPORTED_TASKS.has(task);
27357
+ }
27358
+ function registerHuggingFaceTransformersPipeline(pipeline, task, model) {
27359
+ if (typeof task !== "string") {
27360
+ return;
27361
+ }
27362
+ const info = { task };
27363
+ if (typeof model === "string") {
27364
+ info.model = model;
27365
+ }
27366
+ pipelineInfo.set(pipeline, info);
27367
+ }
27368
+ function getHuggingFaceTransformersPipelineInfo(pipeline) {
27369
+ return pipeline ? pipelineInfo.get(pipeline) : void 0;
27370
+ }
27371
+ var huggingFaceTransformersChannels = defineChannels(
27372
+ "@huggingface/transformers",
27373
+ {
27374
+ pipeline: channel({
27375
+ channelName: "pipeline",
27376
+ kind: "async"
27377
+ }),
27378
+ pipelineCall: channel({
27379
+ channelName: "pipeline.call",
27380
+ kind: "async"
27381
+ })
27382
+ },
27383
+ { instrumentationName: INSTRUMENTATION_NAMES.HUGGINGFACE }
27384
+ );
27385
+
27386
+ // src/instrumentation/plugins/huggingface-transformers-plugin.ts
27387
+ var REQUEST_METADATA_KEYS = [
27388
+ "temperature",
27389
+ "top_p",
27390
+ "max_tokens",
27391
+ "stop"
27392
+ ];
27393
+ var HuggingFaceTransformersPlugin = class extends BasePlugin {
27394
+ onEnable() {
27395
+ this.subscribeToPipelineFactory();
27396
+ this.unsubscribers.push(
27397
+ traceAsyncChannel(huggingFaceTransformersChannels.pipelineCall, {
27398
+ name: (_args, event) => {
27399
+ const task = getTask(event);
27400
+ const operation = task?.replaceAll("-", "_") ?? "unknown";
27401
+ return `huggingface.transformers.${operation}`;
27402
+ },
27403
+ type: "llm" /* LLM */,
27404
+ shouldTrace: (_args, event) => isSupportedHuggingFaceTransformersTask(
27405
+ getTask(event)
27406
+ ),
27407
+ extractInput: (args, event) => ({
27408
+ input: extractInput(
27409
+ getTask(event),
27410
+ args
27411
+ ),
27412
+ metadata: extractMetadata(
27413
+ event,
27414
+ args
27415
+ )
27416
+ }),
27417
+ extractOutput: (result, event) => extractOutput(
27418
+ getTask(event),
27419
+ result
27420
+ ),
27421
+ extractMetrics: () => ({})
27422
+ })
27423
+ );
27424
+ }
27425
+ onDisable() {
27426
+ this.unsubscribers = unsubscribeAll(this.unsubscribers);
27427
+ }
27428
+ subscribeToPipelineFactory() {
27429
+ const channel2 = huggingFaceTransformersChannels.pipeline.tracingChannel();
27430
+ const handlers = {
27431
+ asyncEnd: (event) => {
27432
+ if (typeof event.result !== "function") {
27433
+ return;
27434
+ }
27435
+ registerHuggingFaceTransformersPipeline(
27436
+ event.result,
27437
+ event.arguments?.[0],
27438
+ event.arguments?.[1]
27439
+ );
27440
+ }
27441
+ };
27442
+ channel2.subscribe(handlers);
27443
+ this.unsubscribers.push(() => channel2.unsubscribe(handlers));
27444
+ }
27445
+ };
27446
+ function getTask(event) {
27447
+ const self = event.self;
27448
+ const registeredTask = getHuggingFaceTransformersPipelineInfo(self)?.task;
27449
+ if (registeredTask !== void 0) {
27450
+ return registeredTask;
27451
+ }
27452
+ if (typeof self?.task === "string") {
27453
+ return self.task;
27454
+ }
27455
+ return void 0;
27456
+ }
27457
+ function extractMetadata(event, args) {
27458
+ const metadata = {
27459
+ provider: "huggingface"
27460
+ };
27461
+ const registeredModel = getHuggingFaceTransformersPipelineInfo(
27462
+ event.self
27463
+ )?.model;
27464
+ const model = registeredModel ?? modelIdentifier(event.self);
27465
+ if (model) {
27466
+ metadata.model = model;
27467
+ }
27468
+ const task = getTask(event);
27469
+ const options = task === "question-answering" ? args[2] : args[1];
27470
+ if (isObject(options)) {
27471
+ for (const key of REQUEST_METADATA_KEYS) {
27472
+ if (options[key] !== void 0) {
27473
+ metadata[key] = options[key];
27474
+ }
27475
+ }
27476
+ }
27477
+ return metadata;
27478
+ }
27479
+ function modelIdentifier(pipeline) {
27480
+ const model = pipeline?.model;
27481
+ if (!isObject(model)) {
27482
+ return void 0;
27483
+ }
27484
+ const config3 = isObject(model.config) ? model.config : void 0;
27485
+ for (const value of [
27486
+ config3?._name_or_path,
27487
+ config3?.name_or_path,
27488
+ config3?.model_id,
27489
+ config3?.modelId,
27490
+ model.name
27491
+ ]) {
27492
+ if (typeof value === "string" && value.length > 0) {
27493
+ return value;
27494
+ }
27495
+ }
27496
+ return void 0;
27497
+ }
27498
+ function extractInput(task, args) {
27499
+ switch (task) {
27500
+ case "feature-extraction":
27501
+ return args[0];
27502
+ case "question-answering": {
27503
+ const question = args[0];
27504
+ const context2 = args[1];
27505
+ if (Array.isArray(question) && Array.isArray(context2) && question.every((value) => typeof value === "string") && context2.every((value) => typeof value === "string")) {
27506
+ return question.map((value, index) => [
27507
+ {
27508
+ role: "user",
27509
+ content: `Context:
27510
+ ${context2[index] ?? ""}
27511
+
27512
+ Question:
27513
+ ${value}`
27514
+ }
27515
+ ]);
27516
+ }
27517
+ if (typeof question === "string" && typeof context2 === "string") {
27518
+ return [
27519
+ {
27520
+ role: "user",
27521
+ content: `Context:
27522
+ ${context2}
27523
+
27524
+ Question:
27525
+ ${question}`
27526
+ }
27527
+ ];
27528
+ }
27529
+ return { context: context2, question };
27530
+ }
27531
+ }
27532
+ const input = args[0];
27533
+ if (task === "text-generation" && isChat(input)) {
27534
+ return input;
27535
+ }
27536
+ if (task === "text-generation" && Array.isArray(input) && input.every(isChat)) {
27537
+ return input;
27538
+ }
27539
+ if (typeof input === "string") {
27540
+ return [{ role: "user", content: input }];
27541
+ }
27542
+ if (Array.isArray(input) && input.every((value) => typeof value === "string")) {
27543
+ return input.map((value) => [
27544
+ {
27545
+ role: "user",
27546
+ content: value
27547
+ }
27548
+ ]);
27549
+ }
27550
+ return input;
27551
+ }
27552
+ function isChat(value) {
27553
+ return Array.isArray(value) && value.length > 0 && value.every(
27554
+ (message) => isObject(message) && typeof message.role === "string" && "content" in message
27555
+ );
27556
+ }
27557
+ function extractOutput(task, result) {
27558
+ switch (task) {
27559
+ case "feature-extraction":
27560
+ return summarizeEmbedding(result);
27561
+ case "question-answering":
27562
+ return choicesFromAnswers(result);
27563
+ default:
27564
+ return choicesFromGenerations(result);
27565
+ }
27566
+ }
27567
+ function summarizeEmbedding(result) {
27568
+ if (!isObject(result) || !Array.isArray(result.dims)) {
27569
+ return void 0;
27570
+ }
27571
+ const { dims } = result;
27572
+ if (dims.length === 0 || !dims.every((dimension) => typeof dimension === "number")) {
27573
+ return void 0;
27574
+ }
27575
+ if (dims.length === 1) {
27576
+ return { embedding_length: dims[0] };
27577
+ }
27578
+ if (dims.length === 2) {
27579
+ return {
27580
+ embedding_count: dims[0],
27581
+ embedding_length: dims[1]
27582
+ };
27583
+ }
27584
+ return {
27585
+ embedding_batch_count: dims[0],
27586
+ embedding_count: dims[1],
27587
+ embedding_length: dims.at(-1) ?? 0
27588
+ };
27589
+ }
27590
+ function choicesFromAnswers(result) {
27591
+ const answers = Array.isArray(result) ? result.flat() : [result];
27592
+ const choices = answers.flatMap((answer, index) => {
27593
+ if (!isObject(answer) || typeof answer.answer !== "string") {
27594
+ return [];
27595
+ }
27596
+ return [
27597
+ {
27598
+ index,
27599
+ finish_reason: "stop",
27600
+ message: {
27601
+ role: "assistant",
27602
+ content: answer.answer
27603
+ }
27604
+ }
27605
+ ];
27606
+ });
27607
+ return choices.length > 0 ? choices : void 0;
27608
+ }
27609
+ function choicesFromGenerations(result) {
27610
+ const generations = Array.isArray(result) ? result.flat() : [result];
27611
+ const choices = generations.flatMap((generation, index) => {
27612
+ if (!isObject(generation)) {
27613
+ return [];
27614
+ }
27615
+ const generated = generation.generated_text ?? generation.summary_text;
27616
+ let content;
27617
+ if (typeof generated === "string") {
27618
+ content = generated;
27619
+ } else if (isChat(generated)) {
27620
+ content = generated.at(-1)?.content;
27621
+ }
27622
+ if (typeof content !== "string") {
27623
+ return [];
27624
+ }
27625
+ return [
27626
+ {
27627
+ index,
27628
+ finish_reason: "stop",
27629
+ message: {
27630
+ role: "assistant",
27631
+ content
27632
+ }
27633
+ }
27634
+ ];
27635
+ });
27636
+ return choices.length > 0 ? choices : void 0;
27637
+ }
27638
+
26898
27639
  // src/instrumentation/plugins/openrouter-agent-channels.ts
26899
27640
  var openRouterAgentChannels = defineChannels(
26900
27641
  "@openrouter/agent",
@@ -27294,7 +28035,7 @@ function isWrappedTool(tool) {
27294
28035
  return Boolean(tool[OPENROUTER_WRAPPED_TOOL]);
27295
28036
  }
27296
28037
  function traceToolExecution(args) {
27297
- const tracingChannel2 = openRouterAgentChannels.toolExecute.tracingChannel();
28038
+ const tracingChannel = openRouterAgentChannels.toolExecute.tracingChannel();
27298
28039
  const input = args.args.length > 0 ? args.args[0] : void 0;
27299
28040
  const event = {
27300
28041
  arguments: [input],
@@ -27304,33 +28045,33 @@ function traceToolExecution(args) {
27304
28045
  toolCallId: args.toolCallId,
27305
28046
  toolName: args.toolName
27306
28047
  };
27307
- tracingChannel2.start.publish(event);
28048
+ tracingChannel.start.publish(event);
27308
28049
  try {
27309
28050
  const result = args.execute();
27310
- return publishToolResult(tracingChannel2, event, result);
28051
+ return publishToolResult(tracingChannel, event, result);
27311
28052
  } catch (error2) {
27312
28053
  event.error = normalizeError(error2);
27313
- tracingChannel2.error.publish(event);
28054
+ tracingChannel.error.publish(event);
27314
28055
  throw error2;
27315
28056
  }
27316
28057
  }
27317
- function publishToolResult(tracingChannel2, event, result) {
28058
+ function publishToolResult(tracingChannel, event, result) {
27318
28059
  if (isPromiseLike(result)) {
27319
28060
  return result.then(
27320
28061
  (resolved) => {
27321
28062
  event.result = resolved;
27322
- tracingChannel2.asyncEnd.publish(event);
28063
+ tracingChannel.asyncEnd.publish(event);
27323
28064
  return resolved;
27324
28065
  },
27325
28066
  (error2) => {
27326
28067
  event.error = normalizeError(error2);
27327
- tracingChannel2.error.publish(event);
28068
+ tracingChannel.error.publish(event);
27328
28069
  throw error2;
27329
28070
  }
27330
28071
  );
27331
28072
  }
27332
28073
  event.result = result;
27333
- tracingChannel2.asyncEnd.publish(event);
28074
+ tracingChannel.asyncEnd.publish(event);
27334
28075
  return result;
27335
28076
  }
27336
28077
  function getToolCallId(context2) {
@@ -28236,7 +28977,7 @@ function isWrappedTool2(tool) {
28236
28977
  return Boolean(tool[OPENROUTER_WRAPPED_TOOL2]);
28237
28978
  }
28238
28979
  function traceToolExecution2(args) {
28239
- const tracingChannel2 = openRouterChannels.toolExecute.tracingChannel();
28980
+ const tracingChannel = openRouterChannels.toolExecute.tracingChannel();
28240
28981
  const input = args.args.length > 0 ? args.args[0] : void 0;
28241
28982
  const event = {
28242
28983
  arguments: [input],
@@ -28246,33 +28987,33 @@ function traceToolExecution2(args) {
28246
28987
  toolCallId: args.toolCallId,
28247
28988
  toolName: args.toolName
28248
28989
  };
28249
- tracingChannel2.start.publish(event);
28990
+ tracingChannel.start.publish(event);
28250
28991
  try {
28251
28992
  const result = args.execute();
28252
- return publishToolResult2(tracingChannel2, event, result);
28993
+ return publishToolResult2(tracingChannel, event, result);
28253
28994
  } catch (error2) {
28254
28995
  event.error = normalizeError2(error2);
28255
- tracingChannel2.error.publish(event);
28996
+ tracingChannel.error.publish(event);
28256
28997
  throw error2;
28257
28998
  }
28258
28999
  }
28259
- function publishToolResult2(tracingChannel2, event, result) {
29000
+ function publishToolResult2(tracingChannel, event, result) {
28260
29001
  if (isPromiseLike(result)) {
28261
29002
  return result.then(
28262
29003
  (resolved) => {
28263
29004
  event.result = resolved;
28264
- tracingChannel2.asyncEnd.publish(event);
29005
+ tracingChannel.asyncEnd.publish(event);
28265
29006
  return resolved;
28266
29007
  },
28267
29008
  (error2) => {
28268
29009
  event.error = normalizeError2(error2);
28269
- tracingChannel2.error.publish(event);
29010
+ tracingChannel.error.publish(event);
28270
29011
  throw error2;
28271
29012
  }
28272
29013
  );
28273
29014
  }
28274
29015
  event.result = result;
28275
- tracingChannel2.asyncEnd.publish(event);
29016
+ tracingChannel.asyncEnd.publish(event);
28276
29017
  return result;
28277
29018
  }
28278
29019
  function getToolCallId2(context2) {
@@ -29462,7 +30203,7 @@ var GoogleADKPlugin = class extends BasePlugin {
29462
30203
  this.activeAgentSpans.clear();
29463
30204
  }
29464
30205
  subscribeToRunnerRunAsync() {
29465
- const tracingChannel2 = googleADKChannels.runnerRunAsync.tracingChannel();
30206
+ const tracingChannel = googleADKChannels.runnerRunAsync.tracingChannel();
29466
30207
  const states = /* @__PURE__ */ new WeakMap();
29467
30208
  const createState = (event) => {
29468
30209
  const params = event.arguments[0] ?? {};
@@ -29493,7 +30234,7 @@ var GoogleADKPlugin = class extends BasePlugin {
29493
30234
  return { span, startTime, events: [], contextKey };
29494
30235
  };
29495
30236
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart3(
29496
- tracingChannel2,
30237
+ tracingChannel,
29497
30238
  states,
29498
30239
  createState
29499
30240
  );
@@ -29545,14 +30286,14 @@ var GoogleADKPlugin = class extends BasePlugin {
29545
30286
  states.delete(event);
29546
30287
  }
29547
30288
  };
29548
- tracingChannel2.subscribe(handlers);
30289
+ tracingChannel.subscribe(handlers);
29549
30290
  this.unsubscribers.push(() => {
29550
30291
  unbindCurrentSpanStore?.();
29551
- tracingChannel2.unsubscribe(handlers);
30292
+ tracingChannel.unsubscribe(handlers);
29552
30293
  });
29553
30294
  }
29554
30295
  subscribeToAgentRunAsync() {
29555
- const tracingChannel2 = googleADKChannels.agentRunAsync.tracingChannel();
30296
+ const tracingChannel = googleADKChannels.agentRunAsync.tracingChannel();
29556
30297
  const states = /* @__PURE__ */ new WeakMap();
29557
30298
  const createState = (event) => {
29558
30299
  const parentContext = event.arguments[0];
@@ -29601,7 +30342,7 @@ var GoogleADKPlugin = class extends BasePlugin {
29601
30342
  return { span, startTime, events: [], contextKey, name: agentName };
29602
30343
  };
29603
30344
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart3(
29604
- tracingChannel2,
30345
+ tracingChannel,
29605
30346
  states,
29606
30347
  createState
29607
30348
  );
@@ -29653,14 +30394,14 @@ var GoogleADKPlugin = class extends BasePlugin {
29653
30394
  states.delete(event);
29654
30395
  }
29655
30396
  };
29656
- tracingChannel2.subscribe(handlers);
30397
+ tracingChannel.subscribe(handlers);
29657
30398
  this.unsubscribers.push(() => {
29658
30399
  unbindCurrentSpanStore?.();
29659
- tracingChannel2.unsubscribe(handlers);
30400
+ tracingChannel.unsubscribe(handlers);
29660
30401
  });
29661
30402
  }
29662
30403
  subscribeToToolRunAsync() {
29663
- const tracingChannel2 = googleADKChannels.toolRunAsync.tracingChannel();
30404
+ const tracingChannel = googleADKChannels.toolRunAsync.tracingChannel();
29664
30405
  const states = /* @__PURE__ */ new WeakMap();
29665
30406
  const handlers = {
29666
30407
  start: (event) => {
@@ -29727,9 +30468,9 @@ var GoogleADKPlugin = class extends BasePlugin {
29727
30468
  states.delete(event);
29728
30469
  }
29729
30470
  };
29730
- tracingChannel2.subscribe(handlers);
30471
+ tracingChannel.subscribe(handlers);
29731
30472
  this.unsubscribers.push(() => {
29732
- tracingChannel2.unsubscribe(handlers);
30473
+ tracingChannel.unsubscribe(handlers);
29733
30474
  });
29734
30475
  }
29735
30476
  };
@@ -29805,10 +30546,10 @@ function bindAsyncIterableToCurrentSpan(stream, span) {
29805
30546
  }
29806
30547
  return stream;
29807
30548
  }
29808
- function bindCurrentSpanStoreToStart3(tracingChannel2, states, create) {
30549
+ function bindCurrentSpanStoreToStart3(tracingChannel, states, create) {
29809
30550
  const state = _internalGetGlobalState();
29810
30551
  const contextManager = state?.contextManager;
29811
- const startChannel = tracingChannel2.start;
30552
+ const startChannel = tracingChannel.start;
29812
30553
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
29813
30554
  if (!startChannel?.bindStore || !currentSpanStore) {
29814
30555
  return void 0;
@@ -30060,15 +30801,32 @@ function aggregateUsageFromEvents(events) {
30060
30801
  if (usage.thoughtsTokenCount !== void 0) {
30061
30802
  aggregated.thoughtsTokenCount = (aggregated.thoughtsTokenCount ?? 0) + usage.thoughtsTokenCount;
30062
30803
  }
30804
+ if (usage.toolUsePromptTokenCount !== void 0) {
30805
+ aggregated.toolUsePromptTokenCount = (aggregated.toolUsePromptTokenCount ?? 0) + usage.toolUsePromptTokenCount;
30806
+ }
30807
+ for (const detailsField of [
30808
+ "promptTokensDetails",
30809
+ "cacheTokensDetails",
30810
+ "candidatesTokensDetails",
30811
+ "toolUsePromptTokensDetails"
30812
+ ]) {
30813
+ const details = usage[detailsField];
30814
+ if (details !== void 0) {
30815
+ aggregated[detailsField] = [
30816
+ ...aggregated[detailsField] ?? [],
30817
+ ...details
30818
+ ];
30819
+ }
30820
+ }
30063
30821
  }
30064
30822
  return hasUsage ? aggregated : void 0;
30065
30823
  }
30066
30824
  function populateUsageMetrics2(metrics, usage) {
30067
- if (usage.promptTokenCount !== void 0) {
30068
- metrics.prompt_tokens = usage.promptTokenCount;
30825
+ if (usage.promptTokenCount !== void 0 || usage.toolUsePromptTokenCount !== void 0) {
30826
+ metrics.prompt_tokens = (usage.promptTokenCount ?? 0) + (usage.toolUsePromptTokenCount ?? 0);
30069
30827
  }
30070
- if (usage.candidatesTokenCount !== void 0) {
30071
- metrics.completion_tokens = usage.candidatesTokenCount;
30828
+ if (usage.candidatesTokenCount !== void 0 || usage.thoughtsTokenCount !== void 0) {
30829
+ metrics.completion_tokens = (usage.candidatesTokenCount ?? 0) + (usage.thoughtsTokenCount ?? 0);
30072
30830
  }
30073
30831
  if (usage.totalTokenCount !== void 0) {
30074
30832
  metrics.tokens = usage.totalTokenCount;
@@ -30079,6 +30837,19 @@ function populateUsageMetrics2(metrics, usage) {
30079
30837
  if (usage.thoughtsTokenCount !== void 0) {
30080
30838
  metrics.completion_reasoning_tokens = usage.thoughtsTokenCount;
30081
30839
  }
30840
+ for (const detail of usage.promptTokensDetails ?? []) {
30841
+ if (detail.modality === "AUDIO" && detail.tokenCount !== void 0) {
30842
+ metrics.prompt_audio_tokens = (metrics.prompt_audio_tokens ?? 0) + detail.tokenCount;
30843
+ }
30844
+ }
30845
+ for (const detail of usage.candidatesTokensDetails ?? []) {
30846
+ if (detail.modality === "AUDIO" && detail.tokenCount !== void 0) {
30847
+ metrics.completion_audio_tokens = (metrics.completion_audio_tokens ?? 0) + detail.tokenCount;
30848
+ }
30849
+ if (detail.modality === "IMAGE" && detail.tokenCount !== void 0) {
30850
+ metrics.completion_image_tokens = (metrics.completion_image_tokens ?? 0) + detail.tokenCount;
30851
+ }
30852
+ }
30082
30853
  }
30083
30854
  function cleanMetrics4(metrics) {
30084
30855
  const cleaned = {};
@@ -31644,10 +32415,10 @@ var GenkitPlugin = class extends BasePlugin {
31644
32415
  this.subscribeToActionStream();
31645
32416
  }
31646
32417
  subscribeToActionRun() {
31647
- const tracingChannel2 = genkitChannels.actionRun.tracingChannel();
32418
+ const tracingChannel = genkitChannels.actionRun.tracingChannel();
31648
32419
  const states = /* @__PURE__ */ new WeakMap();
31649
32420
  const unbindCurrentSpanStore = bindActionCurrentSpanStoreToStart(
31650
- tracingChannel2,
32421
+ tracingChannel,
31651
32422
  states,
31652
32423
  (event) => startActionRunSpan(event)
31653
32424
  );
@@ -31684,17 +32455,17 @@ var GenkitPlugin = class extends BasePlugin {
31684
32455
  states.delete(event);
31685
32456
  }
31686
32457
  };
31687
- tracingChannel2.subscribe(handlers);
32458
+ tracingChannel.subscribe(handlers);
31688
32459
  this.unsubscribers.push(() => {
31689
32460
  unbindCurrentSpanStore?.();
31690
- tracingChannel2.unsubscribe(handlers);
32461
+ tracingChannel.unsubscribe(handlers);
31691
32462
  });
31692
32463
  }
31693
32464
  subscribeToActionSpan() {
31694
- const tracingChannel2 = genkitCoreChannels.actionSpan.tracingChannel();
32465
+ const tracingChannel = genkitCoreChannels.actionSpan.tracingChannel();
31695
32466
  const states = /* @__PURE__ */ new WeakMap();
31696
32467
  const unbindCurrentSpanStore = bindActionCurrentSpanStoreToStart(
31697
- tracingChannel2,
32468
+ tracingChannel,
31698
32469
  states,
31699
32470
  (event) => startActionSpan(event)
31700
32471
  );
@@ -31732,10 +32503,10 @@ var GenkitPlugin = class extends BasePlugin {
31732
32503
  states.delete(event);
31733
32504
  }
31734
32505
  };
31735
- tracingChannel2.subscribe(handlers);
32506
+ tracingChannel.subscribe(handlers);
31736
32507
  this.unsubscribers.push(() => {
31737
32508
  unbindCurrentSpanStore?.();
31738
- tracingChannel2.unsubscribe(handlers);
32509
+ tracingChannel.unsubscribe(handlers);
31739
32510
  });
31740
32511
  }
31741
32512
  subscribeToActionStream() {
@@ -31804,10 +32575,10 @@ function ensureActionSpanState(states, event, create) {
31804
32575
  }
31805
32576
  return created;
31806
32577
  }
31807
- function bindActionCurrentSpanStoreToStart(tracingChannel2, states, create) {
32578
+ function bindActionCurrentSpanStoreToStart(tracingChannel, states, create) {
31808
32579
  const state = _internalGetGlobalState();
31809
32580
  const contextManager = state?.contextManager;
31810
- const startChannel = tracingChannel2.start;
32581
+ const startChannel = tracingChannel.start;
31811
32582
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
31812
32583
  if (!startChannel?.bindStore || !currentSpanStore) {
31813
32584
  return void 0;
@@ -34169,7 +34940,7 @@ var LangChainPlugin = class extends BasePlugin {
34169
34940
  this.injectedManagers = /* @__PURE__ */ new WeakSet();
34170
34941
  }
34171
34942
  subscribeToConfigure(channel2) {
34172
- const tracingChannel2 = channel2.tracingChannel();
34943
+ const tracingChannel = channel2.tracingChannel();
34173
34944
  const handlers = {
34174
34945
  start: (event) => {
34175
34946
  injectHandlerIntoArguments(event.arguments);
@@ -34178,9 +34949,9 @@ var LangChainPlugin = class extends BasePlugin {
34178
34949
  this.injectHandler(event.result);
34179
34950
  }
34180
34951
  };
34181
- tracingChannel2.subscribe(handlers);
34952
+ tracingChannel.subscribe(handlers);
34182
34953
  this.unsubscribers.push(() => {
34183
- tracingChannel2.unsubscribe(handlers);
34954
+ tracingChannel.unsubscribe(handlers);
34184
34955
  });
34185
34956
  }
34186
34957
  injectHandler(result) {
@@ -34444,7 +35215,7 @@ var LangSmithPlugin = class extends BasePlugin {
34444
35215
  const inputs = preferOwnValue(run2, previous, "inputs");
34445
35216
  const outputs = preferOwnValue(run2, previous, "outputs");
34446
35217
  const error2 = errorMessage(preferOwnValue(run2, previous, "error"));
34447
- const metadata = extractMetadata(run2, previous);
35218
+ const metadata = extractMetadata2(run2, previous);
34448
35219
  const tags = extractTags(preferOwnValue(run2, previous, "tags"));
34449
35220
  const metrics = extractMetrics(run2, previous);
34450
35221
  span.log({
@@ -34549,7 +35320,7 @@ function mapRunType(runType) {
34549
35320
  return "task" /* TASK */;
34550
35321
  }
34551
35322
  }
34552
- function extractMetadata(run2, previous) {
35323
+ function extractMetadata2(run2, previous) {
34553
35324
  const extra = preferOwnValue(run2, previous, "extra");
34554
35325
  const rawMetadata = ownValue(extra, "metadata");
34555
35326
  if (!isRecord2(rawMetadata)) {
@@ -35680,9 +36451,9 @@ var StrandsAgentSDKPlugin = class extends BasePlugin {
35680
36451
  });
35681
36452
  }
35682
36453
  subscribeToMultiAgentStream(channel2, operation) {
35683
- const tracingChannel2 = channel2.tracingChannel();
36454
+ const tracingChannel = channel2.tracingChannel();
35684
36455
  const states = /* @__PURE__ */ new WeakMap();
35685
- const unbindAutoInstrumentationSuppression = bindAutoInstrumentationSuppressionToStart(tracingChannel2);
36456
+ const unbindAutoInstrumentationSuppression = bindAutoInstrumentationSuppressionToStart(tracingChannel);
35686
36457
  const handlers = {
35687
36458
  start: (event) => {
35688
36459
  const state = startMultiAgentStream(
@@ -35736,10 +36507,10 @@ var StrandsAgentSDKPlugin = class extends BasePlugin {
35736
36507
  states.delete(event);
35737
36508
  }
35738
36509
  };
35739
- tracingChannel2.subscribe(handlers);
36510
+ tracingChannel.subscribe(handlers);
35740
36511
  this.unsubscribers.push(() => {
35741
36512
  unbindAutoInstrumentationSuppression?.();
35742
- tracingChannel2.unsubscribe(handlers);
36513
+ tracingChannel.unsubscribe(handlers);
35743
36514
  });
35744
36515
  }
35745
36516
  };
@@ -35922,6 +36693,15 @@ function handleMultiAgentStreamEvent(state, event, activeChildParents) {
35922
36693
  logInstrumentationError5("Strands Agent SDK multi-agent event", error2);
35923
36694
  }
35924
36695
  }
36696
+ function buildModelSpanInput(event, attachmentCache) {
36697
+ const systemPrompt = typeof event.agent?.systemPrompt === "string" && event.agent.systemPrompt.length > 0 ? event.agent.systemPrompt : void 0;
36698
+ const processedMessages = Array.isArray(event.agent?.messages) ? processStrandsInputAttachments(event.agent.messages, attachmentCache) : void 0;
36699
+ if (!systemPrompt) {
36700
+ return processedMessages;
36701
+ }
36702
+ const systemMessage = { role: "system", content: systemPrompt };
36703
+ return Array.isArray(processedMessages) ? [systemMessage, ...processedMessages] : [systemMessage];
36704
+ }
35925
36705
  function startModelSpan(state, event) {
35926
36706
  if (state.activeModel) {
35927
36707
  finalizeModelSpan(state);
@@ -35939,10 +36719,7 @@ function startModelSpan(state, event) {
35939
36719
  withSpanInstrumentationName(
35940
36720
  {
35941
36721
  event: {
35942
- input: Array.isArray(event.agent?.messages) ? processStrandsInputAttachments(
35943
- event.agent.messages,
35944
- state.attachmentCache
35945
- ) : void 0,
36722
+ input: buildModelSpanInput(event, state.attachmentCache),
35946
36723
  metadata
35947
36724
  },
35948
36725
  name: formatModelSpanName(model),
@@ -36582,6 +37359,532 @@ function logInstrumentationError5(context2, error2) {
36582
37359
  debugLogger.debug(`${context2}:`, error2);
36583
37360
  }
36584
37361
 
37362
+ // src/instrumentation/plugins/cloudflare-ai-chat-channels.ts
37363
+ var cloudflareAIChatChannels = defineChannels(
37364
+ "@cloudflare/ai-chat",
37365
+ {
37366
+ runExclusiveChatTurn: channel({
37367
+ channelName: "AIChatAgent._runExclusiveChatTurn",
37368
+ kind: "async"
37369
+ }),
37370
+ onChatResponse: channel({
37371
+ channelName: "AIChatAgent.onChatResponse",
37372
+ kind: "sync-stream"
37373
+ })
37374
+ },
37375
+ { instrumentationName: INSTRUMENTATION_NAMES.CLOUDFLARE_AI_CHAT }
37376
+ );
37377
+
37378
+ // src/instrumentation/plugins/cloudflare-ai-chat-instrumentation.ts
37379
+ var wrappedResponseHooks = /* @__PURE__ */ new WeakSet();
37380
+ function instrumentCloudflareAIChatResponseHook(agent) {
37381
+ try {
37382
+ const original = Reflect.get(agent, "onChatResponse");
37383
+ if (typeof original !== "function" || wrappedResponseHooks.has(original)) {
37384
+ return;
37385
+ }
37386
+ const wrapped = function(result) {
37387
+ const args = [result];
37388
+ return cloudflareAIChatChannels.onChatResponse.traceSync(
37389
+ () => Reflect.apply(original, this, args),
37390
+ {
37391
+ arguments: args,
37392
+ self: this
37393
+ }
37394
+ );
37395
+ };
37396
+ wrappedResponseHooks.add(wrapped);
37397
+ defineWrappedMethod(agent, "onChatResponse", original, wrapped);
37398
+ } catch (error2) {
37399
+ debugLogger.debug(
37400
+ "Failed to wrap @cloudflare/ai-chat response hook:",
37401
+ error2
37402
+ );
37403
+ }
37404
+ }
37405
+ function defineWrappedMethod(target, property, original, wrapped) {
37406
+ const ownDescriptor = Object.getOwnPropertyDescriptor(target, property);
37407
+ Object.defineProperty(target, property, {
37408
+ configurable: ownDescriptor?.configurable ?? true,
37409
+ enumerable: ownDescriptor?.enumerable ?? false,
37410
+ value: wrapped,
37411
+ writable: ownDescriptor && "writable" in ownDescriptor ? ownDescriptor.writable : true
37412
+ });
37413
+ try {
37414
+ Object.defineProperty(wrapped, "name", {
37415
+ configurable: true,
37416
+ value: original.name
37417
+ });
37418
+ } catch {
37419
+ }
37420
+ }
37421
+
37422
+ // src/instrumentation/plugins/cloudflare-ai-chat-plugin.ts
37423
+ var BLOCKED_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
37424
+ var RESPONSE_STATE_RETENTION_MS = 6e4;
37425
+ var CloudflareAIChatPlugin = class extends BasePlugin {
37426
+ activeStates = /* @__PURE__ */ new Set();
37427
+ activeTurns = /* @__PURE__ */ new WeakMap();
37428
+ eventStates = /* @__PURE__ */ new WeakMap();
37429
+ onEnable() {
37430
+ this.subscribeToResponseHook();
37431
+ this.subscribeToTurnRunner();
37432
+ }
37433
+ onDisable() {
37434
+ for (const unsubscribe of this.unsubscribers) {
37435
+ unsubscribe();
37436
+ }
37437
+ this.unsubscribers = [];
37438
+ for (const state of this.activeStates) {
37439
+ this.cleanupState(state);
37440
+ }
37441
+ this.activeStates.clear();
37442
+ }
37443
+ subscribeToTurnRunner() {
37444
+ const tracingChannel = cloudflareAIChatChannels.runExclusiveChatTurn.tracingChannel();
37445
+ const unbindCurrentSpanStore = this.bindCurrentSpanStore(tracingChannel);
37446
+ const handlers = {
37447
+ start: (event) => {
37448
+ this.ensureEventState(event);
37449
+ },
37450
+ asyncEnd: (event) => {
37451
+ this.finishEvent(event);
37452
+ },
37453
+ error: (event) => {
37454
+ this.finishEvent(event, event.error);
37455
+ }
37456
+ };
37457
+ tracingChannel.subscribe(handlers);
37458
+ this.unsubscribers.push(() => {
37459
+ unbindCurrentSpanStore?.();
37460
+ tracingChannel.unsubscribe(handlers);
37461
+ });
37462
+ }
37463
+ subscribeToResponseHook() {
37464
+ const tracingChannel = cloudflareAIChatChannels.onChatResponse.tracingChannel();
37465
+ const handlers = {
37466
+ start: (event) => {
37467
+ let state;
37468
+ try {
37469
+ const agent = asObject(event.self);
37470
+ const result = event.arguments[0];
37471
+ state = agent ? this.findResponseState(
37472
+ agent,
37473
+ stringValue3(ownValue2(result, "requestId"))
37474
+ ) : void 0;
37475
+ if (!state) {
37476
+ return;
37477
+ }
37478
+ state.responseObserved = true;
37479
+ const output = serializeMessage(ownValue2(result, "message"));
37480
+ const status = stringValue3(ownValue2(result, "status"));
37481
+ const error2 = ownValue2(result, "error");
37482
+ const input = ownValue2(result, "continuation") === true ? state.input : serializeMessages(readProperty(agent, "messages"))?.filter(
37483
+ (message) => typeof output?.id !== "string" || message.id !== output.id
37484
+ );
37485
+ state.span.log({
37486
+ ...input !== void 0 ? { input } : {},
37487
+ ...output !== void 0 ? { output } : {},
37488
+ ...status === "error" && error2 !== void 0 ? { error: error2 } : {}
37489
+ });
37490
+ } catch (error2) {
37491
+ debugLogger.debug(
37492
+ "Failed to process @cloudflare/ai-chat response hook:",
37493
+ error2
37494
+ );
37495
+ } finally {
37496
+ if (state?.settled) {
37497
+ this.cleanupState(state);
37498
+ }
37499
+ }
37500
+ }
37501
+ };
37502
+ tracingChannel.subscribe(handlers);
37503
+ this.unsubscribers.push(() => tracingChannel.unsubscribe(handlers));
37504
+ }
37505
+ bindCurrentSpanStore(tracingChannel) {
37506
+ const globalState = _internalGetGlobalState();
37507
+ const contextManager = globalState?.contextManager;
37508
+ const startChannel = tracingChannel.start;
37509
+ const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
37510
+ if (!startChannel || !currentSpanStore || !contextManager) {
37511
+ return void 0;
37512
+ }
37513
+ startChannel.bindStore(currentSpanStore, (event) => {
37514
+ const state = this.ensureEventState(event);
37515
+ return state ? contextManager.wrapSpanForStore(state.span) : currentSpanStore.getStore();
37516
+ });
37517
+ return () => startChannel.unbindStore(currentSpanStore);
37518
+ }
37519
+ ensureEventState(event) {
37520
+ const eventKey = event;
37521
+ const known = this.eventStates.get(eventKey);
37522
+ if (known) {
37523
+ return known;
37524
+ }
37525
+ try {
37526
+ const agent = asObject(event.self);
37527
+ const requestId = stringValue3(event.arguments[0]);
37528
+ const key = requestId ?? /* @__PURE__ */ Symbol("cloudflare-ai-chat-turn");
37529
+ const activeForAgent = agent ? this.getActiveTurns(agent) : void 0;
37530
+ const existing = activeForAgent?.get(key);
37531
+ const state = existing && !existing.settled ? existing : this.createTurnState(agent, key);
37532
+ if (existing && !existing.settled) {
37533
+ state.depth += 1;
37534
+ }
37535
+ this.eventStates.set(eventKey, state);
37536
+ this.bindTurnCallback(event, agent, state);
37537
+ if (agent) {
37538
+ instrumentCloudflareAIChatResponseHook(agent);
37539
+ }
37540
+ return state;
37541
+ } catch (error2) {
37542
+ debugLogger.debug(
37543
+ "Failed to start @cloudflare/ai-chat instrumentation:",
37544
+ error2
37545
+ );
37546
+ return void 0;
37547
+ }
37548
+ }
37549
+ createTurnState(agent, key) {
37550
+ const span = startSpan(
37551
+ withSpanInstrumentationName(
37552
+ {
37553
+ name: "AIChatAgent.onChatMessage",
37554
+ spanAttributes: { type: "task" /* TASK */ }
37555
+ },
37556
+ INSTRUMENTATION_NAMES.CLOUDFLARE_AI_CHAT
37557
+ )
37558
+ );
37559
+ const state = {
37560
+ agent,
37561
+ depth: 1,
37562
+ ended: false,
37563
+ key,
37564
+ responseObserved: false,
37565
+ settled: false,
37566
+ span
37567
+ };
37568
+ this.activeStates.add(state);
37569
+ if (agent) {
37570
+ this.getActiveTurns(agent).set(key, state);
37571
+ }
37572
+ return state;
37573
+ }
37574
+ bindTurnCallback(event, agent, state) {
37575
+ const callback = event.arguments[1];
37576
+ if (typeof callback !== "function") {
37577
+ return;
37578
+ }
37579
+ try {
37580
+ event.arguments[1] = function(...args) {
37581
+ return withCurrent(state.span, () => {
37582
+ try {
37583
+ const input = serializeMessages(readProperty(agent, "messages"));
37584
+ if (input !== void 0 && state.input === void 0) {
37585
+ state.input = input;
37586
+ state.span.log({ input });
37587
+ }
37588
+ } catch (error2) {
37589
+ debugLogger.debug(
37590
+ "Failed to capture @cloudflare/ai-chat messages:",
37591
+ error2
37592
+ );
37593
+ }
37594
+ return Reflect.apply(callback, this, args);
37595
+ });
37596
+ };
37597
+ } catch (error2) {
37598
+ debugLogger.debug(
37599
+ "Failed to bind @cloudflare/ai-chat turn callback context:",
37600
+ error2
37601
+ );
37602
+ }
37603
+ }
37604
+ finishEvent(event, error2) {
37605
+ const eventKey = event;
37606
+ const state = this.eventStates.get(eventKey);
37607
+ if (!state || state.ended) {
37608
+ return;
37609
+ }
37610
+ this.eventStates.delete(eventKey);
37611
+ if (error2 !== void 0 && state.pendingError === void 0) {
37612
+ state.pendingError = error2;
37613
+ }
37614
+ state.depth -= 1;
37615
+ if (state.depth === 0) {
37616
+ state.settled = true;
37617
+ this.endState(state);
37618
+ if (state.responseObserved || error2 !== void 0) {
37619
+ this.cleanupState(state);
37620
+ } else {
37621
+ state.cleanupTimer = setTimeout(
37622
+ () => this.cleanupState(state),
37623
+ RESPONSE_STATE_RETENTION_MS
37624
+ );
37625
+ if (typeof state.cleanupTimer === "object" && state.cleanupTimer !== null && "unref" in state.cleanupTimer && typeof state.cleanupTimer.unref === "function") {
37626
+ state.cleanupTimer.unref();
37627
+ }
37628
+ }
37629
+ }
37630
+ }
37631
+ endState(state) {
37632
+ if (state.ended) {
37633
+ return;
37634
+ }
37635
+ state.ended = true;
37636
+ try {
37637
+ if (state.pendingError !== void 0) {
37638
+ state.span.log({ error: state.pendingError });
37639
+ }
37640
+ } finally {
37641
+ state.span.end();
37642
+ }
37643
+ }
37644
+ cleanupState(state) {
37645
+ if (state.cleanupTimer !== void 0) {
37646
+ clearTimeout(state.cleanupTimer);
37647
+ state.cleanupTimer = void 0;
37648
+ }
37649
+ try {
37650
+ this.endState(state);
37651
+ } finally {
37652
+ this.activeStates.delete(state);
37653
+ if (state.agent) {
37654
+ const activeForAgent = this.activeTurns.get(state.agent);
37655
+ if (activeForAgent?.get(state.key) === state) {
37656
+ activeForAgent.delete(state.key);
37657
+ }
37658
+ }
37659
+ }
37660
+ }
37661
+ getActiveTurns(agent) {
37662
+ let turns = this.activeTurns.get(agent);
37663
+ if (!turns) {
37664
+ turns = /* @__PURE__ */ new Map();
37665
+ this.activeTurns.set(agent, turns);
37666
+ }
37667
+ return turns;
37668
+ }
37669
+ findResponseState(agent, requestId) {
37670
+ const turns = this.activeTurns.get(agent);
37671
+ if (!turns) {
37672
+ return void 0;
37673
+ }
37674
+ if (requestId !== void 0) {
37675
+ return turns.get(requestId);
37676
+ }
37677
+ const active = [...turns.values()];
37678
+ return active.length === 1 ? active[0] : void 0;
37679
+ }
37680
+ };
37681
+ function asObject(value) {
37682
+ return value !== null && (typeof value === "object" || typeof value === "function") ? value : void 0;
37683
+ }
37684
+ function readProperty(value, key) {
37685
+ const object = asObject(value);
37686
+ return object ? Reflect.get(object, key) : void 0;
37687
+ }
37688
+ function ownValue2(value, key) {
37689
+ const object = asObject(value);
37690
+ if (!object) {
37691
+ return void 0;
37692
+ }
37693
+ const descriptor = Object.getOwnPropertyDescriptor(object, key);
37694
+ return descriptor && "value" in descriptor ? descriptor.value : void 0;
37695
+ }
37696
+ function stringValue3(value) {
37697
+ return typeof value === "string" ? value : void 0;
37698
+ }
37699
+ function serializeMessages(value) {
37700
+ if (!Array.isArray(value)) {
37701
+ return void 0;
37702
+ }
37703
+ return value.flatMap((message) => {
37704
+ const serialized = serializeMessage(message);
37705
+ return serialized === void 0 ? [] : [serialized];
37706
+ });
37707
+ }
37708
+ function serializeMessage(value) {
37709
+ const message = asObject(value);
37710
+ if (!message) {
37711
+ return void 0;
37712
+ }
37713
+ const serialized = [];
37714
+ const id = ownValue2(message, "id");
37715
+ const role = ownValue2(message, "role");
37716
+ const parts = ownValue2(message, "parts");
37717
+ if (typeof id === "string") {
37718
+ serialized.push(["id", id]);
37719
+ }
37720
+ if (typeof role === "string") {
37721
+ serialized.push(["role", role]);
37722
+ }
37723
+ const sanitizedParts = sanitizeLoggedValue2(parts);
37724
+ if (sanitizedParts !== void 0) {
37725
+ serialized.push(["parts", sanitizedParts]);
37726
+ }
37727
+ return serialized.length > 0 ? Object.fromEntries(serialized) : void 0;
37728
+ }
37729
+ function sanitizeLoggedValue2(value, seen = /* @__PURE__ */ new WeakSet(), depth = 0) {
37730
+ if (value === null || typeof value === "string" || typeof value === "boolean") {
37731
+ return value;
37732
+ }
37733
+ if (typeof value === "number") {
37734
+ return Number.isFinite(value) ? value : void 0;
37735
+ }
37736
+ const object = asObject(value);
37737
+ if (!object || depth >= 20 || typeof value === "function") {
37738
+ return void 0;
37739
+ }
37740
+ if (seen.has(object)) {
37741
+ return "[Circular]";
37742
+ }
37743
+ seen.add(object);
37744
+ if (Array.isArray(value)) {
37745
+ return value.map((entry) => sanitizeLoggedValue2(entry, seen, depth + 1));
37746
+ }
37747
+ const entries = [];
37748
+ for (const [key, descriptor] of Object.entries(
37749
+ Object.getOwnPropertyDescriptors(object)
37750
+ )) {
37751
+ if (BLOCKED_KEYS.has(key) || !descriptor.enumerable || !("value" in descriptor)) {
37752
+ continue;
37753
+ }
37754
+ const sanitized = sanitizeLoggedValue2(descriptor.value, seen, depth + 1);
37755
+ if (sanitized !== void 0) {
37756
+ entries.push([key, sanitized]);
37757
+ }
37758
+ }
37759
+ return Object.fromEntries(entries);
37760
+ }
37761
+
37762
+ // src/instrumentation/plugins/cloudflare-agents-channels.ts
37763
+ var cloudflareAgentsChannels = defineChannels(
37764
+ "agents",
37765
+ {
37766
+ runAgentTool: channel({
37767
+ channelName: "Agent.runAgentTool",
37768
+ kind: "async"
37769
+ })
37770
+ },
37771
+ { instrumentationName: INSTRUMENTATION_NAMES.CLOUDFLARE_AGENTS }
37772
+ );
37773
+
37774
+ // src/instrumentation/plugins/cloudflare-agents-plugin.ts
37775
+ var CLOUDFLARE_WORKERS_CONTEXT = {
37776
+ span_origin: {
37777
+ environment: { type: "server", name: "cloudflare_workers" }
37778
+ }
37779
+ };
37780
+ var CloudflareAgentsPlugin = class extends BasePlugin {
37781
+ onEnable() {
37782
+ const channel2 = cloudflareAgentsChannels.runAgentTool.tracingChannel();
37783
+ const spans = /* @__PURE__ */ new WeakMap();
37784
+ const handlers = {
37785
+ start: (event) => {
37786
+ try {
37787
+ const agentClass = event.arguments[0];
37788
+ const options = event.arguments[1];
37789
+ if (ownValue3(options, "detached")) {
37790
+ return;
37791
+ }
37792
+ const name = ownValue3(agentClass, "name");
37793
+ if (typeof name !== "string" || name.length === 0) {
37794
+ debugLogger.warn(
37795
+ "Skipping Cloudflare Agents runAgentTool span because the child agent class has no name."
37796
+ );
37797
+ return;
37798
+ }
37799
+ const span = _internalStartSpanWithContext(
37800
+ withSpanInstrumentationName(
37801
+ {
37802
+ name,
37803
+ spanAttributes: { type: "tool" /* TOOL */ },
37804
+ event: {
37805
+ input: ownValue3(options, "input")
37806
+ }
37807
+ },
37808
+ INSTRUMENTATION_NAMES.CLOUDFLARE_AGENTS
37809
+ ),
37810
+ CLOUDFLARE_WORKERS_CONTEXT
37811
+ );
37812
+ spans.set(event, span);
37813
+ } catch (error2) {
37814
+ logInstrumentationError6("start", error2);
37815
+ }
37816
+ },
37817
+ asyncEnd: (event) => {
37818
+ const span = spans.get(event);
37819
+ if (!span) {
37820
+ return;
37821
+ }
37822
+ spans.delete(event);
37823
+ try {
37824
+ const status = ownValue3(event.result, "status");
37825
+ if (status === "completed") {
37826
+ span.log({ output: ownValue3(event.result, "output") });
37827
+ } else {
37828
+ const error2 = ownValue3(event.result, "error");
37829
+ if (typeof error2 === "string") {
37830
+ span.log({ error: error2 });
37831
+ }
37832
+ }
37833
+ } catch (error2) {
37834
+ logInstrumentationError6("completion", error2);
37835
+ } finally {
37836
+ safelyEndSpan(span);
37837
+ }
37838
+ },
37839
+ error: (event) => {
37840
+ const span = spans.get(event);
37841
+ if (!span) {
37842
+ return;
37843
+ }
37844
+ spans.delete(event);
37845
+ try {
37846
+ span.log({ error: event.error });
37847
+ } catch (error2) {
37848
+ logInstrumentationError6("rejection", error2);
37849
+ } finally {
37850
+ safelyEndSpan(span);
37851
+ }
37852
+ }
37853
+ };
37854
+ channel2.subscribe(handlers);
37855
+ this.unsubscribers.push(() => channel2.unsubscribe(handlers));
37856
+ }
37857
+ onDisable() {
37858
+ for (const unsubscribe of this.unsubscribers) {
37859
+ unsubscribe();
37860
+ }
37861
+ this.unsubscribers = [];
37862
+ }
37863
+ };
37864
+ function ownValue3(value, key) {
37865
+ if (!isObjectLike2(value)) {
37866
+ return void 0;
37867
+ }
37868
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
37869
+ return descriptor && "value" in descriptor ? descriptor.value : void 0;
37870
+ }
37871
+ function isObjectLike2(value) {
37872
+ return typeof value === "object" && value !== null || typeof value === "function";
37873
+ }
37874
+ function safelyEndSpan(span) {
37875
+ try {
37876
+ span.end();
37877
+ } catch (error2) {
37878
+ logInstrumentationError6("span end", error2);
37879
+ }
37880
+ }
37881
+ function logInstrumentationError6(operation, error2) {
37882
+ debugLogger.error(
37883
+ `Failed to process Cloudflare Agents ${operation} instrumentation:`,
37884
+ error2
37885
+ );
37886
+ }
37887
+
36585
37888
  // src/instrumentation/braintrust-plugin.ts
36586
37889
  var BraintrustPlugin = class extends BasePlugin {
36587
37890
  config;
@@ -36594,6 +37897,7 @@ var BraintrustPlugin = class extends BasePlugin {
36594
37897
  openAIAgentsPlugin = null;
36595
37898
  googleGenAIPlugin = null;
36596
37899
  huggingFacePlugin = null;
37900
+ huggingFaceTransformersPlugin = null;
36597
37901
  openRouterPlugin = null;
36598
37902
  openRouterAgentPlugin = null;
36599
37903
  mistralPlugin = null;
@@ -36608,6 +37912,8 @@ var BraintrustPlugin = class extends BasePlugin {
36608
37912
  langSmithPlugin = null;
36609
37913
  piCodingAgentPlugin = null;
36610
37914
  strandsAgentSDKPlugin = null;
37915
+ cloudflareAIChatPlugin = null;
37916
+ cloudflareAgentsPlugin = null;
36611
37917
  constructor(config3 = {}) {
36612
37918
  super();
36613
37919
  this.config = config3;
@@ -36649,6 +37955,8 @@ var BraintrustPlugin = class extends BasePlugin {
36649
37955
  if (integrations.huggingface !== false) {
36650
37956
  this.huggingFacePlugin = new HuggingFacePlugin();
36651
37957
  this.huggingFacePlugin.enable();
37958
+ this.huggingFaceTransformersPlugin = new HuggingFaceTransformersPlugin();
37959
+ this.huggingFaceTransformersPlugin.enable();
36652
37960
  }
36653
37961
  if (integrations.openrouter !== false) {
36654
37962
  this.openRouterPlugin = new OpenRouterPlugin();
@@ -36694,6 +38002,14 @@ var BraintrustPlugin = class extends BasePlugin {
36694
38002
  this.strandsAgentSDKPlugin = new StrandsAgentSDKPlugin();
36695
38003
  this.strandsAgentSDKPlugin.enable();
36696
38004
  }
38005
+ if (integrations.cloudflareAIChat !== false) {
38006
+ this.cloudflareAIChatPlugin = new CloudflareAIChatPlugin();
38007
+ this.cloudflareAIChatPlugin.enable();
38008
+ }
38009
+ if (integrations.cloudflareAgents !== false) {
38010
+ this.cloudflareAgentsPlugin = new CloudflareAgentsPlugin();
38011
+ this.cloudflareAgentsPlugin.enable();
38012
+ }
36697
38013
  if (integrations.flue !== false) {
36698
38014
  this.fluePlugin = new FluePlugin();
36699
38015
  this.fluePlugin.enable();
@@ -36746,6 +38062,10 @@ var BraintrustPlugin = class extends BasePlugin {
36746
38062
  this.huggingFacePlugin.disable();
36747
38063
  this.huggingFacePlugin = null;
36748
38064
  }
38065
+ if (this.huggingFaceTransformersPlugin) {
38066
+ this.huggingFaceTransformersPlugin.disable();
38067
+ this.huggingFaceTransformersPlugin = null;
38068
+ }
36749
38069
  if (this.openRouterPlugin) {
36750
38070
  this.openRouterPlugin.disable();
36751
38071
  this.openRouterPlugin = null;
@@ -36790,6 +38110,14 @@ var BraintrustPlugin = class extends BasePlugin {
36790
38110
  this.strandsAgentSDKPlugin.disable();
36791
38111
  this.strandsAgentSDKPlugin = null;
36792
38112
  }
38113
+ if (this.cloudflareAIChatPlugin) {
38114
+ this.cloudflareAIChatPlugin.disable();
38115
+ this.cloudflareAIChatPlugin = null;
38116
+ }
38117
+ if (this.cloudflareAgentsPlugin) {
38118
+ this.cloudflareAgentsPlugin.disable();
38119
+ this.cloudflareAgentsPlugin = null;
38120
+ }
36793
38121
  if (this.fluePlugin) {
36794
38122
  this.fluePlugin.disable();
36795
38123
  this.fluePlugin = null;
@@ -36822,6 +38150,9 @@ var envIntegrationAliases = {
36822
38150
  strandsagentsdk: "strandsAgentSDK",
36823
38151
  "strands-agent-sdk": "strandsAgentSDK",
36824
38152
  "@strands-agents/sdk": "strandsAgentSDK",
38153
+ agents: "cloudflareAgents",
38154
+ "cloudflare-agents": "cloudflareAgents",
38155
+ cloudflareagents: "cloudflareAgents",
36825
38156
  anthropic: "anthropic",
36826
38157
  aisdk: "aisdk",
36827
38158
  "ai-sdk": "aisdk",
@@ -36829,6 +38160,9 @@ var envIntegrationAliases = {
36829
38160
  vercel: "vercel",
36830
38161
  claudeagentsdk: "claudeAgentSDK",
36831
38162
  "claude-agent-sdk": "claudeAgentSDK",
38163
+ cloudflareaichat: "cloudflareAIChat",
38164
+ "cloudflare-ai-chat": "cloudflareAIChat",
38165
+ "@cloudflare/ai-chat": "cloudflareAIChat",
36832
38166
  cursor: "cursor",
36833
38167
  "cursor-sdk": "cursorSDK",
36834
38168
  cursorsdk: "cursorSDK",
@@ -36843,6 +38177,8 @@ var envIntegrationAliases = {
36843
38177
  "google-genai": "googleGenAI",
36844
38178
  googlegenai: "googleGenAI",
36845
38179
  huggingface: "huggingface",
38180
+ "@huggingface/transformers": "huggingface",
38181
+ transformers: "huggingface",
36846
38182
  openrouter: "openrouter",
36847
38183
  openrouteragent: "openrouterAgent",
36848
38184
  "openrouter-agent": "openrouterAgent",
@@ -36881,6 +38217,7 @@ function getDefaultInstrumentationIntegrations() {
36881
38217
  googleADK: true,
36882
38218
  huggingface: true,
36883
38219
  claudeAgentSDK: true,
38220
+ cloudflareAIChat: true,
36884
38221
  cursor: true,
36885
38222
  cursorSDK: true,
36886
38223
  flue: true,
@@ -36900,7 +38237,8 @@ function getDefaultInstrumentationIntegrations() {
36900
38237
  langgraph: true,
36901
38238
  langsmith: true,
36902
38239
  piCodingAgent: true,
36903
- strandsAgentSDK: true
38240
+ strandsAgentSDK: true,
38241
+ cloudflareAgents: true
36904
38242
  };
36905
38243
  }
36906
38244
  function readDisabledInstrumentationEnvConfig(disabledList) {
@@ -36921,7 +38259,9 @@ function isInstrumentationIntegrationDisabled(integrations, ...names) {
36921
38259
  }
36922
38260
 
36923
38261
  // src/instrumentation/registry.ts
36924
- var REGISTRY_STATE_KEY = /* @__PURE__ */ Symbol.for("braintrust.registry");
38262
+ var REGISTRY_STATE_KEY = /* @__PURE__ */ Symbol.for(
38263
+ `braintrust.registry.global-hooks.v${GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION}`
38264
+ );
36925
38265
  function getSharedState() {
36926
38266
  const state = globalThis[/* @__PURE__ */ Symbol.for("braintrust-state")];
36927
38267
  return state && typeof state === "object" ? state : void 0;
@@ -37357,8 +38697,6 @@ function configureNode() {
37357
38697
  };
37358
38698
  isomorph_default.getCallerLocation = getCallerLocation;
37359
38699
  isomorph_default.newAsyncLocalStorage = () => new import_node_async_hooks.AsyncLocalStorage();
37360
- isomorph_default.newTracingChannel = (nameOrChannels) => diagnostics_channel.tracingChannel(nameOrChannels);
37361
- patchTracingChannel(diagnostics_channel.tracingChannel);
37362
38700
  isomorph_default.processOn = (event, handler) => {
37363
38701
  process.on(event, handler);
37364
38702
  };