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/browser.mjs CHANGED
@@ -4,87 +4,528 @@ var __export = (target, all) => {
4
4
  __defProp(target, name, { get: all[name], enumerable: true });
5
5
  };
6
6
 
7
- // src/browser/config.ts
8
- import { tracingChannel } from "dc-browser";
9
-
10
- // src/isomorph.ts
11
- var DefaultAsyncLocalStorage = class {
12
- constructor() {
13
- }
14
- enterWith(_) {
15
- }
16
- run(_, callback) {
17
- return callback();
7
+ // src/global-instrumentation-hooks.ts
8
+ var GLOBAL_INSTRUMENTATION_HOOKS_KEY = "__braintrust_instrumentation_hooks";
9
+ var GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION = 1;
10
+ var GLOBAL_INSTRUMENTATION_HOOKS_REGISTRY_BRAND = "braintrust.global-instrumentation-hooks.registry";
11
+ var GLOBAL_INSTRUMENTATION_HOOK_BRAND = "braintrust.global-instrumentation-hooks.hook";
12
+ var registryBrand = Symbol.for(GLOBAL_INSTRUMENTATION_HOOKS_REGISTRY_BRAND);
13
+ var hookBrand = Symbol.for(GLOBAL_INSTRUMENTATION_HOOK_BRAND);
14
+ var errorReporter;
15
+ function setGlobalHookErrorReporter(reporter) {
16
+ const previousReporter = errorReporter;
17
+ errorReporter = reporter;
18
+ return () => {
19
+ if (errorReporter === reporter) {
20
+ errorReporter = previousReporter;
21
+ }
22
+ };
23
+ }
24
+ function reportError(error) {
25
+ try {
26
+ errorReporter?.(error);
27
+ } catch {
18
28
  }
19
- getStore() {
20
- return void 0;
29
+ }
30
+ function setContextValue(context, key, value) {
31
+ try {
32
+ context[key] = value;
33
+ } catch (error) {
34
+ reportError(error);
21
35
  }
22
- };
23
- var DefaultChannel = class {
36
+ }
37
+ function wrapStoreRun(store, message, next, transform) {
38
+ return () => {
39
+ let context;
40
+ try {
41
+ context = transform ? transform(message) : message;
42
+ } catch (error) {
43
+ reportError(error);
44
+ return next();
45
+ }
46
+ let called = false;
47
+ let result;
48
+ let providerError;
49
+ let providerThrew = false;
50
+ const runNext = () => {
51
+ if (called) {
52
+ reportError(
53
+ new Error(
54
+ "Instrumentation store invoked its callback more than once"
55
+ )
56
+ );
57
+ if (providerThrew) {
58
+ throw providerError;
59
+ }
60
+ return result;
61
+ }
62
+ called = true;
63
+ try {
64
+ result = next();
65
+ return result;
66
+ } catch (error) {
67
+ providerThrew = true;
68
+ providerError = error;
69
+ throw error;
70
+ }
71
+ };
72
+ try {
73
+ store.run(context, runNext);
74
+ } catch (error) {
75
+ if (!providerThrew || error !== providerError) {
76
+ reportError(error);
77
+ }
78
+ }
79
+ if (!called) {
80
+ reportError(
81
+ new Error("Instrumentation store did not invoke its callback")
82
+ );
83
+ return runNext();
84
+ }
85
+ if (providerThrew) {
86
+ throw providerError;
87
+ }
88
+ return result;
89
+ };
90
+ }
91
+ var HookChannel = class {
24
92
  constructor(name) {
25
93
  this.name = name;
26
94
  }
27
95
  name;
28
- hasSubscribers = false;
29
- subscribe(_subscription) {
96
+ subscribers = [];
97
+ stores = /* @__PURE__ */ new Map();
98
+ get hasSubscribers() {
99
+ return this.subscribers.length > 0 || this.stores.size > 0;
30
100
  }
31
- unsubscribe(_subscription) {
32
- return false;
101
+ subscribe(subscription) {
102
+ if (typeof subscription !== "function") {
103
+ throw new TypeError("subscription must be a function");
104
+ }
105
+ this.subscribers = [...this.subscribers, subscription];
33
106
  }
34
- bindStore(_store, _transform) {
107
+ unsubscribe(subscription) {
108
+ const index = this.subscribers.indexOf(subscription);
109
+ if (index === -1) {
110
+ return false;
111
+ }
112
+ this.subscribers = [
113
+ ...this.subscribers.slice(0, index),
114
+ ...this.subscribers.slice(index + 1)
115
+ ];
116
+ return true;
35
117
  }
36
- unbindStore(_store) {
37
- return false;
118
+ bindStore(store, transform) {
119
+ if (!store || typeof store.run !== "function") {
120
+ throw new TypeError("store must have a run method");
121
+ }
122
+ this.stores.set(
123
+ store,
124
+ transform
125
+ );
38
126
  }
39
- publish(_message) {
127
+ unbindStore(store) {
128
+ return this.stores.delete(store);
40
129
  }
41
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
42
- runStores(_message, fn, thisArg, ...args) {
43
- return fn.apply(thisArg, args);
130
+ publish(message) {
131
+ const subscribers = this.subscribers;
132
+ for (const subscriber of subscribers) {
133
+ try {
134
+ subscriber(message, this.name);
135
+ } catch (error) {
136
+ reportError(error);
137
+ }
138
+ }
139
+ }
140
+ runStores(message, fn, thisArg, ...args) {
141
+ let run = () => {
142
+ this.publish(message);
143
+ return Reflect.apply(fn, thisArg, args);
144
+ };
145
+ for (const [store, transform] of this.stores.entries()) {
146
+ run = wrapStoreRun(store, message, run, transform);
147
+ }
148
+ return run();
44
149
  }
45
150
  };
46
- var DefaultTracingChannel = class {
151
+ var traceEvents = [
152
+ "start",
153
+ "end",
154
+ "asyncStart",
155
+ "asyncEnd",
156
+ "error"
157
+ ];
158
+ var TracingHook = class {
47
159
  start;
48
160
  end;
49
161
  asyncStart;
50
162
  asyncEnd;
51
163
  error;
52
164
  constructor(nameOrChannels) {
165
+ Object.defineProperty(this, hookBrand, {
166
+ configurable: false,
167
+ enumerable: false,
168
+ value: GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION,
169
+ writable: false
170
+ });
53
171
  if (typeof nameOrChannels === "string") {
54
- this.start = new DefaultChannel(`tracing:${nameOrChannels}:start`);
55
- this.end = new DefaultChannel(`tracing:${nameOrChannels}:end`);
56
- this.asyncStart = new DefaultChannel(
57
- `tracing:${nameOrChannels}:asyncStart`
58
- );
59
- this.asyncEnd = new DefaultChannel(`tracing:${nameOrChannels}:asyncEnd`);
60
- this.error = new DefaultChannel(`tracing:${nameOrChannels}:error`);
172
+ this.start = new HookChannel(`tracing:${nameOrChannels}:start`);
173
+ this.end = new HookChannel(`tracing:${nameOrChannels}:end`);
174
+ this.asyncStart = new HookChannel(`tracing:${nameOrChannels}:asyncStart`);
175
+ this.asyncEnd = new HookChannel(`tracing:${nameOrChannels}:asyncEnd`);
176
+ this.error = new HookChannel(`tracing:${nameOrChannels}:error`);
61
177
  return;
62
178
  }
63
- this.start = nameOrChannels.start ?? new DefaultChannel("tracing:start");
64
- this.end = nameOrChannels.end ?? new DefaultChannel("tracing:end");
65
- this.asyncStart = nameOrChannels.asyncStart ?? new DefaultChannel("tracing:asyncStart");
66
- this.asyncEnd = nameOrChannels.asyncEnd ?? new DefaultChannel("tracing:asyncEnd");
67
- this.error = nameOrChannels.error ?? new DefaultChannel("tracing:error");
179
+ this.start = nameOrChannels.start ?? new HookChannel("tracing:start");
180
+ this.end = nameOrChannels.end ?? new HookChannel("tracing:end");
181
+ this.asyncStart = nameOrChannels.asyncStart ?? new HookChannel("tracing:asyncStart");
182
+ this.asyncEnd = nameOrChannels.asyncEnd ?? new HookChannel("tracing:asyncEnd");
183
+ this.error = nameOrChannels.error ?? new HookChannel("tracing:error");
68
184
  }
69
185
  get hasSubscribers() {
70
186
  return this.start.hasSubscribers || this.end.hasSubscribers || this.asyncStart.hasSubscribers || this.asyncEnd.hasSubscribers || this.error.hasSubscribers;
71
187
  }
72
- subscribe(_handlers) {
188
+ subscribe(handlers) {
189
+ for (const eventName of traceEvents) {
190
+ const handler = handlers[eventName];
191
+ if (handler) {
192
+ this[eventName].subscribe(handler);
193
+ }
194
+ }
195
+ }
196
+ unsubscribe(handlers) {
197
+ let done = true;
198
+ for (const eventName of traceEvents) {
199
+ const handler = handlers[eventName];
200
+ if (handler && !this[eventName].unsubscribe(handler)) {
201
+ done = false;
202
+ }
203
+ }
204
+ return done;
73
205
  }
74
- unsubscribe(_handlers) {
206
+ traceSync(fn, message = {}, thisArg, ...args) {
207
+ if (!this.hasSubscribers) {
208
+ return Reflect.apply(fn, thisArg, args);
209
+ }
210
+ const context = message;
211
+ return this.start.runStores(message, () => {
212
+ try {
213
+ const result = Reflect.apply(fn, thisArg, args);
214
+ setContextValue(context, "result", result);
215
+ return result;
216
+ } catch (error) {
217
+ setContextValue(context, "error", error);
218
+ this.error.publish(message);
219
+ throw error;
220
+ } finally {
221
+ this.end.publish(message);
222
+ }
223
+ });
224
+ }
225
+ tracePromise(fn, message = {}, thisArg, ...args) {
226
+ if (!this.hasSubscribers) {
227
+ return Reflect.apply(fn, thisArg, args);
228
+ }
229
+ const context = message;
230
+ return this.start.runStores(message, () => {
231
+ let result;
232
+ try {
233
+ result = Reflect.apply(fn, thisArg, args);
234
+ } catch (error) {
235
+ setContextValue(context, "error", error);
236
+ this.error.publish(message);
237
+ this.end.publish(message);
238
+ throw error;
239
+ }
240
+ this.end.publish(message);
241
+ if (!result || typeof result !== "object" && typeof result !== "function") {
242
+ setContextValue(context, "result", result);
243
+ this.asyncStart.publish(message);
244
+ this.asyncEnd.publish(message);
245
+ return result;
246
+ }
247
+ let terminalPublished = false;
248
+ const finishUnobservedResult = (error) => {
249
+ reportError(error);
250
+ if (!terminalPublished) {
251
+ terminalPublished = true;
252
+ setContextValue(context, "result", result);
253
+ this.asyncStart.publish(message);
254
+ this.asyncEnd.publish(message);
255
+ }
256
+ return result;
257
+ };
258
+ let then;
259
+ try {
260
+ then = result.then;
261
+ } catch (error) {
262
+ return finishUnobservedResult(error);
263
+ }
264
+ if (typeof then !== "function") {
265
+ setContextValue(context, "result", result);
266
+ this.asyncStart.publish(message);
267
+ this.asyncEnd.publish(message);
268
+ return result;
269
+ }
270
+ const resolve = (resolved) => {
271
+ if (!terminalPublished) {
272
+ terminalPublished = true;
273
+ setContextValue(context, "result", resolved);
274
+ this.asyncStart.publish(message);
275
+ this.asyncEnd.publish(message);
276
+ }
277
+ return resolved;
278
+ };
279
+ let rejectionThrown = false;
280
+ let rejectionError;
281
+ const reject2 = (error) => {
282
+ if (!terminalPublished) {
283
+ terminalPublished = true;
284
+ setContextValue(context, "error", error);
285
+ this.error.publish(message);
286
+ this.asyncStart.publish(message);
287
+ this.asyncEnd.publish(message);
288
+ }
289
+ rejectionThrown = true;
290
+ rejectionError = error;
291
+ throw error;
292
+ };
293
+ let isPlainPromise;
294
+ try {
295
+ isPlainPromise = result instanceof Promise && result.constructor === Promise;
296
+ } catch (error) {
297
+ return finishUnobservedResult(error);
298
+ }
299
+ try {
300
+ if (isPlainPromise) {
301
+ return Reflect.apply(then, result, [resolve, reject2]);
302
+ }
303
+ Reflect.apply(then, result, [
304
+ resolve,
305
+ (error) => {
306
+ try {
307
+ reject2(error);
308
+ } catch {
309
+ }
310
+ }
311
+ ]);
312
+ } catch (error) {
313
+ if (rejectionThrown && error === rejectionError) {
314
+ return result;
315
+ }
316
+ return finishUnobservedResult(error);
317
+ }
318
+ return result;
319
+ });
320
+ }
321
+ traceCallback(fn, position = -1, message = {}, thisArg, ...args) {
322
+ if (!this.hasSubscribers) {
323
+ return Reflect.apply(fn, thisArg, args);
324
+ }
325
+ const context = message;
326
+ const callArgs = args.length > 0 ? args : context.arguments ?? args;
327
+ const callback = Array.prototype.at.call(callArgs, position);
328
+ if (typeof callback !== "function") {
329
+ return Reflect.apply(fn, thisArg, args);
330
+ }
331
+ const { asyncStart, asyncEnd, error: errorChannel } = this;
332
+ function wrappedCallback(error, result) {
333
+ if (error) {
334
+ setContextValue(context, "error", error);
335
+ errorChannel.publish(message);
336
+ } else {
337
+ setContextValue(context, "result", result);
338
+ }
339
+ return asyncStart.runStores(message, () => {
340
+ try {
341
+ return Reflect.apply(callback, this, arguments);
342
+ } finally {
343
+ asyncEnd.publish(message);
344
+ }
345
+ });
346
+ }
347
+ Array.prototype.splice.call(callArgs, position, 1, wrappedCallback);
348
+ return this.start.runStores(message, () => {
349
+ try {
350
+ return Reflect.apply(fn, thisArg, args);
351
+ } catch (error) {
352
+ setContextValue(context, "error", error);
353
+ this.error.publish(message);
354
+ throw error;
355
+ } finally {
356
+ this.end.publish(message);
357
+ }
358
+ });
359
+ }
360
+ };
361
+ var inertChannel = Object.freeze({
362
+ name: "braintrust:inert",
363
+ hasSubscribers: false,
364
+ subscribe() {
365
+ },
366
+ unsubscribe() {
75
367
  return false;
368
+ },
369
+ bindStore() {
370
+ },
371
+ unbindStore() {
372
+ return false;
373
+ },
374
+ publish() {
375
+ },
376
+ runStores(_message, fn, thisArg, ...args) {
377
+ return Reflect.apply(fn, thisArg, args);
76
378
  }
77
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
78
- traceSync(fn, _message, thisArg, ...args) {
79
- return fn.apply(thisArg, args);
379
+ });
380
+ var inertTracingHook = new TracingHook({
381
+ start: inertChannel,
382
+ end: inertChannel,
383
+ asyncStart: inertChannel,
384
+ asyncEnd: inertChannel,
385
+ error: inertChannel
386
+ });
387
+ function isHookChannel(value) {
388
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
389
+ return false;
80
390
  }
81
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
82
- tracePromise(fn, _message, thisArg, ...args) {
83
- return fn.apply(thisArg, args);
391
+ try {
392
+ const channel2 = value;
393
+ 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";
394
+ } catch {
395
+ return false;
84
396
  }
85
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
86
- traceCallback(fn, _position, _message, thisArg, ...args) {
87
- return fn.apply(thisArg, args);
397
+ }
398
+ function hasTracingHookShape(value) {
399
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
400
+ return false;
401
+ }
402
+ try {
403
+ const hook = value;
404
+ 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);
405
+ } catch {
406
+ return false;
407
+ }
408
+ }
409
+ function isCompatibleTracingHook(value) {
410
+ try {
411
+ return value[hookBrand] === GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION && hasTracingHookShape(value);
412
+ } catch {
413
+ return false;
414
+ }
415
+ }
416
+ function isCompatibleHookRegistry(value) {
417
+ try {
418
+ return value instanceof Map && value[registryBrand] === GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION;
419
+ } catch {
420
+ return false;
421
+ }
422
+ }
423
+ function getHookRegistry() {
424
+ let descriptor;
425
+ try {
426
+ descriptor = Object.getOwnPropertyDescriptor(
427
+ globalThis,
428
+ GLOBAL_INSTRUMENTATION_HOOKS_KEY
429
+ );
430
+ } catch (error) {
431
+ reportError(error);
432
+ return void 0;
433
+ }
434
+ if (descriptor && "value" in descriptor && isCompatibleHookRegistry(descriptor.value) && (descriptor.configurable || descriptor.enumerable === false)) {
435
+ if (descriptor.configurable || descriptor.writable) {
436
+ try {
437
+ Object.defineProperty(globalThis, GLOBAL_INSTRUMENTATION_HOOKS_KEY, {
438
+ configurable: false,
439
+ enumerable: false,
440
+ value: descriptor.value,
441
+ writable: false
442
+ });
443
+ } catch (error) {
444
+ reportError(error);
445
+ return void 0;
446
+ }
447
+ }
448
+ return descriptor.value;
449
+ }
450
+ if (descriptor && !descriptor.configurable) {
451
+ reportError(new Error("Incompatible global instrumentation hook registry"));
452
+ return void 0;
453
+ }
454
+ const registry2 = /* @__PURE__ */ new Map();
455
+ try {
456
+ Object.defineProperty(registry2, registryBrand, {
457
+ configurable: false,
458
+ enumerable: false,
459
+ value: GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION,
460
+ writable: false
461
+ });
462
+ } catch (error) {
463
+ reportError(error);
464
+ return void 0;
465
+ }
466
+ try {
467
+ Object.defineProperty(globalThis, GLOBAL_INSTRUMENTATION_HOOKS_KEY, {
468
+ configurable: false,
469
+ enumerable: false,
470
+ value: registry2,
471
+ writable: false
472
+ });
473
+ return registry2;
474
+ } catch (error) {
475
+ reportError(error);
476
+ return void 0;
477
+ }
478
+ }
479
+ function newGlobalTracingChannel(nameOrChannels) {
480
+ if (typeof nameOrChannels !== "string") {
481
+ return new TracingHook(nameOrChannels);
482
+ }
483
+ const registry2 = getHookRegistry();
484
+ if (!registry2) {
485
+ return inertTracingHook;
486
+ }
487
+ let existing;
488
+ try {
489
+ existing = Map.prototype.get.call(registry2, nameOrChannels);
490
+ } catch (error) {
491
+ reportError(error);
492
+ return inertTracingHook;
493
+ }
494
+ if (isCompatibleTracingHook(existing)) {
495
+ return existing;
496
+ }
497
+ if (existing !== void 0) {
498
+ reportError(
499
+ new Error(`Invalid global instrumentation hook: ${nameOrChannels}`)
500
+ );
501
+ try {
502
+ Map.prototype.delete.call(registry2, nameOrChannels);
503
+ } catch (error) {
504
+ reportError(error);
505
+ return inertTracingHook;
506
+ }
507
+ }
508
+ const hook = new TracingHook(nameOrChannels);
509
+ try {
510
+ Map.prototype.set.call(registry2, nameOrChannels, hook);
511
+ } catch (error) {
512
+ reportError(error);
513
+ return inertTracingHook;
514
+ }
515
+ return hook;
516
+ }
517
+
518
+ // src/isomorph.ts
519
+ var DefaultAsyncLocalStorage = class {
520
+ constructor() {
521
+ }
522
+ enterWith(_) {
523
+ }
524
+ run(_, callback) {
525
+ return callback();
526
+ }
527
+ getStore() {
528
+ return void 0;
88
529
  }
89
530
  };
90
531
  var iso = {
@@ -97,7 +538,7 @@ var iso = {
97
538
  getCallerLocation: () => void 0,
98
539
  newAsyncLocalStorage: () => new DefaultAsyncLocalStorage(),
99
540
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
100
- newTracingChannel: (nameOrChannels) => new DefaultTracingChannel(nameOrChannels),
541
+ newTracingChannel: (nameOrChannels) => newGlobalTracingChannel(nameOrChannels),
101
542
  processOn: (_0, _1) => {
102
543
  },
103
544
  basename: (filepath) => filepath.split(/[\\/]/).pop() || filepath,
@@ -217,6 +658,9 @@ var debugLogger = {
217
658
  return createDebugLogger(state);
218
659
  }
219
660
  };
661
+ setGlobalHookErrorReporter((error) => {
662
+ debugLogger.error("Global instrumentation hook error:", error);
663
+ });
220
664
 
221
665
  // src/queue.ts
222
666
  var DEFAULT_QUEUE_SIZE = 15e3;
@@ -2001,7 +2445,8 @@ var ApiKey = z6.object({
2001
2445
  user_email: z6.union([z6.string(), z6.null()]).optional(),
2002
2446
  user_given_name: z6.union([z6.string(), z6.null()]).optional(),
2003
2447
  user_family_name: z6.union([z6.string(), z6.null()]).optional(),
2004
- org_id: z6.union([z6.string(), z6.null()]).optional()
2448
+ org_id: z6.union([z6.string(), z6.null()]).optional(),
2449
+ expires_at: z6.union([z6.string(), z6.null()]).optional()
2005
2450
  });
2006
2451
  var TriggeredFunctionState = z6.object({
2007
2452
  triggered_xact_id: z6.string(),
@@ -2121,6 +2566,7 @@ var TopicMapData = z6.object({
2121
2566
  topic_names: z6.record(z6.string()).optional(),
2122
2567
  generation_settings: TopicMapGenerationSettings.optional(),
2123
2568
  disable_reconciliation: z6.boolean().optional(),
2569
+ reconcile_mode: z6.enum(["evolve", "names_only"]).optional(),
2124
2570
  distance_threshold: z6.number().optional(),
2125
2571
  btql_filter: z6.string().optional(),
2126
2572
  automation_btql_filter: z6.string().optional()
@@ -2701,7 +3147,12 @@ var ModelParams = z6.union([
2701
3147
  }).partial().passthrough()
2702
3148
  ]);
2703
3149
  var PromptOptionsNullish = z6.union([
2704
- z6.object({ model: z6.string(), params: ModelParams, position: z6.string() }).partial(),
3150
+ z6.object({
3151
+ model: z6.string(),
3152
+ params: ModelParams,
3153
+ position: z6.string(),
3154
+ endpoint_name: z6.union([z6.string(), z6.null()])
3155
+ }).partial(),
2705
3156
  z6.null()
2706
3157
  ]);
2707
3158
  var PromptParserNullish = z6.union([
@@ -2715,11 +3166,25 @@ var PromptParserNullish = z6.union([
2715
3166
  }),
2716
3167
  z6.null()
2717
3168
  ]);
3169
+ var PreprocessorSavedFunctionId = z6.union([
3170
+ z6.object({
3171
+ type: z6.literal("function"),
3172
+ id: z6.string(),
3173
+ version: z6.string().optional()
3174
+ }),
3175
+ z6.object({
3176
+ type: z6.literal("global"),
3177
+ name: z6.string(),
3178
+ function_type: z6.literal("preprocessor").optional().default("preprocessor")
3179
+ }),
3180
+ z6.null()
3181
+ ]);
2718
3182
  var PromptDataNullish = z6.union([
2719
3183
  z6.object({
2720
3184
  prompt: PromptBlockDataNullish,
2721
3185
  options: PromptOptionsNullish,
2722
3186
  parser: PromptParserNullish,
3187
+ preprocessor: PreprocessorSavedFunctionId,
2723
3188
  tool_functions: z6.union([z6.array(SavedFunctionId), z6.null()]),
2724
3189
  template_format: z6.union([
2725
3190
  z6.enum(["mustache", "nunjucks", "none"]),
@@ -2921,6 +3386,7 @@ var PromptData = z6.object({
2921
3386
  prompt: PromptBlockDataNullish,
2922
3387
  options: PromptOptionsNullish,
2923
3388
  parser: PromptParserNullish,
3389
+ preprocessor: PreprocessorSavedFunctionId,
2924
3390
  tool_functions: z6.union([z6.array(SavedFunctionId), z6.null()]),
2925
3391
  template_format: z6.union([
2926
3392
  z6.enum(["mustache", "nunjucks", "none"]),
@@ -3083,7 +3549,8 @@ var InvokeFunction = FunctionId.and(
3083
3549
  mode: StreamingMode,
3084
3550
  strict: z6.union([z6.boolean(), z6.null()]),
3085
3551
  mcp_auth: z6.record(z6.object({ oauth_token: z6.string() }).partial()),
3086
- overrides: z6.union([z6.object({}).partial().passthrough(), z6.null()])
3552
+ overrides: z6.union([z6.object({}).partial().passthrough(), z6.null()]),
3553
+ endpoint_name: z6.union([z6.string(), z6.null()])
3087
3554
  }).partial()
3088
3555
  );
3089
3556
  var MCPServer = z6.object({
@@ -3147,6 +3614,24 @@ var Organization = z6.object({
3147
3614
  created: z6.union([z6.string(), z6.null()]).optional(),
3148
3615
  image_rendering_mode: ImageRenderingMode.optional()
3149
3616
  });
3617
+ var RetentionObjectType = z6.enum([
3618
+ "project_logs",
3619
+ "experiment",
3620
+ "dataset"
3621
+ ]);
3622
+ var OrgAutomation = z6.object({
3623
+ id: z6.string().uuid(),
3624
+ org_id: z6.string().uuid(),
3625
+ user_id: z6.union([z6.string(), z6.null()]).optional(),
3626
+ created: z6.union([z6.string(), z6.null()]).optional(),
3627
+ name: z6.string(),
3628
+ description: z6.union([z6.string(), z6.null()]).optional(),
3629
+ config: z6.object({
3630
+ event_type: z6.literal("retention"),
3631
+ object_type: RetentionObjectType,
3632
+ retention_days: z6.number().int().gte(0)
3633
+ })
3634
+ });
3150
3635
  var ProjectSettings = z6.union([
3151
3636
  z6.object({
3152
3637
  comparison_key: z6.union([z6.string(), z6.null()]),
@@ -3173,6 +3658,7 @@ var ProjectSettings = z6.union([
3173
3658
  z6.null()
3174
3659
  ]),
3175
3660
  disable_realtime_queries: z6.union([z6.boolean(), z6.null()]),
3661
+ monitor_charts_use_metrics_start: z6.union([z6.boolean(), z6.null()]),
3176
3662
  default_preprocessor: NullableSavedFunctionId
3177
3663
  }).partial(),
3178
3664
  z6.null()
@@ -3187,11 +3673,6 @@ var Project = z6.object({
3187
3673
  user_id: z6.union([z6.string(), z6.null()]).optional(),
3188
3674
  settings: ProjectSettings.optional()
3189
3675
  });
3190
- var RetentionObjectType = z6.enum([
3191
- "project_logs",
3192
- "experiment",
3193
- "dataset"
3194
- ]);
3195
3676
  var TopicAutomationFacetModel = z6.union([
3196
3677
  z6.enum(["brain-facet-latest", "brain-facet-1", "brain-facet-2"]),
3197
3678
  z6.null()
@@ -3302,7 +3783,7 @@ var ProjectAutomation = z6.object({
3302
3783
  z6.object({
3303
3784
  event_type: z6.literal("retention"),
3304
3785
  object_type: RetentionObjectType,
3305
- retention_days: z6.number().gte(0)
3786
+ retention_days: z6.number().int().gte(0)
3306
3787
  }),
3307
3788
  z6.object({
3308
3789
  event_type: z6.literal("environment_update"),
@@ -3474,7 +3955,12 @@ var Prompt = z6.object({
3474
3955
  metadata: z6.union([z6.object({}).partial().passthrough(), z6.null()]).optional(),
3475
3956
  function_type: FunctionTypeEnumNullish.optional()
3476
3957
  });
3477
- var PromptOptions = z6.object({ model: z6.string(), params: ModelParams, position: z6.string() }).partial();
3958
+ var PromptOptions = z6.object({
3959
+ model: z6.string(),
3960
+ params: ModelParams,
3961
+ position: z6.string(),
3962
+ endpoint_name: z6.union([z6.string(), z6.null()])
3963
+ }).partial();
3478
3964
  var PromptSessionEvent = z6.object({
3479
3965
  id: z6.string(),
3480
3966
  _xact_id: z6.string(),
@@ -3557,7 +4043,8 @@ var RunEval = z6.object({
3557
4043
  stop_token: z6.union([z6.string(), z6.null()]).optional(),
3558
4044
  extra_messages: z6.string().optional(),
3559
4045
  tags: z6.array(z6.string()).optional(),
3560
- mcp_auth: z6.record(z6.object({ oauth_token: z6.string() }).partial()).optional()
4046
+ mcp_auth: z6.record(z6.object({ oauth_token: z6.string() }).partial()).optional(),
4047
+ endpoint_name: z6.union([z6.string(), z6.null()]).optional()
3561
4048
  });
3562
4049
  var ServiceToken = z6.object({
3563
4050
  id: z6.string().uuid(),
@@ -3567,7 +4054,8 @@ var ServiceToken = z6.object({
3567
4054
  service_account_id: z6.union([z6.string(), z6.null()]).optional(),
3568
4055
  service_account_email: z6.union([z6.string(), z6.null()]).optional(),
3569
4056
  service_account_name: z6.union([z6.string(), z6.null()]).optional(),
3570
- org_id: z6.union([z6.string(), z6.null()]).optional()
4057
+ org_id: z6.union([z6.string(), z6.null()]).optional(),
4058
+ expires_at: z6.union([z6.string(), z6.null()]).optional()
3571
4059
  });
3572
4060
  var SpanIFrame = z6.object({
3573
4061
  id: z6.string().uuid(),
@@ -3689,6 +4177,13 @@ var ViewOptions = z6.union([
3689
4177
  }),
3690
4178
  z6.null()
3691
4179
  ]),
4180
+ pointSizeMetric: z6.union([
4181
+ z6.object({
4182
+ type: z6.enum(["none", "score", "metric", "metadata"]),
4183
+ value: z6.string()
4184
+ }),
4185
+ z6.null()
4186
+ ]),
3692
4187
  xAxisAggregation: z6.union([z6.string(), z6.null()]),
3693
4188
  chartAnnotations: z6.union([
3694
4189
  z6.array(z6.object({ id: z6.string(), text: z6.string() })),
@@ -4832,6 +5327,8 @@ var INSTRUMENTATION_NAMES = {
4832
5327
  BEDROCK_RUNTIME: "bedrock-runtime",
4833
5328
  BRAINTRUST_JS_LOGGER: "braintrust-js-logger",
4834
5329
  CLAUDE_AGENT_SDK: "claude-agent-sdk",
5330
+ CLOUDFLARE_AI_CHAT: "cloudflare-ai-chat",
5331
+ CLOUDFLARE_AGENTS: "cloudflare-agents",
4835
5332
  COHERE: "cohere",
4836
5333
  CURSOR_SDK: "cursor-sdk",
4837
5334
  EVE: "eve",
@@ -4857,7 +5354,7 @@ var INSTRUMENTATION_NAMES = {
4857
5354
  var INTERNAL_SPAN_INSTRUMENTATION_NAME = /* @__PURE__ */ Symbol.for(
4858
5355
  "braintrust.spanInstrumentationName"
4859
5356
  );
4860
- var SDK_VERSION = true ? "3.25.0" : "0.0.0";
5357
+ var SDK_VERSION = true ? "3.26.0" : "0.0.0";
4861
5358
  function withSpanInstrumentationName(args, instrumentationName) {
4862
5359
  return {
4863
5360
  ...args,
@@ -5052,12 +5549,13 @@ function applyMaskingToField(maskingFunction, data, fieldName) {
5052
5549
  var INITIAL_SPAN_WRITE_AS_MERGE = /* @__PURE__ */ Symbol(
5053
5550
  "braintrust.initial-span-write-as-merge"
5054
5551
  );
5552
+ var INTERNAL_SPAN_CONTEXT = /* @__PURE__ */ Symbol("braintrust.internal-span-context");
5055
5553
  var BRAINTRUST_CURRENT_SPAN_STORE = /* @__PURE__ */ Symbol.for(
5056
5554
  "braintrust.currentSpanStore"
5057
5555
  );
5058
5556
  var ContextManager = class {
5059
5557
  /**
5060
- * Returns the value to store in the ALS bound to a TracingChannel's start event.
5558
+ * Returns the value to store in the ALS bound to a global hook's start event.
5061
5559
  * In default mode this is the Span itself; in OTEL mode it is the OTEL Context
5062
5560
  * containing the span so that OTEL's own ALS stores a proper Context object.
5063
5561
  */
@@ -8790,6 +9288,12 @@ function _internalStartSpanWithInitialMerge(args) {
8790
9288
  [INITIAL_SPAN_WRITE_AS_MERGE]: true
8791
9289
  }).span;
8792
9290
  }
9291
+ function _internalStartSpanWithContext(args, context) {
9292
+ return startSpanAndIsLogger({
9293
+ ...args,
9294
+ [INTERNAL_SPAN_CONTEXT]: context
9295
+ }).span;
9296
+ }
8793
9297
  async function flush(options) {
8794
9298
  const state = options?.state ?? _globalState;
8795
9299
  return await state.bgLogger().flush();
@@ -9691,7 +10195,7 @@ var SpanImpl = class _SpanImpl {
9691
10195
  start: args.startTime ?? getCurrentUnixTimestamp()
9692
10196
  },
9693
10197
  context: mergeSpanOriginContext(
9694
- { ...callerLocation },
10198
+ { ...callerLocation, ...args[INTERNAL_SPAN_CONTEXT] },
9695
10199
  instrumentationName,
9696
10200
  this._state.spanOriginEnvironment
9697
10201
  ),
@@ -11631,8 +12135,8 @@ function runWithAutoInstrumentationSuppressed(callback) {
11631
12135
  callback
11632
12136
  );
11633
12137
  }
11634
- function bindAutoInstrumentationSuppressionToStart(tracingChannel2) {
11635
- const startChannel = tracingChannel2.start;
12138
+ function bindAutoInstrumentationSuppressionToStart(tracingChannel) {
12139
+ const startChannel = tracingChannel.start;
11636
12140
  if (!startChannel) {
11637
12141
  return void 0;
11638
12142
  }
@@ -11743,9 +12247,9 @@ function ensureSpanStateForEvent(states, config, event, channelName, instrumenta
11743
12247
  states.set(key, created);
11744
12248
  return created;
11745
12249
  }
11746
- function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelName, instrumentationName) {
12250
+ function bindCurrentSpanStoreToStart(tracingChannel, states, config, channelName, instrumentationName) {
11747
12251
  const state = _internalGetGlobalState();
11748
- const startChannel = tracingChannel2.start;
12252
+ const startChannel = tracingChannel.start;
11749
12253
  const contextManager = state?.contextManager;
11750
12254
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
11751
12255
  if (!currentSpanStore || !startChannel) {
@@ -11828,11 +12332,11 @@ function runStreamingErrorHook(args) {
11828
12332
  }
11829
12333
  }
11830
12334
  function traceAsyncChannel(channel2, config) {
11831
- const tracingChannel2 = channel2.tracingChannel();
12335
+ const tracingChannel = channel2.tracingChannel();
11832
12336
  const states = /* @__PURE__ */ new WeakMap();
11833
12337
  const channelName = channel2.channelName;
11834
12338
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart(
11835
- tracingChannel2,
12339
+ tracingChannel,
11836
12340
  states,
11837
12341
  config,
11838
12342
  channelName,
@@ -11888,18 +12392,18 @@ function traceAsyncChannel(channel2, config) {
11888
12392
  logErrorAndEnd(states, event, channelName);
11889
12393
  }
11890
12394
  };
11891
- tracingChannel2.subscribe(handlers);
12395
+ tracingChannel.subscribe(handlers);
11892
12396
  return () => {
11893
12397
  unbindCurrentSpanStore?.();
11894
- tracingChannel2.unsubscribe(handlers);
12398
+ tracingChannel.unsubscribe(handlers);
11895
12399
  };
11896
12400
  }
11897
12401
  function traceStreamingChannel(channel2, config) {
11898
- const tracingChannel2 = channel2.tracingChannel();
12402
+ const tracingChannel = channel2.tracingChannel();
11899
12403
  const states = /* @__PURE__ */ new WeakMap();
11900
12404
  const channelName = channel2.channelName;
11901
12405
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart(
11902
- tracingChannel2,
12406
+ tracingChannel,
11903
12407
  states,
11904
12408
  config,
11905
12409
  channelName,
@@ -12110,18 +12614,18 @@ function traceStreamingChannel(channel2, config) {
12110
12614
  }
12111
12615
  }
12112
12616
  };
12113
- tracingChannel2.subscribe(handlers);
12617
+ tracingChannel.subscribe(handlers);
12114
12618
  return () => {
12115
12619
  unbindCurrentSpanStore?.();
12116
- tracingChannel2.unsubscribe(handlers);
12620
+ tracingChannel.unsubscribe(handlers);
12117
12621
  };
12118
12622
  }
12119
12623
  function traceSyncStreamChannel(channel2, config) {
12120
- const tracingChannel2 = channel2.tracingChannel();
12624
+ const tracingChannel = channel2.tracingChannel();
12121
12625
  const states = /* @__PURE__ */ new WeakMap();
12122
12626
  const channelName = channel2.channelName;
12123
12627
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart(
12124
- tracingChannel2,
12628
+ tracingChannel,
12125
12629
  states,
12126
12630
  config,
12127
12631
  channelName,
@@ -12234,10 +12738,10 @@ function traceSyncStreamChannel(channel2, config) {
12234
12738
  logErrorAndEnd(states, event, channelName);
12235
12739
  }
12236
12740
  };
12237
- tracingChannel2.subscribe(handlers);
12741
+ tracingChannel.subscribe(handlers);
12238
12742
  return () => {
12239
12743
  unbindCurrentSpanStore?.();
12240
- tracingChannel2.unsubscribe(handlers);
12744
+ tracingChannel.unsubscribe(handlers);
12241
12745
  };
12242
12746
  }
12243
12747
  function unsubscribeAll(unsubscribers) {
@@ -12417,7 +12921,7 @@ function defineChannels(pkg, channels, options) {
12417
12921
  const fullChannelName = `orchestrion:${pkg}:${spec.channelName}`;
12418
12922
  if (spec.kind === "async") {
12419
12923
  const asyncSpec = spec;
12420
- const tracingChannel3 = () => isomorph_default.newTracingChannel(
12924
+ const tracingChannel2 = () => isomorph_default.newTracingChannel(
12421
12925
  fullChannelName
12422
12926
  );
12423
12927
  return [
@@ -12425,8 +12929,8 @@ function defineChannels(pkg, channels, options) {
12425
12929
  {
12426
12930
  ...asyncSpec,
12427
12931
  instrumentationName,
12428
- tracingChannel: tracingChannel3,
12429
- tracePromise: (fn, context) => tracingChannel3().tracePromise(
12932
+ tracingChannel: tracingChannel2,
12933
+ tracePromise: (fn, context) => tracingChannel2().tracePromise(
12430
12934
  fn,
12431
12935
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
12432
12936
  context
@@ -12435,7 +12939,7 @@ function defineChannels(pkg, channels, options) {
12435
12939
  ];
12436
12940
  }
12437
12941
  const syncSpec = spec;
12438
- const tracingChannel2 = () => isomorph_default.newTracingChannel(
12942
+ const tracingChannel = () => isomorph_default.newTracingChannel(
12439
12943
  fullChannelName
12440
12944
  );
12441
12945
  return [
@@ -12443,8 +12947,8 @@ function defineChannels(pkg, channels, options) {
12443
12947
  {
12444
12948
  ...syncSpec,
12445
12949
  instrumentationName,
12446
- tracingChannel: tracingChannel2,
12447
- traceSync: (fn, context) => tracingChannel2().traceSync(
12950
+ tracingChannel,
12951
+ traceSync: (fn, context) => tracingChannel().traceSync(
12448
12952
  fn,
12449
12953
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
12450
12954
  context
@@ -13776,7 +14280,7 @@ var AnthropicPlugin = class extends BasePlugin {
13776
14280
  );
13777
14281
  }
13778
14282
  subscribeToAnthropicToolRunner() {
13779
- const tracingChannel2 = anthropicChannels.betaMessagesToolRunner.tracingChannel();
14283
+ const tracingChannel = anthropicChannels.betaMessagesToolRunner.tracingChannel();
13780
14284
  const states = /* @__PURE__ */ new WeakMap();
13781
14285
  const handlers = {
13782
14286
  start: (event) => {
@@ -13833,9 +14337,9 @@ var AnthropicPlugin = class extends BasePlugin {
13833
14337
  states.delete(event);
13834
14338
  }
13835
14339
  };
13836
- tracingChannel2.subscribe(handlers);
14340
+ tracingChannel.subscribe(handlers);
13837
14341
  this.unsubscribers.push(() => {
13838
- tracingChannel2.unsubscribe(handlers);
14342
+ tracingChannel.unsubscribe(handlers);
13839
14343
  });
13840
14344
  }
13841
14345
  };
@@ -14747,8 +15251,8 @@ function registerHarnessSessionParent(session, parent) {
14747
15251
  function currentHarnessTurnParent() {
14748
15252
  return harnessTurnParentStore?.getStore() ?? wrapperTurnParents.get(currentSpan());
14749
15253
  }
14750
- function bindHarnessTurnParentToStart(tracingChannel2, parentFromEvent) {
14751
- const startChannel = tracingChannel2.start;
15254
+ function bindHarnessTurnParentToStart(tracingChannel, parentFromEvent) {
15255
+ const startChannel = tracingChannel.start;
14752
15256
  if (!startChannel) {
14753
15257
  return () => {
14754
15258
  };
@@ -20214,7 +20718,7 @@ var CursorSDKPlugin = class extends BasePlugin {
20214
20718
  this.subscribeToAgentFactory(cursorSDKChannels.resume);
20215
20719
  }
20216
20720
  subscribeToAgentFactory(channel2) {
20217
- const tracingChannel2 = channel2.tracingChannel();
20721
+ const tracingChannel = channel2.tracingChannel();
20218
20722
  const handlers = {
20219
20723
  asyncEnd: (event) => {
20220
20724
  patchCursorAgentInPlace(event.result);
@@ -20222,9 +20726,9 @@ var CursorSDKPlugin = class extends BasePlugin {
20222
20726
  error: () => {
20223
20727
  }
20224
20728
  };
20225
- tracingChannel2.subscribe(handlers);
20729
+ tracingChannel.subscribe(handlers);
20226
20730
  this.unsubscribers.push(() => {
20227
- tracingChannel2.unsubscribe(handlers);
20731
+ tracingChannel.unsubscribe(handlers);
20228
20732
  });
20229
20733
  }
20230
20734
  subscribeToPrompt() {
@@ -21580,10 +22084,10 @@ var GoogleGenAIPlugin = class extends BasePlugin {
21580
22084
  this.subscribeToInteractionsCreateChannel();
21581
22085
  }
21582
22086
  subscribeToGenerateContentChannel() {
21583
- const tracingChannel2 = googleGenAIChannels.generateContent.tracingChannel();
22087
+ const tracingChannel = googleGenAIChannels.generateContent.tracingChannel();
21584
22088
  const states = /* @__PURE__ */ new WeakMap();
21585
22089
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart2(
21586
- tracingChannel2,
22090
+ tracingChannel,
21587
22091
  states,
21588
22092
  (event) => {
21589
22093
  const params = event.arguments[0];
@@ -21657,14 +22161,14 @@ var GoogleGenAIPlugin = class extends BasePlugin {
21657
22161
  logErrorAndEndSpan(states, event);
21658
22162
  }
21659
22163
  };
21660
- tracingChannel2.subscribe(handlers);
22164
+ tracingChannel.subscribe(handlers);
21661
22165
  this.unsubscribers.push(() => {
21662
22166
  unbindCurrentSpanStore?.();
21663
- tracingChannel2.unsubscribe(handlers);
22167
+ tracingChannel.unsubscribe(handlers);
21664
22168
  });
21665
22169
  }
21666
22170
  subscribeToGenerateContentStreamChannel() {
21667
- const tracingChannel2 = googleGenAIChannels.generateContentStream.tracingChannel();
22171
+ const tracingChannel = googleGenAIChannels.generateContentStream.tracingChannel();
21668
22172
  const handlers = {
21669
22173
  start: (event) => {
21670
22174
  const streamEvent = event;
@@ -21685,16 +22189,16 @@ var GoogleGenAIPlugin = class extends BasePlugin {
21685
22189
  error: () => {
21686
22190
  }
21687
22191
  };
21688
- tracingChannel2.subscribe(handlers);
22192
+ tracingChannel.subscribe(handlers);
21689
22193
  this.unsubscribers.push(() => {
21690
- tracingChannel2.unsubscribe(handlers);
22194
+ tracingChannel.unsubscribe(handlers);
21691
22195
  });
21692
22196
  }
21693
22197
  subscribeToEmbedContentChannel() {
21694
- const tracingChannel2 = googleGenAIChannels.embedContent.tracingChannel();
22198
+ const tracingChannel = googleGenAIChannels.embedContent.tracingChannel();
21695
22199
  const states = /* @__PURE__ */ new WeakMap();
21696
22200
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart2(
21697
- tracingChannel2,
22201
+ tracingChannel,
21698
22202
  states,
21699
22203
  (event) => {
21700
22204
  const params = event.arguments[0];
@@ -21764,10 +22268,10 @@ var GoogleGenAIPlugin = class extends BasePlugin {
21764
22268
  logErrorAndEndSpan(states, event);
21765
22269
  }
21766
22270
  };
21767
- tracingChannel2.subscribe(handlers);
22271
+ tracingChannel.subscribe(handlers);
21768
22272
  this.unsubscribers.push(() => {
21769
22273
  unbindCurrentSpanStore?.();
21770
- tracingChannel2.unsubscribe(handlers);
22274
+ tracingChannel.unsubscribe(handlers);
21771
22275
  });
21772
22276
  }
21773
22277
  subscribeToInteractionsCreateChannel() {
@@ -21803,10 +22307,10 @@ function ensureSpanState(states, event, create) {
21803
22307
  states.set(event, created);
21804
22308
  return created;
21805
22309
  }
21806
- function bindCurrentSpanStoreToStart2(tracingChannel2, states, create) {
22310
+ function bindCurrentSpanStoreToStart2(tracingChannel, states, create) {
21807
22311
  const state = _internalGetGlobalState();
21808
22312
  const contextManager = state?.contextManager;
21809
- const startChannel = tracingChannel2.start;
22313
+ const startChannel = tracingChannel.start;
21810
22314
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
21811
22315
  if (!startChannel?.bindStore || !currentSpanStore) {
21812
22316
  return void 0;
@@ -22309,11 +22813,11 @@ function summarizeEmbedContentOutput(response) {
22309
22813
  };
22310
22814
  }
22311
22815
  function populateUsageMetrics(metrics, usage) {
22312
- if (usage.promptTokenCount !== void 0) {
22313
- metrics.prompt_tokens = usage.promptTokenCount;
22816
+ if (usage.promptTokenCount !== void 0 || usage.toolUsePromptTokenCount !== void 0) {
22817
+ metrics.prompt_tokens = (usage.promptTokenCount ?? 0) + (usage.toolUsePromptTokenCount ?? 0);
22314
22818
  }
22315
- if (usage.candidatesTokenCount !== void 0) {
22316
- metrics.completion_tokens = usage.candidatesTokenCount;
22819
+ if (usage.candidatesTokenCount !== void 0 || usage.thoughtsTokenCount !== void 0) {
22820
+ metrics.completion_tokens = (usage.candidatesTokenCount ?? 0) + (usage.thoughtsTokenCount ?? 0);
22317
22821
  }
22318
22822
  if (usage.totalTokenCount !== void 0) {
22319
22823
  metrics.tokens = usage.totalTokenCount;
@@ -22324,13 +22828,26 @@ function populateUsageMetrics(metrics, usage) {
22324
22828
  if (usage.thoughtsTokenCount !== void 0) {
22325
22829
  metrics.completion_reasoning_tokens = usage.thoughtsTokenCount;
22326
22830
  }
22831
+ for (const detail of usage.promptTokensDetails ?? []) {
22832
+ if (detail.modality === "AUDIO" && detail.tokenCount !== void 0) {
22833
+ metrics.prompt_audio_tokens = (metrics.prompt_audio_tokens ?? 0) + detail.tokenCount;
22834
+ }
22835
+ }
22836
+ for (const detail of usage.candidatesTokensDetails ?? []) {
22837
+ if (detail.modality === "AUDIO" && detail.tokenCount !== void 0) {
22838
+ metrics.completion_audio_tokens = (metrics.completion_audio_tokens ?? 0) + detail.tokenCount;
22839
+ }
22840
+ if (detail.modality === "IMAGE" && detail.tokenCount !== void 0) {
22841
+ metrics.completion_image_tokens = (metrics.completion_image_tokens ?? 0) + detail.tokenCount;
22842
+ }
22843
+ }
22327
22844
  }
22328
22845
  function populateInteractionUsageMetrics(metrics, usage) {
22329
22846
  if (typeof usage.total_input_tokens === "number") {
22330
22847
  metrics.prompt_tokens = usage.total_input_tokens;
22331
22848
  }
22332
22849
  if (typeof usage.total_output_tokens === "number") {
22333
- metrics.completion_tokens = usage.total_output_tokens;
22850
+ metrics.completion_tokens = usage.total_output_tokens + (typeof usage.total_thought_tokens === "number" ? usage.total_thought_tokens : 0);
22334
22851
  }
22335
22852
  if (typeof usage.total_tokens === "number") {
22336
22853
  metrics.tokens = usage.total_tokens;
@@ -22341,6 +22858,24 @@ function populateInteractionUsageMetrics(metrics, usage) {
22341
22858
  if (typeof usage.total_thought_tokens === "number") {
22342
22859
  metrics.completion_reasoning_tokens = usage.total_thought_tokens;
22343
22860
  }
22861
+ for (const detail of Array.isArray(usage.input_tokens_by_modality) ? usage.input_tokens_by_modality : []) {
22862
+ if (typeof detail?.modality === "string" && detail.modality.toLowerCase() === "audio" && typeof detail.tokens === "number") {
22863
+ metrics.prompt_audio_tokens = (metrics.prompt_audio_tokens ?? 0) + detail.tokens;
22864
+ }
22865
+ }
22866
+ for (const detail of Array.isArray(usage.output_tokens_by_modality) ? usage.output_tokens_by_modality : []) {
22867
+ if (typeof detail?.modality !== "string" || typeof detail.tokens !== "number") {
22868
+ continue;
22869
+ }
22870
+ switch (detail.modality.toLowerCase()) {
22871
+ case "audio":
22872
+ metrics.completion_audio_tokens = (metrics.completion_audio_tokens ?? 0) + detail.tokens;
22873
+ break;
22874
+ case "image":
22875
+ metrics.completion_image_tokens = (metrics.completion_image_tokens ?? 0) + detail.tokens;
22876
+ break;
22877
+ }
22878
+ }
22344
22879
  }
22345
22880
  function aggregateGenerateContentChunks(chunks, startTime, firstTokenTime) {
22346
22881
  const end = getCurrentUnixTimestamp();
@@ -23079,6 +23614,299 @@ function extractTextGenerationStreamMetadata(chunks) {
23079
23614
  return void 0;
23080
23615
  }
23081
23616
 
23617
+ // src/instrumentation/plugins/huggingface-transformers-channels.ts
23618
+ var SUPPORTED_TASKS = /* @__PURE__ */ new Set([
23619
+ "text-generation",
23620
+ "text2text-generation",
23621
+ "summarization",
23622
+ "feature-extraction",
23623
+ "question-answering"
23624
+ ]);
23625
+ var pipelineInfo = /* @__PURE__ */ new WeakMap();
23626
+ function isSupportedHuggingFaceTransformersTask(task) {
23627
+ return typeof task === "string" && SUPPORTED_TASKS.has(task);
23628
+ }
23629
+ function registerHuggingFaceTransformersPipeline(pipeline, task, model) {
23630
+ if (typeof task !== "string") {
23631
+ return;
23632
+ }
23633
+ const info = { task };
23634
+ if (typeof model === "string") {
23635
+ info.model = model;
23636
+ }
23637
+ pipelineInfo.set(pipeline, info);
23638
+ }
23639
+ function getHuggingFaceTransformersPipelineInfo(pipeline) {
23640
+ return pipeline ? pipelineInfo.get(pipeline) : void 0;
23641
+ }
23642
+ var huggingFaceTransformersChannels = defineChannels(
23643
+ "@huggingface/transformers",
23644
+ {
23645
+ pipeline: channel({
23646
+ channelName: "pipeline",
23647
+ kind: "async"
23648
+ }),
23649
+ pipelineCall: channel({
23650
+ channelName: "pipeline.call",
23651
+ kind: "async"
23652
+ })
23653
+ },
23654
+ { instrumentationName: INSTRUMENTATION_NAMES.HUGGINGFACE }
23655
+ );
23656
+
23657
+ // src/instrumentation/plugins/huggingface-transformers-plugin.ts
23658
+ var REQUEST_METADATA_KEYS = [
23659
+ "temperature",
23660
+ "top_p",
23661
+ "max_tokens",
23662
+ "stop"
23663
+ ];
23664
+ var HuggingFaceTransformersPlugin = class extends BasePlugin {
23665
+ onEnable() {
23666
+ this.subscribeToPipelineFactory();
23667
+ this.unsubscribers.push(
23668
+ traceAsyncChannel(huggingFaceTransformersChannels.pipelineCall, {
23669
+ name: (_args, event) => {
23670
+ const task = getTask(event);
23671
+ const operation = task?.replaceAll("-", "_") ?? "unknown";
23672
+ return `huggingface.transformers.${operation}`;
23673
+ },
23674
+ type: "llm" /* LLM */,
23675
+ shouldTrace: (_args, event) => isSupportedHuggingFaceTransformersTask(
23676
+ getTask(event)
23677
+ ),
23678
+ extractInput: (args, event) => ({
23679
+ input: extractInput(
23680
+ getTask(event),
23681
+ args
23682
+ ),
23683
+ metadata: extractMetadata(
23684
+ event,
23685
+ args
23686
+ )
23687
+ }),
23688
+ extractOutput: (result, event) => extractOutput(
23689
+ getTask(event),
23690
+ result
23691
+ ),
23692
+ extractMetrics: () => ({})
23693
+ })
23694
+ );
23695
+ }
23696
+ onDisable() {
23697
+ this.unsubscribers = unsubscribeAll(this.unsubscribers);
23698
+ }
23699
+ subscribeToPipelineFactory() {
23700
+ const channel2 = huggingFaceTransformersChannels.pipeline.tracingChannel();
23701
+ const handlers = {
23702
+ asyncEnd: (event) => {
23703
+ if (typeof event.result !== "function") {
23704
+ return;
23705
+ }
23706
+ registerHuggingFaceTransformersPipeline(
23707
+ event.result,
23708
+ event.arguments?.[0],
23709
+ event.arguments?.[1]
23710
+ );
23711
+ }
23712
+ };
23713
+ channel2.subscribe(handlers);
23714
+ this.unsubscribers.push(() => channel2.unsubscribe(handlers));
23715
+ }
23716
+ };
23717
+ function getTask(event) {
23718
+ const self = event.self;
23719
+ const registeredTask = getHuggingFaceTransformersPipelineInfo(self)?.task;
23720
+ if (registeredTask !== void 0) {
23721
+ return registeredTask;
23722
+ }
23723
+ if (typeof self?.task === "string") {
23724
+ return self.task;
23725
+ }
23726
+ return void 0;
23727
+ }
23728
+ function extractMetadata(event, args) {
23729
+ const metadata = {
23730
+ provider: "huggingface"
23731
+ };
23732
+ const registeredModel = getHuggingFaceTransformersPipelineInfo(
23733
+ event.self
23734
+ )?.model;
23735
+ const model = registeredModel ?? modelIdentifier(event.self);
23736
+ if (model) {
23737
+ metadata.model = model;
23738
+ }
23739
+ const task = getTask(event);
23740
+ const options = task === "question-answering" ? args[2] : args[1];
23741
+ if (isObject(options)) {
23742
+ for (const key of REQUEST_METADATA_KEYS) {
23743
+ if (options[key] !== void 0) {
23744
+ metadata[key] = options[key];
23745
+ }
23746
+ }
23747
+ }
23748
+ return metadata;
23749
+ }
23750
+ function modelIdentifier(pipeline) {
23751
+ const model = pipeline?.model;
23752
+ if (!isObject(model)) {
23753
+ return void 0;
23754
+ }
23755
+ const config = isObject(model.config) ? model.config : void 0;
23756
+ for (const value of [
23757
+ config?._name_or_path,
23758
+ config?.name_or_path,
23759
+ config?.model_id,
23760
+ config?.modelId,
23761
+ model.name
23762
+ ]) {
23763
+ if (typeof value === "string" && value.length > 0) {
23764
+ return value;
23765
+ }
23766
+ }
23767
+ return void 0;
23768
+ }
23769
+ function extractInput(task, args) {
23770
+ switch (task) {
23771
+ case "feature-extraction":
23772
+ return args[0];
23773
+ case "question-answering": {
23774
+ const question = args[0];
23775
+ const context = args[1];
23776
+ if (Array.isArray(question) && Array.isArray(context) && question.every((value) => typeof value === "string") && context.every((value) => typeof value === "string")) {
23777
+ return question.map((value, index) => [
23778
+ {
23779
+ role: "user",
23780
+ content: `Context:
23781
+ ${context[index] ?? ""}
23782
+
23783
+ Question:
23784
+ ${value}`
23785
+ }
23786
+ ]);
23787
+ }
23788
+ if (typeof question === "string" && typeof context === "string") {
23789
+ return [
23790
+ {
23791
+ role: "user",
23792
+ content: `Context:
23793
+ ${context}
23794
+
23795
+ Question:
23796
+ ${question}`
23797
+ }
23798
+ ];
23799
+ }
23800
+ return { context, question };
23801
+ }
23802
+ }
23803
+ const input = args[0];
23804
+ if (task === "text-generation" && isChat(input)) {
23805
+ return input;
23806
+ }
23807
+ if (task === "text-generation" && Array.isArray(input) && input.every(isChat)) {
23808
+ return input;
23809
+ }
23810
+ if (typeof input === "string") {
23811
+ return [{ role: "user", content: input }];
23812
+ }
23813
+ if (Array.isArray(input) && input.every((value) => typeof value === "string")) {
23814
+ return input.map((value) => [
23815
+ {
23816
+ role: "user",
23817
+ content: value
23818
+ }
23819
+ ]);
23820
+ }
23821
+ return input;
23822
+ }
23823
+ function isChat(value) {
23824
+ return Array.isArray(value) && value.length > 0 && value.every(
23825
+ (message) => isObject(message) && typeof message.role === "string" && "content" in message
23826
+ );
23827
+ }
23828
+ function extractOutput(task, result) {
23829
+ switch (task) {
23830
+ case "feature-extraction":
23831
+ return summarizeEmbedding(result);
23832
+ case "question-answering":
23833
+ return choicesFromAnswers(result);
23834
+ default:
23835
+ return choicesFromGenerations(result);
23836
+ }
23837
+ }
23838
+ function summarizeEmbedding(result) {
23839
+ if (!isObject(result) || !Array.isArray(result.dims)) {
23840
+ return void 0;
23841
+ }
23842
+ const { dims } = result;
23843
+ if (dims.length === 0 || !dims.every((dimension) => typeof dimension === "number")) {
23844
+ return void 0;
23845
+ }
23846
+ if (dims.length === 1) {
23847
+ return { embedding_length: dims[0] };
23848
+ }
23849
+ if (dims.length === 2) {
23850
+ return {
23851
+ embedding_count: dims[0],
23852
+ embedding_length: dims[1]
23853
+ };
23854
+ }
23855
+ return {
23856
+ embedding_batch_count: dims[0],
23857
+ embedding_count: dims[1],
23858
+ embedding_length: dims.at(-1) ?? 0
23859
+ };
23860
+ }
23861
+ function choicesFromAnswers(result) {
23862
+ const answers = Array.isArray(result) ? result.flat() : [result];
23863
+ const choices = answers.flatMap((answer, index) => {
23864
+ if (!isObject(answer) || typeof answer.answer !== "string") {
23865
+ return [];
23866
+ }
23867
+ return [
23868
+ {
23869
+ index,
23870
+ finish_reason: "stop",
23871
+ message: {
23872
+ role: "assistant",
23873
+ content: answer.answer
23874
+ }
23875
+ }
23876
+ ];
23877
+ });
23878
+ return choices.length > 0 ? choices : void 0;
23879
+ }
23880
+ function choicesFromGenerations(result) {
23881
+ const generations = Array.isArray(result) ? result.flat() : [result];
23882
+ const choices = generations.flatMap((generation, index) => {
23883
+ if (!isObject(generation)) {
23884
+ return [];
23885
+ }
23886
+ const generated = generation.generated_text ?? generation.summary_text;
23887
+ let content;
23888
+ if (typeof generated === "string") {
23889
+ content = generated;
23890
+ } else if (isChat(generated)) {
23891
+ content = generated.at(-1)?.content;
23892
+ }
23893
+ if (typeof content !== "string") {
23894
+ return [];
23895
+ }
23896
+ return [
23897
+ {
23898
+ index,
23899
+ finish_reason: "stop",
23900
+ message: {
23901
+ role: "assistant",
23902
+ content
23903
+ }
23904
+ }
23905
+ ];
23906
+ });
23907
+ return choices.length > 0 ? choices : void 0;
23908
+ }
23909
+
23082
23910
  // src/instrumentation/plugins/openrouter-agent-channels.ts
23083
23911
  var openRouterAgentChannels = defineChannels(
23084
23912
  "@openrouter/agent",
@@ -23478,7 +24306,7 @@ function isWrappedTool(tool) {
23478
24306
  return Boolean(tool[OPENROUTER_WRAPPED_TOOL]);
23479
24307
  }
23480
24308
  function traceToolExecution(args) {
23481
- const tracingChannel2 = openRouterAgentChannels.toolExecute.tracingChannel();
24309
+ const tracingChannel = openRouterAgentChannels.toolExecute.tracingChannel();
23482
24310
  const input = args.args.length > 0 ? args.args[0] : void 0;
23483
24311
  const event = {
23484
24312
  arguments: [input],
@@ -23488,33 +24316,33 @@ function traceToolExecution(args) {
23488
24316
  toolCallId: args.toolCallId,
23489
24317
  toolName: args.toolName
23490
24318
  };
23491
- tracingChannel2.start.publish(event);
24319
+ tracingChannel.start.publish(event);
23492
24320
  try {
23493
24321
  const result = args.execute();
23494
- return publishToolResult(tracingChannel2, event, result);
24322
+ return publishToolResult(tracingChannel, event, result);
23495
24323
  } catch (error) {
23496
24324
  event.error = normalizeError(error);
23497
- tracingChannel2.error.publish(event);
24325
+ tracingChannel.error.publish(event);
23498
24326
  throw error;
23499
24327
  }
23500
24328
  }
23501
- function publishToolResult(tracingChannel2, event, result) {
24329
+ function publishToolResult(tracingChannel, event, result) {
23502
24330
  if (isPromiseLike(result)) {
23503
24331
  return result.then(
23504
24332
  (resolved) => {
23505
24333
  event.result = resolved;
23506
- tracingChannel2.asyncEnd.publish(event);
24334
+ tracingChannel.asyncEnd.publish(event);
23507
24335
  return resolved;
23508
24336
  },
23509
24337
  (error) => {
23510
24338
  event.error = normalizeError(error);
23511
- tracingChannel2.error.publish(event);
24339
+ tracingChannel.error.publish(event);
23512
24340
  throw error;
23513
24341
  }
23514
24342
  );
23515
24343
  }
23516
24344
  event.result = result;
23517
- tracingChannel2.asyncEnd.publish(event);
24345
+ tracingChannel.asyncEnd.publish(event);
23518
24346
  return result;
23519
24347
  }
23520
24348
  function getToolCallId(context) {
@@ -24420,7 +25248,7 @@ function isWrappedTool2(tool) {
24420
25248
  return Boolean(tool[OPENROUTER_WRAPPED_TOOL2]);
24421
25249
  }
24422
25250
  function traceToolExecution2(args) {
24423
- const tracingChannel2 = openRouterChannels.toolExecute.tracingChannel();
25251
+ const tracingChannel = openRouterChannels.toolExecute.tracingChannel();
24424
25252
  const input = args.args.length > 0 ? args.args[0] : void 0;
24425
25253
  const event = {
24426
25254
  arguments: [input],
@@ -24430,33 +25258,33 @@ function traceToolExecution2(args) {
24430
25258
  toolCallId: args.toolCallId,
24431
25259
  toolName: args.toolName
24432
25260
  };
24433
- tracingChannel2.start.publish(event);
25261
+ tracingChannel.start.publish(event);
24434
25262
  try {
24435
25263
  const result = args.execute();
24436
- return publishToolResult2(tracingChannel2, event, result);
25264
+ return publishToolResult2(tracingChannel, event, result);
24437
25265
  } catch (error) {
24438
25266
  event.error = normalizeError2(error);
24439
- tracingChannel2.error.publish(event);
25267
+ tracingChannel.error.publish(event);
24440
25268
  throw error;
24441
25269
  }
24442
25270
  }
24443
- function publishToolResult2(tracingChannel2, event, result) {
25271
+ function publishToolResult2(tracingChannel, event, result) {
24444
25272
  if (isPromiseLike(result)) {
24445
25273
  return result.then(
24446
25274
  (resolved) => {
24447
25275
  event.result = resolved;
24448
- tracingChannel2.asyncEnd.publish(event);
25276
+ tracingChannel.asyncEnd.publish(event);
24449
25277
  return resolved;
24450
25278
  },
24451
25279
  (error) => {
24452
25280
  event.error = normalizeError2(error);
24453
- tracingChannel2.error.publish(event);
25281
+ tracingChannel.error.publish(event);
24454
25282
  throw error;
24455
25283
  }
24456
25284
  );
24457
25285
  }
24458
25286
  event.result = result;
24459
- tracingChannel2.asyncEnd.publish(event);
25287
+ tracingChannel.asyncEnd.publish(event);
24460
25288
  return result;
24461
25289
  }
24462
25290
  function getToolCallId2(context) {
@@ -25646,7 +26474,7 @@ var GoogleADKPlugin = class extends BasePlugin {
25646
26474
  this.activeAgentSpans.clear();
25647
26475
  }
25648
26476
  subscribeToRunnerRunAsync() {
25649
- const tracingChannel2 = googleADKChannels.runnerRunAsync.tracingChannel();
26477
+ const tracingChannel = googleADKChannels.runnerRunAsync.tracingChannel();
25650
26478
  const states = /* @__PURE__ */ new WeakMap();
25651
26479
  const createState = (event) => {
25652
26480
  const params = event.arguments[0] ?? {};
@@ -25677,7 +26505,7 @@ var GoogleADKPlugin = class extends BasePlugin {
25677
26505
  return { span, startTime, events: [], contextKey };
25678
26506
  };
25679
26507
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart3(
25680
- tracingChannel2,
26508
+ tracingChannel,
25681
26509
  states,
25682
26510
  createState
25683
26511
  );
@@ -25729,14 +26557,14 @@ var GoogleADKPlugin = class extends BasePlugin {
25729
26557
  states.delete(event);
25730
26558
  }
25731
26559
  };
25732
- tracingChannel2.subscribe(handlers);
26560
+ tracingChannel.subscribe(handlers);
25733
26561
  this.unsubscribers.push(() => {
25734
26562
  unbindCurrentSpanStore?.();
25735
- tracingChannel2.unsubscribe(handlers);
26563
+ tracingChannel.unsubscribe(handlers);
25736
26564
  });
25737
26565
  }
25738
26566
  subscribeToAgentRunAsync() {
25739
- const tracingChannel2 = googleADKChannels.agentRunAsync.tracingChannel();
26567
+ const tracingChannel = googleADKChannels.agentRunAsync.tracingChannel();
25740
26568
  const states = /* @__PURE__ */ new WeakMap();
25741
26569
  const createState = (event) => {
25742
26570
  const parentContext = event.arguments[0];
@@ -25785,7 +26613,7 @@ var GoogleADKPlugin = class extends BasePlugin {
25785
26613
  return { span, startTime, events: [], contextKey, name: agentName };
25786
26614
  };
25787
26615
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart3(
25788
- tracingChannel2,
26616
+ tracingChannel,
25789
26617
  states,
25790
26618
  createState
25791
26619
  );
@@ -25837,14 +26665,14 @@ var GoogleADKPlugin = class extends BasePlugin {
25837
26665
  states.delete(event);
25838
26666
  }
25839
26667
  };
25840
- tracingChannel2.subscribe(handlers);
26668
+ tracingChannel.subscribe(handlers);
25841
26669
  this.unsubscribers.push(() => {
25842
26670
  unbindCurrentSpanStore?.();
25843
- tracingChannel2.unsubscribe(handlers);
26671
+ tracingChannel.unsubscribe(handlers);
25844
26672
  });
25845
26673
  }
25846
26674
  subscribeToToolRunAsync() {
25847
- const tracingChannel2 = googleADKChannels.toolRunAsync.tracingChannel();
26675
+ const tracingChannel = googleADKChannels.toolRunAsync.tracingChannel();
25848
26676
  const states = /* @__PURE__ */ new WeakMap();
25849
26677
  const handlers = {
25850
26678
  start: (event) => {
@@ -25911,9 +26739,9 @@ var GoogleADKPlugin = class extends BasePlugin {
25911
26739
  states.delete(event);
25912
26740
  }
25913
26741
  };
25914
- tracingChannel2.subscribe(handlers);
26742
+ tracingChannel.subscribe(handlers);
25915
26743
  this.unsubscribers.push(() => {
25916
- tracingChannel2.unsubscribe(handlers);
26744
+ tracingChannel.unsubscribe(handlers);
25917
26745
  });
25918
26746
  }
25919
26747
  };
@@ -25989,10 +26817,10 @@ function bindAsyncIterableToCurrentSpan(stream, span) {
25989
26817
  }
25990
26818
  return stream;
25991
26819
  }
25992
- function bindCurrentSpanStoreToStart3(tracingChannel2, states, create) {
26820
+ function bindCurrentSpanStoreToStart3(tracingChannel, states, create) {
25993
26821
  const state = _internalGetGlobalState();
25994
26822
  const contextManager = state?.contextManager;
25995
- const startChannel = tracingChannel2.start;
26823
+ const startChannel = tracingChannel.start;
25996
26824
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
25997
26825
  if (!startChannel?.bindStore || !currentSpanStore) {
25998
26826
  return void 0;
@@ -26244,15 +27072,32 @@ function aggregateUsageFromEvents(events) {
26244
27072
  if (usage.thoughtsTokenCount !== void 0) {
26245
27073
  aggregated.thoughtsTokenCount = (aggregated.thoughtsTokenCount ?? 0) + usage.thoughtsTokenCount;
26246
27074
  }
27075
+ if (usage.toolUsePromptTokenCount !== void 0) {
27076
+ aggregated.toolUsePromptTokenCount = (aggregated.toolUsePromptTokenCount ?? 0) + usage.toolUsePromptTokenCount;
27077
+ }
27078
+ for (const detailsField of [
27079
+ "promptTokensDetails",
27080
+ "cacheTokensDetails",
27081
+ "candidatesTokensDetails",
27082
+ "toolUsePromptTokensDetails"
27083
+ ]) {
27084
+ const details = usage[detailsField];
27085
+ if (details !== void 0) {
27086
+ aggregated[detailsField] = [
27087
+ ...aggregated[detailsField] ?? [],
27088
+ ...details
27089
+ ];
27090
+ }
27091
+ }
26247
27092
  }
26248
27093
  return hasUsage ? aggregated : void 0;
26249
27094
  }
26250
27095
  function populateUsageMetrics2(metrics, usage) {
26251
- if (usage.promptTokenCount !== void 0) {
26252
- metrics.prompt_tokens = usage.promptTokenCount;
27096
+ if (usage.promptTokenCount !== void 0 || usage.toolUsePromptTokenCount !== void 0) {
27097
+ metrics.prompt_tokens = (usage.promptTokenCount ?? 0) + (usage.toolUsePromptTokenCount ?? 0);
26253
27098
  }
26254
- if (usage.candidatesTokenCount !== void 0) {
26255
- metrics.completion_tokens = usage.candidatesTokenCount;
27099
+ if (usage.candidatesTokenCount !== void 0 || usage.thoughtsTokenCount !== void 0) {
27100
+ metrics.completion_tokens = (usage.candidatesTokenCount ?? 0) + (usage.thoughtsTokenCount ?? 0);
26256
27101
  }
26257
27102
  if (usage.totalTokenCount !== void 0) {
26258
27103
  metrics.tokens = usage.totalTokenCount;
@@ -26263,6 +27108,19 @@ function populateUsageMetrics2(metrics, usage) {
26263
27108
  if (usage.thoughtsTokenCount !== void 0) {
26264
27109
  metrics.completion_reasoning_tokens = usage.thoughtsTokenCount;
26265
27110
  }
27111
+ for (const detail of usage.promptTokensDetails ?? []) {
27112
+ if (detail.modality === "AUDIO" && detail.tokenCount !== void 0) {
27113
+ metrics.prompt_audio_tokens = (metrics.prompt_audio_tokens ?? 0) + detail.tokenCount;
27114
+ }
27115
+ }
27116
+ for (const detail of usage.candidatesTokensDetails ?? []) {
27117
+ if (detail.modality === "AUDIO" && detail.tokenCount !== void 0) {
27118
+ metrics.completion_audio_tokens = (metrics.completion_audio_tokens ?? 0) + detail.tokenCount;
27119
+ }
27120
+ if (detail.modality === "IMAGE" && detail.tokenCount !== void 0) {
27121
+ metrics.completion_image_tokens = (metrics.completion_image_tokens ?? 0) + detail.tokenCount;
27122
+ }
27123
+ }
26266
27124
  }
26267
27125
  function cleanMetrics4(metrics) {
26268
27126
  const cleaned = {};
@@ -27828,10 +28686,10 @@ var GenkitPlugin = class extends BasePlugin {
27828
28686
  this.subscribeToActionStream();
27829
28687
  }
27830
28688
  subscribeToActionRun() {
27831
- const tracingChannel2 = genkitChannels.actionRun.tracingChannel();
28689
+ const tracingChannel = genkitChannels.actionRun.tracingChannel();
27832
28690
  const states = /* @__PURE__ */ new WeakMap();
27833
28691
  const unbindCurrentSpanStore = bindActionCurrentSpanStoreToStart(
27834
- tracingChannel2,
28692
+ tracingChannel,
27835
28693
  states,
27836
28694
  (event) => startActionRunSpan(event)
27837
28695
  );
@@ -27868,17 +28726,17 @@ var GenkitPlugin = class extends BasePlugin {
27868
28726
  states.delete(event);
27869
28727
  }
27870
28728
  };
27871
- tracingChannel2.subscribe(handlers);
28729
+ tracingChannel.subscribe(handlers);
27872
28730
  this.unsubscribers.push(() => {
27873
28731
  unbindCurrentSpanStore?.();
27874
- tracingChannel2.unsubscribe(handlers);
28732
+ tracingChannel.unsubscribe(handlers);
27875
28733
  });
27876
28734
  }
27877
28735
  subscribeToActionSpan() {
27878
- const tracingChannel2 = genkitCoreChannels.actionSpan.tracingChannel();
28736
+ const tracingChannel = genkitCoreChannels.actionSpan.tracingChannel();
27879
28737
  const states = /* @__PURE__ */ new WeakMap();
27880
28738
  const unbindCurrentSpanStore = bindActionCurrentSpanStoreToStart(
27881
- tracingChannel2,
28739
+ tracingChannel,
27882
28740
  states,
27883
28741
  (event) => startActionSpan(event)
27884
28742
  );
@@ -27916,10 +28774,10 @@ var GenkitPlugin = class extends BasePlugin {
27916
28774
  states.delete(event);
27917
28775
  }
27918
28776
  };
27919
- tracingChannel2.subscribe(handlers);
28777
+ tracingChannel.subscribe(handlers);
27920
28778
  this.unsubscribers.push(() => {
27921
28779
  unbindCurrentSpanStore?.();
27922
- tracingChannel2.unsubscribe(handlers);
28780
+ tracingChannel.unsubscribe(handlers);
27923
28781
  });
27924
28782
  }
27925
28783
  subscribeToActionStream() {
@@ -27988,10 +28846,10 @@ function ensureActionSpanState(states, event, create) {
27988
28846
  }
27989
28847
  return created;
27990
28848
  }
27991
- function bindActionCurrentSpanStoreToStart(tracingChannel2, states, create) {
28849
+ function bindActionCurrentSpanStoreToStart(tracingChannel, states, create) {
27992
28850
  const state = _internalGetGlobalState();
27993
28851
  const contextManager = state?.contextManager;
27994
- const startChannel = tracingChannel2.start;
28852
+ const startChannel = tracingChannel.start;
27995
28853
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
27996
28854
  if (!startChannel?.bindStore || !currentSpanStore) {
27997
28855
  return void 0;
@@ -30353,7 +31211,7 @@ var LangChainPlugin = class extends BasePlugin {
30353
31211
  this.injectedManagers = /* @__PURE__ */ new WeakSet();
30354
31212
  }
30355
31213
  subscribeToConfigure(channel2) {
30356
- const tracingChannel2 = channel2.tracingChannel();
31214
+ const tracingChannel = channel2.tracingChannel();
30357
31215
  const handlers = {
30358
31216
  start: (event) => {
30359
31217
  injectHandlerIntoArguments(event.arguments);
@@ -30362,9 +31220,9 @@ var LangChainPlugin = class extends BasePlugin {
30362
31220
  this.injectHandler(event.result);
30363
31221
  }
30364
31222
  };
30365
- tracingChannel2.subscribe(handlers);
31223
+ tracingChannel.subscribe(handlers);
30366
31224
  this.unsubscribers.push(() => {
30367
- tracingChannel2.unsubscribe(handlers);
31225
+ tracingChannel.unsubscribe(handlers);
30368
31226
  });
30369
31227
  }
30370
31228
  injectHandler(result) {
@@ -30628,7 +31486,7 @@ var LangSmithPlugin = class extends BasePlugin {
30628
31486
  const inputs = preferOwnValue(run, previous, "inputs");
30629
31487
  const outputs = preferOwnValue(run, previous, "outputs");
30630
31488
  const error = errorMessage(preferOwnValue(run, previous, "error"));
30631
- const metadata = extractMetadata(run, previous);
31489
+ const metadata = extractMetadata2(run, previous);
30632
31490
  const tags = extractTags(preferOwnValue(run, previous, "tags"));
30633
31491
  const metrics = extractMetrics(run, previous);
30634
31492
  span.log({
@@ -30733,7 +31591,7 @@ function mapRunType(runType) {
30733
31591
  return "task" /* TASK */;
30734
31592
  }
30735
31593
  }
30736
- function extractMetadata(run, previous) {
31594
+ function extractMetadata2(run, previous) {
30737
31595
  const extra = preferOwnValue(run, previous, "extra");
30738
31596
  const rawMetadata = ownValue(extra, "metadata");
30739
31597
  if (!isRecord2(rawMetadata)) {
@@ -31864,9 +32722,9 @@ var StrandsAgentSDKPlugin = class extends BasePlugin {
31864
32722
  });
31865
32723
  }
31866
32724
  subscribeToMultiAgentStream(channel2, operation) {
31867
- const tracingChannel2 = channel2.tracingChannel();
32725
+ const tracingChannel = channel2.tracingChannel();
31868
32726
  const states = /* @__PURE__ */ new WeakMap();
31869
- const unbindAutoInstrumentationSuppression = bindAutoInstrumentationSuppressionToStart(tracingChannel2);
32727
+ const unbindAutoInstrumentationSuppression = bindAutoInstrumentationSuppressionToStart(tracingChannel);
31870
32728
  const handlers = {
31871
32729
  start: (event) => {
31872
32730
  const state = startMultiAgentStream(
@@ -31920,10 +32778,10 @@ var StrandsAgentSDKPlugin = class extends BasePlugin {
31920
32778
  states.delete(event);
31921
32779
  }
31922
32780
  };
31923
- tracingChannel2.subscribe(handlers);
32781
+ tracingChannel.subscribe(handlers);
31924
32782
  this.unsubscribers.push(() => {
31925
32783
  unbindAutoInstrumentationSuppression?.();
31926
- tracingChannel2.unsubscribe(handlers);
32784
+ tracingChannel.unsubscribe(handlers);
31927
32785
  });
31928
32786
  }
31929
32787
  };
@@ -32106,6 +32964,15 @@ function handleMultiAgentStreamEvent(state, event, activeChildParents) {
32106
32964
  logInstrumentationError5("Strands Agent SDK multi-agent event", error);
32107
32965
  }
32108
32966
  }
32967
+ function buildModelSpanInput(event, attachmentCache) {
32968
+ const systemPrompt = typeof event.agent?.systemPrompt === "string" && event.agent.systemPrompt.length > 0 ? event.agent.systemPrompt : void 0;
32969
+ const processedMessages = Array.isArray(event.agent?.messages) ? processStrandsInputAttachments(event.agent.messages, attachmentCache) : void 0;
32970
+ if (!systemPrompt) {
32971
+ return processedMessages;
32972
+ }
32973
+ const systemMessage = { role: "system", content: systemPrompt };
32974
+ return Array.isArray(processedMessages) ? [systemMessage, ...processedMessages] : [systemMessage];
32975
+ }
32109
32976
  function startModelSpan(state, event) {
32110
32977
  if (state.activeModel) {
32111
32978
  finalizeModelSpan(state);
@@ -32123,10 +32990,7 @@ function startModelSpan(state, event) {
32123
32990
  withSpanInstrumentationName(
32124
32991
  {
32125
32992
  event: {
32126
- input: Array.isArray(event.agent?.messages) ? processStrandsInputAttachments(
32127
- event.agent.messages,
32128
- state.attachmentCache
32129
- ) : void 0,
32993
+ input: buildModelSpanInput(event, state.attachmentCache),
32130
32994
  metadata
32131
32995
  },
32132
32996
  name: formatModelSpanName(model),
@@ -32766,6 +33630,555 @@ function logInstrumentationError5(context, error) {
32766
33630
  debugLogger.debug(`${context}:`, error);
32767
33631
  }
32768
33632
 
33633
+ // src/instrumentation/plugins/cloudflare-ai-chat-channels.ts
33634
+ var cloudflareAIChatChannels = defineChannels(
33635
+ "@cloudflare/ai-chat",
33636
+ {
33637
+ runExclusiveChatTurn: channel({
33638
+ channelName: "AIChatAgent._runExclusiveChatTurn",
33639
+ kind: "async"
33640
+ }),
33641
+ onChatResponse: channel({
33642
+ channelName: "AIChatAgent.onChatResponse",
33643
+ kind: "sync-stream"
33644
+ })
33645
+ },
33646
+ { instrumentationName: INSTRUMENTATION_NAMES.CLOUDFLARE_AI_CHAT }
33647
+ );
33648
+
33649
+ // src/instrumentation/plugins/cloudflare-ai-chat-instrumentation.ts
33650
+ var wrappedTurnRunners = /* @__PURE__ */ new WeakSet();
33651
+ var wrappedResponseHooks = /* @__PURE__ */ new WeakSet();
33652
+ function instrumentCloudflareAIChatAgent(agent) {
33653
+ try {
33654
+ const original = Reflect.get(agent, "_runExclusiveChatTurn");
33655
+ if (typeof original !== "function" || wrappedTurnRunners.has(original)) {
33656
+ return agent;
33657
+ }
33658
+ const wrapped = async function(...args) {
33659
+ return cloudflareAIChatChannels.runExclusiveChatTurn.tracePromise(
33660
+ () => Reflect.apply(original, this, args),
33661
+ {
33662
+ arguments: args,
33663
+ self: this
33664
+ }
33665
+ );
33666
+ };
33667
+ wrappedTurnRunners.add(wrapped);
33668
+ defineWrappedMethod(agent, "_runExclusiveChatTurn", original, wrapped);
33669
+ } catch (error) {
33670
+ debugLogger.debug("Failed to wrap @cloudflare/ai-chat turn runner:", error);
33671
+ }
33672
+ return agent;
33673
+ }
33674
+ function instrumentCloudflareAIChatResponseHook(agent) {
33675
+ try {
33676
+ const original = Reflect.get(agent, "onChatResponse");
33677
+ if (typeof original !== "function" || wrappedResponseHooks.has(original)) {
33678
+ return;
33679
+ }
33680
+ const wrapped = function(result) {
33681
+ const args = [result];
33682
+ return cloudflareAIChatChannels.onChatResponse.traceSync(
33683
+ () => Reflect.apply(original, this, args),
33684
+ {
33685
+ arguments: args,
33686
+ self: this
33687
+ }
33688
+ );
33689
+ };
33690
+ wrappedResponseHooks.add(wrapped);
33691
+ defineWrappedMethod(agent, "onChatResponse", original, wrapped);
33692
+ } catch (error) {
33693
+ debugLogger.debug(
33694
+ "Failed to wrap @cloudflare/ai-chat response hook:",
33695
+ error
33696
+ );
33697
+ }
33698
+ }
33699
+ function defineWrappedMethod(target, property, original, wrapped) {
33700
+ const ownDescriptor = Object.getOwnPropertyDescriptor(target, property);
33701
+ Object.defineProperty(target, property, {
33702
+ configurable: ownDescriptor?.configurable ?? true,
33703
+ enumerable: ownDescriptor?.enumerable ?? false,
33704
+ value: wrapped,
33705
+ writable: ownDescriptor && "writable" in ownDescriptor ? ownDescriptor.writable : true
33706
+ });
33707
+ try {
33708
+ Object.defineProperty(wrapped, "name", {
33709
+ configurable: true,
33710
+ value: original.name
33711
+ });
33712
+ } catch {
33713
+ }
33714
+ }
33715
+
33716
+ // src/instrumentation/plugins/cloudflare-ai-chat-plugin.ts
33717
+ var BLOCKED_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
33718
+ var RESPONSE_STATE_RETENTION_MS = 6e4;
33719
+ var CloudflareAIChatPlugin = class extends BasePlugin {
33720
+ activeStates = /* @__PURE__ */ new Set();
33721
+ activeTurns = /* @__PURE__ */ new WeakMap();
33722
+ eventStates = /* @__PURE__ */ new WeakMap();
33723
+ onEnable() {
33724
+ this.subscribeToResponseHook();
33725
+ this.subscribeToTurnRunner();
33726
+ }
33727
+ onDisable() {
33728
+ for (const unsubscribe of this.unsubscribers) {
33729
+ unsubscribe();
33730
+ }
33731
+ this.unsubscribers = [];
33732
+ for (const state of this.activeStates) {
33733
+ this.cleanupState(state);
33734
+ }
33735
+ this.activeStates.clear();
33736
+ }
33737
+ subscribeToTurnRunner() {
33738
+ const tracingChannel = cloudflareAIChatChannels.runExclusiveChatTurn.tracingChannel();
33739
+ const unbindCurrentSpanStore = this.bindCurrentSpanStore(tracingChannel);
33740
+ const handlers = {
33741
+ start: (event) => {
33742
+ this.ensureEventState(event);
33743
+ },
33744
+ asyncEnd: (event) => {
33745
+ this.finishEvent(event);
33746
+ },
33747
+ error: (event) => {
33748
+ this.finishEvent(event, event.error);
33749
+ }
33750
+ };
33751
+ tracingChannel.subscribe(handlers);
33752
+ this.unsubscribers.push(() => {
33753
+ unbindCurrentSpanStore?.();
33754
+ tracingChannel.unsubscribe(handlers);
33755
+ });
33756
+ }
33757
+ subscribeToResponseHook() {
33758
+ const tracingChannel = cloudflareAIChatChannels.onChatResponse.tracingChannel();
33759
+ const handlers = {
33760
+ start: (event) => {
33761
+ let state;
33762
+ try {
33763
+ const agent = asObject(event.self);
33764
+ const result = event.arguments[0];
33765
+ state = agent ? this.findResponseState(
33766
+ agent,
33767
+ stringValue3(ownValue2(result, "requestId"))
33768
+ ) : void 0;
33769
+ if (!state) {
33770
+ return;
33771
+ }
33772
+ state.responseObserved = true;
33773
+ const output = serializeMessage(ownValue2(result, "message"));
33774
+ const status = stringValue3(ownValue2(result, "status"));
33775
+ const error = ownValue2(result, "error");
33776
+ const input = ownValue2(result, "continuation") === true ? state.input : serializeMessages(readProperty(agent, "messages"))?.filter(
33777
+ (message) => typeof output?.id !== "string" || message.id !== output.id
33778
+ );
33779
+ state.span.log({
33780
+ ...input !== void 0 ? { input } : {},
33781
+ ...output !== void 0 ? { output } : {},
33782
+ ...status === "error" && error !== void 0 ? { error } : {}
33783
+ });
33784
+ } catch (error) {
33785
+ debugLogger.debug(
33786
+ "Failed to process @cloudflare/ai-chat response hook:",
33787
+ error
33788
+ );
33789
+ } finally {
33790
+ if (state?.settled) {
33791
+ this.cleanupState(state);
33792
+ }
33793
+ }
33794
+ }
33795
+ };
33796
+ tracingChannel.subscribe(handlers);
33797
+ this.unsubscribers.push(() => tracingChannel.unsubscribe(handlers));
33798
+ }
33799
+ bindCurrentSpanStore(tracingChannel) {
33800
+ const globalState = _internalGetGlobalState();
33801
+ const contextManager = globalState?.contextManager;
33802
+ const startChannel = tracingChannel.start;
33803
+ const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
33804
+ if (!startChannel || !currentSpanStore || !contextManager) {
33805
+ return void 0;
33806
+ }
33807
+ startChannel.bindStore(currentSpanStore, (event) => {
33808
+ const state = this.ensureEventState(event);
33809
+ return state ? contextManager.wrapSpanForStore(state.span) : currentSpanStore.getStore();
33810
+ });
33811
+ return () => startChannel.unbindStore(currentSpanStore);
33812
+ }
33813
+ ensureEventState(event) {
33814
+ const eventKey = event;
33815
+ const known = this.eventStates.get(eventKey);
33816
+ if (known) {
33817
+ return known;
33818
+ }
33819
+ try {
33820
+ const agent = asObject(event.self);
33821
+ const requestId = stringValue3(event.arguments[0]);
33822
+ const key = requestId ?? /* @__PURE__ */ Symbol("cloudflare-ai-chat-turn");
33823
+ const activeForAgent = agent ? this.getActiveTurns(agent) : void 0;
33824
+ const existing = activeForAgent?.get(key);
33825
+ const state = existing && !existing.settled ? existing : this.createTurnState(agent, key);
33826
+ if (existing && !existing.settled) {
33827
+ state.depth += 1;
33828
+ }
33829
+ this.eventStates.set(eventKey, state);
33830
+ this.bindTurnCallback(event, agent, state);
33831
+ if (agent) {
33832
+ instrumentCloudflareAIChatResponseHook(agent);
33833
+ }
33834
+ return state;
33835
+ } catch (error) {
33836
+ debugLogger.debug(
33837
+ "Failed to start @cloudflare/ai-chat instrumentation:",
33838
+ error
33839
+ );
33840
+ return void 0;
33841
+ }
33842
+ }
33843
+ createTurnState(agent, key) {
33844
+ const span = startSpan(
33845
+ withSpanInstrumentationName(
33846
+ {
33847
+ name: "AIChatAgent.onChatMessage",
33848
+ spanAttributes: { type: "task" /* TASK */ }
33849
+ },
33850
+ INSTRUMENTATION_NAMES.CLOUDFLARE_AI_CHAT
33851
+ )
33852
+ );
33853
+ const state = {
33854
+ agent,
33855
+ depth: 1,
33856
+ ended: false,
33857
+ key,
33858
+ responseObserved: false,
33859
+ settled: false,
33860
+ span
33861
+ };
33862
+ this.activeStates.add(state);
33863
+ if (agent) {
33864
+ this.getActiveTurns(agent).set(key, state);
33865
+ }
33866
+ return state;
33867
+ }
33868
+ bindTurnCallback(event, agent, state) {
33869
+ const callback = event.arguments[1];
33870
+ if (typeof callback !== "function") {
33871
+ return;
33872
+ }
33873
+ try {
33874
+ event.arguments[1] = function(...args) {
33875
+ return withCurrent(state.span, () => {
33876
+ try {
33877
+ const input = serializeMessages(readProperty(agent, "messages"));
33878
+ if (input !== void 0 && state.input === void 0) {
33879
+ state.input = input;
33880
+ state.span.log({ input });
33881
+ }
33882
+ } catch (error) {
33883
+ debugLogger.debug(
33884
+ "Failed to capture @cloudflare/ai-chat messages:",
33885
+ error
33886
+ );
33887
+ }
33888
+ return Reflect.apply(callback, this, args);
33889
+ });
33890
+ };
33891
+ } catch (error) {
33892
+ debugLogger.debug(
33893
+ "Failed to bind @cloudflare/ai-chat turn callback context:",
33894
+ error
33895
+ );
33896
+ }
33897
+ }
33898
+ finishEvent(event, error) {
33899
+ const eventKey = event;
33900
+ const state = this.eventStates.get(eventKey);
33901
+ if (!state || state.ended) {
33902
+ return;
33903
+ }
33904
+ this.eventStates.delete(eventKey);
33905
+ if (error !== void 0 && state.pendingError === void 0) {
33906
+ state.pendingError = error;
33907
+ }
33908
+ state.depth -= 1;
33909
+ if (state.depth === 0) {
33910
+ state.settled = true;
33911
+ this.endState(state);
33912
+ if (state.responseObserved || error !== void 0) {
33913
+ this.cleanupState(state);
33914
+ } else {
33915
+ state.cleanupTimer = setTimeout(
33916
+ () => this.cleanupState(state),
33917
+ RESPONSE_STATE_RETENTION_MS
33918
+ );
33919
+ if (typeof state.cleanupTimer === "object" && state.cleanupTimer !== null && "unref" in state.cleanupTimer && typeof state.cleanupTimer.unref === "function") {
33920
+ state.cleanupTimer.unref();
33921
+ }
33922
+ }
33923
+ }
33924
+ }
33925
+ endState(state) {
33926
+ if (state.ended) {
33927
+ return;
33928
+ }
33929
+ state.ended = true;
33930
+ try {
33931
+ if (state.pendingError !== void 0) {
33932
+ state.span.log({ error: state.pendingError });
33933
+ }
33934
+ } finally {
33935
+ state.span.end();
33936
+ }
33937
+ }
33938
+ cleanupState(state) {
33939
+ if (state.cleanupTimer !== void 0) {
33940
+ clearTimeout(state.cleanupTimer);
33941
+ state.cleanupTimer = void 0;
33942
+ }
33943
+ try {
33944
+ this.endState(state);
33945
+ } finally {
33946
+ this.activeStates.delete(state);
33947
+ if (state.agent) {
33948
+ const activeForAgent = this.activeTurns.get(state.agent);
33949
+ if (activeForAgent?.get(state.key) === state) {
33950
+ activeForAgent.delete(state.key);
33951
+ }
33952
+ }
33953
+ }
33954
+ }
33955
+ getActiveTurns(agent) {
33956
+ let turns = this.activeTurns.get(agent);
33957
+ if (!turns) {
33958
+ turns = /* @__PURE__ */ new Map();
33959
+ this.activeTurns.set(agent, turns);
33960
+ }
33961
+ return turns;
33962
+ }
33963
+ findResponseState(agent, requestId) {
33964
+ const turns = this.activeTurns.get(agent);
33965
+ if (!turns) {
33966
+ return void 0;
33967
+ }
33968
+ if (requestId !== void 0) {
33969
+ return turns.get(requestId);
33970
+ }
33971
+ const active = [...turns.values()];
33972
+ return active.length === 1 ? active[0] : void 0;
33973
+ }
33974
+ };
33975
+ function asObject(value) {
33976
+ return value !== null && (typeof value === "object" || typeof value === "function") ? value : void 0;
33977
+ }
33978
+ function readProperty(value, key) {
33979
+ const object = asObject(value);
33980
+ return object ? Reflect.get(object, key) : void 0;
33981
+ }
33982
+ function ownValue2(value, key) {
33983
+ const object = asObject(value);
33984
+ if (!object) {
33985
+ return void 0;
33986
+ }
33987
+ const descriptor = Object.getOwnPropertyDescriptor(object, key);
33988
+ return descriptor && "value" in descriptor ? descriptor.value : void 0;
33989
+ }
33990
+ function stringValue3(value) {
33991
+ return typeof value === "string" ? value : void 0;
33992
+ }
33993
+ function serializeMessages(value) {
33994
+ if (!Array.isArray(value)) {
33995
+ return void 0;
33996
+ }
33997
+ return value.flatMap((message) => {
33998
+ const serialized = serializeMessage(message);
33999
+ return serialized === void 0 ? [] : [serialized];
34000
+ });
34001
+ }
34002
+ function serializeMessage(value) {
34003
+ const message = asObject(value);
34004
+ if (!message) {
34005
+ return void 0;
34006
+ }
34007
+ const serialized = [];
34008
+ const id = ownValue2(message, "id");
34009
+ const role = ownValue2(message, "role");
34010
+ const parts = ownValue2(message, "parts");
34011
+ if (typeof id === "string") {
34012
+ serialized.push(["id", id]);
34013
+ }
34014
+ if (typeof role === "string") {
34015
+ serialized.push(["role", role]);
34016
+ }
34017
+ const sanitizedParts = sanitizeLoggedValue2(parts);
34018
+ if (sanitizedParts !== void 0) {
34019
+ serialized.push(["parts", sanitizedParts]);
34020
+ }
34021
+ return serialized.length > 0 ? Object.fromEntries(serialized) : void 0;
34022
+ }
34023
+ function sanitizeLoggedValue2(value, seen = /* @__PURE__ */ new WeakSet(), depth = 0) {
34024
+ if (value === null || typeof value === "string" || typeof value === "boolean") {
34025
+ return value;
34026
+ }
34027
+ if (typeof value === "number") {
34028
+ return Number.isFinite(value) ? value : void 0;
34029
+ }
34030
+ const object = asObject(value);
34031
+ if (!object || depth >= 20 || typeof value === "function") {
34032
+ return void 0;
34033
+ }
34034
+ if (seen.has(object)) {
34035
+ return "[Circular]";
34036
+ }
34037
+ seen.add(object);
34038
+ if (Array.isArray(value)) {
34039
+ return value.map((entry) => sanitizeLoggedValue2(entry, seen, depth + 1));
34040
+ }
34041
+ const entries = [];
34042
+ for (const [key, descriptor] of Object.entries(
34043
+ Object.getOwnPropertyDescriptors(object)
34044
+ )) {
34045
+ if (BLOCKED_KEYS.has(key) || !descriptor.enumerable || !("value" in descriptor)) {
34046
+ continue;
34047
+ }
34048
+ const sanitized = sanitizeLoggedValue2(descriptor.value, seen, depth + 1);
34049
+ if (sanitized !== void 0) {
34050
+ entries.push([key, sanitized]);
34051
+ }
34052
+ }
34053
+ return Object.fromEntries(entries);
34054
+ }
34055
+
34056
+ // src/instrumentation/plugins/cloudflare-agents-channels.ts
34057
+ var cloudflareAgentsChannels = defineChannels(
34058
+ "agents",
34059
+ {
34060
+ runAgentTool: channel({
34061
+ channelName: "Agent.runAgentTool",
34062
+ kind: "async"
34063
+ })
34064
+ },
34065
+ { instrumentationName: INSTRUMENTATION_NAMES.CLOUDFLARE_AGENTS }
34066
+ );
34067
+
34068
+ // src/instrumentation/plugins/cloudflare-agents-plugin.ts
34069
+ var CLOUDFLARE_WORKERS_CONTEXT = {
34070
+ span_origin: {
34071
+ environment: { type: "server", name: "cloudflare_workers" }
34072
+ }
34073
+ };
34074
+ var CloudflareAgentsPlugin = class extends BasePlugin {
34075
+ onEnable() {
34076
+ const channel2 = cloudflareAgentsChannels.runAgentTool.tracingChannel();
34077
+ const spans = /* @__PURE__ */ new WeakMap();
34078
+ const handlers = {
34079
+ start: (event) => {
34080
+ try {
34081
+ const agentClass = event.arguments[0];
34082
+ const options = event.arguments[1];
34083
+ if (ownValue3(options, "detached")) {
34084
+ return;
34085
+ }
34086
+ const name = ownValue3(agentClass, "name");
34087
+ if (typeof name !== "string" || name.length === 0) {
34088
+ debugLogger.warn(
34089
+ "Skipping Cloudflare Agents runAgentTool span because the child agent class has no name."
34090
+ );
34091
+ return;
34092
+ }
34093
+ const span = _internalStartSpanWithContext(
34094
+ withSpanInstrumentationName(
34095
+ {
34096
+ name,
34097
+ spanAttributes: { type: "tool" /* TOOL */ },
34098
+ event: {
34099
+ input: ownValue3(options, "input")
34100
+ }
34101
+ },
34102
+ INSTRUMENTATION_NAMES.CLOUDFLARE_AGENTS
34103
+ ),
34104
+ CLOUDFLARE_WORKERS_CONTEXT
34105
+ );
34106
+ spans.set(event, span);
34107
+ } catch (error) {
34108
+ logInstrumentationError6("start", error);
34109
+ }
34110
+ },
34111
+ asyncEnd: (event) => {
34112
+ const span = spans.get(event);
34113
+ if (!span) {
34114
+ return;
34115
+ }
34116
+ spans.delete(event);
34117
+ try {
34118
+ const status = ownValue3(event.result, "status");
34119
+ if (status === "completed") {
34120
+ span.log({ output: ownValue3(event.result, "output") });
34121
+ } else {
34122
+ const error = ownValue3(event.result, "error");
34123
+ if (typeof error === "string") {
34124
+ span.log({ error });
34125
+ }
34126
+ }
34127
+ } catch (error) {
34128
+ logInstrumentationError6("completion", error);
34129
+ } finally {
34130
+ safelyEndSpan(span);
34131
+ }
34132
+ },
34133
+ error: (event) => {
34134
+ const span = spans.get(event);
34135
+ if (!span) {
34136
+ return;
34137
+ }
34138
+ spans.delete(event);
34139
+ try {
34140
+ span.log({ error: event.error });
34141
+ } catch (error) {
34142
+ logInstrumentationError6("rejection", error);
34143
+ } finally {
34144
+ safelyEndSpan(span);
34145
+ }
34146
+ }
34147
+ };
34148
+ channel2.subscribe(handlers);
34149
+ this.unsubscribers.push(() => channel2.unsubscribe(handlers));
34150
+ }
34151
+ onDisable() {
34152
+ for (const unsubscribe of this.unsubscribers) {
34153
+ unsubscribe();
34154
+ }
34155
+ this.unsubscribers = [];
34156
+ }
34157
+ };
34158
+ function ownValue3(value, key) {
34159
+ if (!isObjectLike2(value)) {
34160
+ return void 0;
34161
+ }
34162
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
34163
+ return descriptor && "value" in descriptor ? descriptor.value : void 0;
34164
+ }
34165
+ function isObjectLike2(value) {
34166
+ return typeof value === "object" && value !== null || typeof value === "function";
34167
+ }
34168
+ function safelyEndSpan(span) {
34169
+ try {
34170
+ span.end();
34171
+ } catch (error) {
34172
+ logInstrumentationError6("span end", error);
34173
+ }
34174
+ }
34175
+ function logInstrumentationError6(operation, error) {
34176
+ debugLogger.error(
34177
+ `Failed to process Cloudflare Agents ${operation} instrumentation:`,
34178
+ error
34179
+ );
34180
+ }
34181
+
32769
34182
  // src/instrumentation/braintrust-plugin.ts
32770
34183
  var BraintrustPlugin = class extends BasePlugin {
32771
34184
  config;
@@ -32778,6 +34191,7 @@ var BraintrustPlugin = class extends BasePlugin {
32778
34191
  openAIAgentsPlugin = null;
32779
34192
  googleGenAIPlugin = null;
32780
34193
  huggingFacePlugin = null;
34194
+ huggingFaceTransformersPlugin = null;
32781
34195
  openRouterPlugin = null;
32782
34196
  openRouterAgentPlugin = null;
32783
34197
  mistralPlugin = null;
@@ -32792,6 +34206,8 @@ var BraintrustPlugin = class extends BasePlugin {
32792
34206
  langSmithPlugin = null;
32793
34207
  piCodingAgentPlugin = null;
32794
34208
  strandsAgentSDKPlugin = null;
34209
+ cloudflareAIChatPlugin = null;
34210
+ cloudflareAgentsPlugin = null;
32795
34211
  constructor(config = {}) {
32796
34212
  super();
32797
34213
  this.config = config;
@@ -32833,6 +34249,8 @@ var BraintrustPlugin = class extends BasePlugin {
32833
34249
  if (integrations.huggingface !== false) {
32834
34250
  this.huggingFacePlugin = new HuggingFacePlugin();
32835
34251
  this.huggingFacePlugin.enable();
34252
+ this.huggingFaceTransformersPlugin = new HuggingFaceTransformersPlugin();
34253
+ this.huggingFaceTransformersPlugin.enable();
32836
34254
  }
32837
34255
  if (integrations.openrouter !== false) {
32838
34256
  this.openRouterPlugin = new OpenRouterPlugin();
@@ -32878,6 +34296,14 @@ var BraintrustPlugin = class extends BasePlugin {
32878
34296
  this.strandsAgentSDKPlugin = new StrandsAgentSDKPlugin();
32879
34297
  this.strandsAgentSDKPlugin.enable();
32880
34298
  }
34299
+ if (integrations.cloudflareAIChat !== false) {
34300
+ this.cloudflareAIChatPlugin = new CloudflareAIChatPlugin();
34301
+ this.cloudflareAIChatPlugin.enable();
34302
+ }
34303
+ if (integrations.cloudflareAgents !== false) {
34304
+ this.cloudflareAgentsPlugin = new CloudflareAgentsPlugin();
34305
+ this.cloudflareAgentsPlugin.enable();
34306
+ }
32881
34307
  if (integrations.flue !== false) {
32882
34308
  this.fluePlugin = new FluePlugin();
32883
34309
  this.fluePlugin.enable();
@@ -32930,6 +34356,10 @@ var BraintrustPlugin = class extends BasePlugin {
32930
34356
  this.huggingFacePlugin.disable();
32931
34357
  this.huggingFacePlugin = null;
32932
34358
  }
34359
+ if (this.huggingFaceTransformersPlugin) {
34360
+ this.huggingFaceTransformersPlugin.disable();
34361
+ this.huggingFaceTransformersPlugin = null;
34362
+ }
32933
34363
  if (this.openRouterPlugin) {
32934
34364
  this.openRouterPlugin.disable();
32935
34365
  this.openRouterPlugin = null;
@@ -32974,6 +34404,14 @@ var BraintrustPlugin = class extends BasePlugin {
32974
34404
  this.strandsAgentSDKPlugin.disable();
32975
34405
  this.strandsAgentSDKPlugin = null;
32976
34406
  }
34407
+ if (this.cloudflareAIChatPlugin) {
34408
+ this.cloudflareAIChatPlugin.disable();
34409
+ this.cloudflareAIChatPlugin = null;
34410
+ }
34411
+ if (this.cloudflareAgentsPlugin) {
34412
+ this.cloudflareAgentsPlugin.disable();
34413
+ this.cloudflareAgentsPlugin = null;
34414
+ }
32977
34415
  if (this.fluePlugin) {
32978
34416
  this.fluePlugin.disable();
32979
34417
  this.fluePlugin = null;
@@ -33006,6 +34444,9 @@ var envIntegrationAliases = {
33006
34444
  strandsagentsdk: "strandsAgentSDK",
33007
34445
  "strands-agent-sdk": "strandsAgentSDK",
33008
34446
  "@strands-agents/sdk": "strandsAgentSDK",
34447
+ agents: "cloudflareAgents",
34448
+ "cloudflare-agents": "cloudflareAgents",
34449
+ cloudflareagents: "cloudflareAgents",
33009
34450
  anthropic: "anthropic",
33010
34451
  aisdk: "aisdk",
33011
34452
  "ai-sdk": "aisdk",
@@ -33013,6 +34454,9 @@ var envIntegrationAliases = {
33013
34454
  vercel: "vercel",
33014
34455
  claudeagentsdk: "claudeAgentSDK",
33015
34456
  "claude-agent-sdk": "claudeAgentSDK",
34457
+ cloudflareaichat: "cloudflareAIChat",
34458
+ "cloudflare-ai-chat": "cloudflareAIChat",
34459
+ "@cloudflare/ai-chat": "cloudflareAIChat",
33016
34460
  cursor: "cursor",
33017
34461
  "cursor-sdk": "cursorSDK",
33018
34462
  cursorsdk: "cursorSDK",
@@ -33027,6 +34471,8 @@ var envIntegrationAliases = {
33027
34471
  "google-genai": "googleGenAI",
33028
34472
  googlegenai: "googleGenAI",
33029
34473
  huggingface: "huggingface",
34474
+ "@huggingface/transformers": "huggingface",
34475
+ transformers: "huggingface",
33030
34476
  openrouter: "openrouter",
33031
34477
  openrouteragent: "openrouterAgent",
33032
34478
  "openrouter-agent": "openrouterAgent",
@@ -33065,6 +34511,7 @@ function getDefaultInstrumentationIntegrations() {
33065
34511
  googleADK: true,
33066
34512
  huggingface: true,
33067
34513
  claudeAgentSDK: true,
34514
+ cloudflareAIChat: true,
33068
34515
  cursor: true,
33069
34516
  cursorSDK: true,
33070
34517
  flue: true,
@@ -33084,7 +34531,8 @@ function getDefaultInstrumentationIntegrations() {
33084
34531
  langgraph: true,
33085
34532
  langsmith: true,
33086
34533
  piCodingAgent: true,
33087
- strandsAgentSDK: true
34534
+ strandsAgentSDK: true,
34535
+ cloudflareAgents: true
33088
34536
  };
33089
34537
  }
33090
34538
  function readDisabledInstrumentationEnvConfig(disabledList) {
@@ -33102,7 +34550,9 @@ function readDisabledInstrumentationEnvConfig(disabledList) {
33102
34550
  }
33103
34551
 
33104
34552
  // src/instrumentation/registry.ts
33105
- var REGISTRY_STATE_KEY = /* @__PURE__ */ Symbol.for("braintrust.registry");
34553
+ var REGISTRY_STATE_KEY = /* @__PURE__ */ Symbol.for(
34554
+ `braintrust.registry.global-hooks.v${GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION}`
34555
+ );
33106
34556
  function getSharedState() {
33107
34557
  const state = globalThis[/* @__PURE__ */ Symbol.for("braintrust-state")];
33108
34558
  return state && typeof state === "object" ? state : void 0;
@@ -33196,92 +34646,6 @@ function configureInstrumentation(config) {
33196
34646
  registry.configure(config);
33197
34647
  }
33198
34648
 
33199
- // src/auto-instrumentations/patch-tracing-channel.ts
33200
- function patchTracingChannel(tracingChannelFn) {
33201
- const dummyChannel = tracingChannelFn("__braintrust_probe__");
33202
- const TracingChannel = dummyChannel?.constructor;
33203
- if (!TracingChannel?.prototype) {
33204
- return;
33205
- }
33206
- if (!Object.getOwnPropertyDescriptor(TracingChannel.prototype, "hasSubscribers")) {
33207
- Object.defineProperty(TracingChannel.prototype, "hasSubscribers", {
33208
- configurable: true,
33209
- enumerable: false,
33210
- get() {
33211
- return Boolean(
33212
- this.start?.hasSubscribers || this.end?.hasSubscribers || this.asyncStart?.hasSubscribers || this.asyncEnd?.hasSubscribers || this.error?.hasSubscribers
33213
- );
33214
- }
33215
- });
33216
- }
33217
- if (TracingChannel.prototype.tracePromise) {
33218
- TracingChannel.prototype.tracePromise = function(fn, context = {}, thisArg, ...args) {
33219
- const start = this.start;
33220
- const end = this.end;
33221
- const asyncStart = this.asyncStart;
33222
- const asyncEnd = this.asyncEnd;
33223
- const error = this.error;
33224
- function publishRejected(err) {
33225
- context.error = err;
33226
- error?.publish(context);
33227
- asyncStart?.publish(context);
33228
- asyncEnd?.publish(context);
33229
- }
33230
- function publishResolved(result) {
33231
- context.result = result;
33232
- asyncStart?.publish(context);
33233
- asyncEnd?.publish(context);
33234
- }
33235
- return start.runStores(context, () => {
33236
- try {
33237
- const result = Reflect.apply(fn, thisArg, args);
33238
- end?.publish(context);
33239
- if (result && (typeof result === "object" || typeof result === "function") && typeof result.then === "function") {
33240
- if (result.constructor === Promise) {
33241
- return result.then(
33242
- (res) => {
33243
- publishResolved(res);
33244
- return res;
33245
- },
33246
- (err) => {
33247
- publishRejected(err);
33248
- return Promise.reject(err);
33249
- }
33250
- );
33251
- }
33252
- void result.then(
33253
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
33254
- (resolved) => {
33255
- try {
33256
- publishResolved(resolved);
33257
- } catch {
33258
- }
33259
- },
33260
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
33261
- (err) => {
33262
- try {
33263
- publishRejected(err);
33264
- } catch {
33265
- }
33266
- }
33267
- );
33268
- return result;
33269
- }
33270
- context.result = result;
33271
- asyncStart?.publish(context);
33272
- asyncEnd?.publish(context);
33273
- return result;
33274
- } catch (err) {
33275
- context.error = err;
33276
- error?.publish(context);
33277
- end?.publish(context);
33278
- throw err;
33279
- }
33280
- });
33281
- };
33282
- }
33283
- }
33284
-
33285
34649
  // src/browser/config.ts
33286
34650
  var browserConfigured = false;
33287
34651
  function configureBrowser() {
@@ -33295,8 +34659,6 @@ function configureBrowser() {
33295
34659
  }
33296
34660
  } catch {
33297
34661
  }
33298
- isomorph_default.newTracingChannel = (nameOrChannels) => tracingChannel(nameOrChannels);
33299
- patchTracingChannel(tracingChannel);
33300
34662
  isomorph_default.getEnv = (name) => {
33301
34663
  if (typeof process === "undefined" || typeof process.env === "undefined") {
33302
34664
  return void 0;
@@ -33471,6 +34833,8 @@ __export(exports_exports, {
33471
34833
  wrapAnthropic: () => wrapAnthropic,
33472
34834
  wrapBedrockRuntime: () => wrapBedrockRuntime,
33473
34835
  wrapClaudeAgentSDK: () => wrapClaudeAgentSDK,
34836
+ wrapCloudflareAIChat: () => wrapCloudflareAIChat,
34837
+ wrapCloudflareAgent: () => wrapCloudflareAgent,
33474
34838
  wrapCohere: () => wrapCohere,
33475
34839
  wrapCopilotClient: () => wrapCopilotClient,
33476
34840
  wrapCursorSDK: () => wrapCursorSDK,
@@ -33479,6 +34843,7 @@ __export(exports_exports, {
33479
34843
  wrapGoogleGenAI: () => wrapGoogleGenAI,
33480
34844
  wrapGroq: () => wrapGroq,
33481
34845
  wrapHuggingFace: () => wrapHuggingFace,
34846
+ wrapHuggingFaceTransformers: () => wrapHuggingFaceTransformers,
33482
34847
  wrapLangSmithClient: () => wrapLangSmithClient,
33483
34848
  wrapLangSmithRunTrees: () => wrapLangSmithRunTrees,
33484
34849
  wrapLangSmithTraceable: () => wrapLangSmithTraceable,
@@ -34802,7 +36167,7 @@ function extractToolCallsFromBlocks(blocks) {
34802
36167
  if (!Array.isArray(blocks)) return [];
34803
36168
  return extractToolCallsFromSteps([{ content: blocks }]);
34804
36169
  }
34805
- function extractInput(params) {
36170
+ function extractInput2(params) {
34806
36171
  return params?.prompt ?? params?.messages ?? params?.system;
34807
36172
  }
34808
36173
  var V2_EXCLUDE_KEYS = /* @__PURE__ */ new Set([
@@ -34824,7 +36189,7 @@ function BraintrustMiddleware(config = {}) {
34824
36189
  params,
34825
36190
  model: modelFromWrapGenerate
34826
36191
  }) => {
34827
- const rawInput = extractInput(params);
36192
+ const rawInput = extractInput2(params);
34828
36193
  const processedInput = processInputAttachments(rawInput);
34829
36194
  const spanArgs = {
34830
36195
  name: config.spanInfo?.name || "ai-sdk.doGenerate",
@@ -34888,7 +36253,7 @@ function BraintrustMiddleware(config = {}) {
34888
36253
  }
34889
36254
  },
34890
36255
  wrapStream: async ({ doStream, params }) => {
34891
- const rawInput = extractInput(params);
36256
+ const rawInput = extractInput2(params);
34892
36257
  const processedInput = processInputAttachments(rawInput);
34893
36258
  const spanArgs = {
34894
36259
  name: config.spanInfo?.name || "ai-sdk.doStream",
@@ -37410,6 +38775,67 @@ function patchAgentSessionClass(AgentSession) {
37410
38775
  });
37411
38776
  }
37412
38777
 
38778
+ // src/wrappers/cloudflare-agent.ts
38779
+ var WRAPPED_RUN_AGENT_TOOL = /* @__PURE__ */ Symbol.for(
38780
+ "braintrust.cloudflare-agents.wrapped-run-agent-tool"
38781
+ );
38782
+ function wrapCloudflareAgent(Agent2) {
38783
+ if (typeof Agent2 !== "function") {
38784
+ warnUnsupportedAgent();
38785
+ return Agent2;
38786
+ }
38787
+ const prototypeDescriptor = Object.getOwnPropertyDescriptor(
38788
+ Agent2,
38789
+ "prototype"
38790
+ );
38791
+ const prototype = prototypeDescriptor && "value" in prototypeDescriptor ? prototypeDescriptor.value : void 0;
38792
+ if (!isObjectLike3(prototype)) {
38793
+ warnUnsupportedAgent();
38794
+ return Agent2;
38795
+ }
38796
+ if (ownValue4(prototype, WRAPPED_RUN_AGENT_TOOL) === true) {
38797
+ return Agent2;
38798
+ }
38799
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, "runAgentTool");
38800
+ if (!descriptor || typeof descriptor.value !== "function") {
38801
+ warnUnsupportedAgent();
38802
+ return Agent2;
38803
+ }
38804
+ const originalRunAgentTool = descriptor.value;
38805
+ Object.defineProperty(prototype, "runAgentTool", {
38806
+ ...descriptor,
38807
+ value: function wrappedRunAgentTool(...args) {
38808
+ const options = args[1];
38809
+ if (ownValue4(options, "detached")) {
38810
+ return Reflect.apply(originalRunAgentTool, this, args);
38811
+ }
38812
+ return cloudflareAgentsChannels.runAgentTool.tracePromise(
38813
+ () => Reflect.apply(originalRunAgentTool, this, args),
38814
+ { arguments: args, self: this }
38815
+ );
38816
+ }
38817
+ });
38818
+ Object.defineProperty(prototype, WRAPPED_RUN_AGENT_TOOL, {
38819
+ configurable: false,
38820
+ enumerable: false,
38821
+ value: true
38822
+ });
38823
+ return Agent2;
38824
+ }
38825
+ function ownValue4(value, key) {
38826
+ if (!isObjectLike3(value)) {
38827
+ return void 0;
38828
+ }
38829
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
38830
+ return descriptor && "value" in descriptor ? descriptor.value : void 0;
38831
+ }
38832
+ function isObjectLike3(value) {
38833
+ return typeof value === "object" && value !== null || typeof value === "function";
38834
+ }
38835
+ function warnUnsupportedAgent() {
38836
+ debugLogger.warn("Unsupported Cloudflare Agents Agent class. Not wrapping.");
38837
+ }
38838
+
37413
38839
  // src/wrappers/strands-agent-sdk.ts
37414
38840
  var WRAPPED_CLASS = /* @__PURE__ */ Symbol.for("braintrust.strands-agent-sdk.wrapped-class");
37415
38841
  var WRAPPED_INSTANCE = /* @__PURE__ */ Symbol.for(
@@ -37578,6 +39004,81 @@ async function consumeAsyncGenerator(generator) {
37578
39004
  return result.value;
37579
39005
  }
37580
39006
 
39007
+ // src/wrappers/cloudflare-ai-chat.ts
39008
+ var wrappedClasses = /* @__PURE__ */ new WeakMap();
39009
+ function wrapCloudflareAIChat(module) {
39010
+ if (!module || typeof module !== "object") {
39011
+ return module;
39012
+ }
39013
+ const candidate = module;
39014
+ let AIChatAgent;
39015
+ try {
39016
+ AIChatAgent = Reflect.get(candidate, "AIChatAgent");
39017
+ } catch (error) {
39018
+ debugLogger.debug("Failed to inspect @cloudflare/ai-chat module:", error);
39019
+ return module;
39020
+ }
39021
+ if (typeof AIChatAgent !== "function") {
39022
+ debugLogger.warn(
39023
+ "Unsupported @cloudflare/ai-chat module. AIChatAgent was not found; not wrapping."
39024
+ );
39025
+ return module;
39026
+ }
39027
+ const target = isModuleNamespace5(module) ? Object.setPrototypeOf({}, module) : candidate;
39028
+ return new Proxy(target, {
39029
+ get(target2, property, receiver) {
39030
+ const value = Reflect.get(target2, property, receiver);
39031
+ if (property === "AIChatAgent" && typeof value === "function") {
39032
+ return wrapAIChatAgentClass(
39033
+ value
39034
+ );
39035
+ }
39036
+ return value;
39037
+ }
39038
+ });
39039
+ }
39040
+ function wrapAIChatAgentClass(AgentClass) {
39041
+ const cached = wrappedClasses.get(AgentClass);
39042
+ if (cached) {
39043
+ return cached;
39044
+ }
39045
+ const wrapped = new Proxy(AgentClass, {
39046
+ get(target, property) {
39047
+ const value = Reflect.get(target, property, target);
39048
+ return typeof value === "function" ? value.bind(target) : value;
39049
+ },
39050
+ construct(target, args, newTarget) {
39051
+ const instance = Reflect.construct(
39052
+ target,
39053
+ args,
39054
+ newTarget
39055
+ );
39056
+ return instrumentCloudflareAIChatAgent(instance);
39057
+ }
39058
+ });
39059
+ wrappedClasses.set(AgentClass, wrapped);
39060
+ wrappedClasses.set(wrapped, wrapped);
39061
+ return wrapped;
39062
+ }
39063
+ function isModuleNamespace5(value) {
39064
+ if (!value || typeof value !== "object") {
39065
+ return false;
39066
+ }
39067
+ try {
39068
+ if (Reflect.get(value, Symbol.toStringTag) === "Module") {
39069
+ return true;
39070
+ }
39071
+ const keys = Object.keys(value);
39072
+ if (keys.length === 0) {
39073
+ return false;
39074
+ }
39075
+ const descriptor = Object.getOwnPropertyDescriptor(value, keys[0]);
39076
+ return descriptor ? !descriptor.configurable && !descriptor.writable : false;
39077
+ } catch {
39078
+ return false;
39079
+ }
39080
+ }
39081
+
37581
39082
  // src/wrappers/google-genai.ts
37582
39083
  function wrapGoogleGenAI(googleGenAI) {
37583
39084
  if (!googleGenAI || typeof googleGenAI !== "object") {
@@ -38230,6 +39731,120 @@ function wrapFeatureExtraction(original, endpointUrl) {
38230
39731
  };
38231
39732
  }
38232
39733
 
39734
+ // src/wrappers/huggingface-transformers.ts
39735
+ var PIPELINE_CONSTRUCTOR_KEYS = /* @__PURE__ */ new Set([
39736
+ "TextGenerationPipeline",
39737
+ "Text2TextGenerationPipeline",
39738
+ "SummarizationPipeline",
39739
+ "FeatureExtractionPipeline",
39740
+ "QuestionAnsweringPipeline"
39741
+ ]);
39742
+ var wrappedValues = /* @__PURE__ */ new WeakMap();
39743
+ function wrapHuggingFaceTransformers(transformers) {
39744
+ const pipelineTask = transformers?.task;
39745
+ if (typeof transformers === "function" && isSupportedHuggingFaceTransformersTask(pipelineTask)) {
39746
+ return wrapPipeline(transformers);
39747
+ }
39748
+ if (!isSupportedModule(transformers)) {
39749
+ return transformers;
39750
+ }
39751
+ const existing = wrappedValues.get(transformers);
39752
+ if (existing) {
39753
+ return existing;
39754
+ }
39755
+ const proxy = new Proxy(Object.create(transformers), {
39756
+ get(_target, property, receiver) {
39757
+ const value = Reflect.get(transformers, property, receiver);
39758
+ if (property === "pipeline" && typeof value === "function") {
39759
+ return wrapPipelineFactory(value);
39760
+ }
39761
+ if (typeof property === "string" && PIPELINE_CONSTRUCTOR_KEYS.has(property) && typeof value === "function") {
39762
+ return wrapPipelineConstructor(
39763
+ value
39764
+ );
39765
+ }
39766
+ return value;
39767
+ }
39768
+ });
39769
+ wrappedValues.set(transformers, proxy);
39770
+ wrappedValues.set(proxy, proxy);
39771
+ return proxy;
39772
+ }
39773
+ function isSupportedModule(value) {
39774
+ if (value === null || typeof value !== "object" && typeof value !== "function") {
39775
+ return false;
39776
+ }
39777
+ if (typeof Reflect.get(value, "pipeline") === "function") {
39778
+ return true;
39779
+ }
39780
+ for (const key of PIPELINE_CONSTRUCTOR_KEYS) {
39781
+ if (typeof Reflect.get(value, key) === "function") {
39782
+ return true;
39783
+ }
39784
+ }
39785
+ return false;
39786
+ }
39787
+ function wrapPipelineFactory(factory) {
39788
+ const existing = wrappedValues.get(factory);
39789
+ if (existing) {
39790
+ return existing;
39791
+ }
39792
+ const wrapped = function(...args) {
39793
+ const [task] = args;
39794
+ const context = {
39795
+ arguments: args
39796
+ };
39797
+ return huggingFaceTransformersChannels.pipeline.tracePromise(() => Reflect.apply(factory, this, args), context).then((pipeline) => {
39798
+ if (isSupportedHuggingFaceTransformersTask(pipeline.task ?? task)) {
39799
+ return wrapPipeline(pipeline);
39800
+ }
39801
+ return pipeline;
39802
+ });
39803
+ };
39804
+ wrappedValues.set(factory, wrapped);
39805
+ wrappedValues.set(wrapped, wrapped);
39806
+ return wrapped;
39807
+ }
39808
+ function wrapPipelineConstructor(constructor) {
39809
+ const existing = wrappedValues.get(constructor);
39810
+ if (existing) {
39811
+ return existing;
39812
+ }
39813
+ const proxy = new Proxy(constructor, {
39814
+ construct(target, args, newTarget) {
39815
+ const pipeline = Reflect.construct(target, args, newTarget);
39816
+ if (isSupportedHuggingFaceTransformersTask(pipeline.task)) {
39817
+ return wrapPipeline(pipeline);
39818
+ }
39819
+ return pipeline;
39820
+ }
39821
+ });
39822
+ wrappedValues.set(constructor, proxy);
39823
+ wrappedValues.set(proxy, proxy);
39824
+ return proxy;
39825
+ }
39826
+ function wrapPipeline(pipeline) {
39827
+ const existing = wrappedValues.get(pipeline);
39828
+ if (existing) {
39829
+ return existing;
39830
+ }
39831
+ const proxy = new Proxy(pipeline, {
39832
+ apply(target, thisArg, args) {
39833
+ const context = {
39834
+ arguments: args,
39835
+ self: target
39836
+ };
39837
+ return huggingFaceTransformersChannels.pipelineCall.tracePromise(
39838
+ () => Reflect.apply(target, thisArg, args),
39839
+ context
39840
+ );
39841
+ }
39842
+ });
39843
+ wrappedValues.set(pipeline, proxy);
39844
+ wrappedValues.set(proxy, proxy);
39845
+ return proxy;
39846
+ }
39847
+
38233
39848
  // src/wrappers/openrouter-agent.ts
38234
39849
  function wrapOpenRouterAgent(agent) {
38235
39850
  const candidate = agent;
@@ -38946,7 +40561,7 @@ function wrapNamespaceExport(namespace, exportName, marker, wrap2) {
38946
40561
  );
38947
40562
  return namespace;
38948
40563
  }
38949
- const target = isModuleNamespace5(namespace) ? Object.setPrototypeOf({}, namespace) : candidate;
40564
+ const target = isModuleNamespace6(namespace) ? Object.setPrototypeOf({}, namespace) : candidate;
38950
40565
  const moduleNamespace = target !== candidate;
38951
40566
  let wrappedExport;
38952
40567
  return new Proxy(target, {
@@ -38980,7 +40595,7 @@ function wrapNamespaceExport(namespace, exportName, marker, wrap2) {
38980
40595
  }
38981
40596
  });
38982
40597
  }
38983
- function isModuleNamespace5(value) {
40598
+ function isModuleNamespace6(value) {
38984
40599
  if (!value || typeof value !== "object") {
38985
40600
  return false;
38986
40601
  }
@@ -43618,6 +45233,8 @@ export {
43618
45233
  wrapAnthropic,
43619
45234
  wrapBedrockRuntime,
43620
45235
  wrapClaudeAgentSDK,
45236
+ wrapCloudflareAIChat,
45237
+ wrapCloudflareAgent,
43621
45238
  wrapCohere,
43622
45239
  wrapCopilotClient,
43623
45240
  wrapCursorSDK,
@@ -43626,6 +45243,7 @@ export {
43626
45243
  wrapGoogleGenAI,
43627
45244
  wrapGroq,
43628
45245
  wrapHuggingFace,
45246
+ wrapHuggingFaceTransformers,
43629
45247
  wrapLangSmithClient,
43630
45248
  wrapLangSmithRunTrees,
43631
45249
  wrapLangSmithTraceable,