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.js CHANGED
@@ -177,6 +177,8 @@ __export(browser_exports, {
177
177
  wrapAnthropic: () => wrapAnthropic,
178
178
  wrapBedrockRuntime: () => wrapBedrockRuntime,
179
179
  wrapClaudeAgentSDK: () => wrapClaudeAgentSDK,
180
+ wrapCloudflareAIChat: () => wrapCloudflareAIChat,
181
+ wrapCloudflareAgent: () => wrapCloudflareAgent,
180
182
  wrapCohere: () => wrapCohere,
181
183
  wrapCopilotClient: () => wrapCopilotClient,
182
184
  wrapCursorSDK: () => wrapCursorSDK,
@@ -185,6 +187,7 @@ __export(browser_exports, {
185
187
  wrapGoogleGenAI: () => wrapGoogleGenAI,
186
188
  wrapGroq: () => wrapGroq,
187
189
  wrapHuggingFace: () => wrapHuggingFace,
190
+ wrapHuggingFaceTransformers: () => wrapHuggingFaceTransformers,
188
191
  wrapLangSmithClient: () => wrapLangSmithClient,
189
192
  wrapLangSmithRunTrees: () => wrapLangSmithRunTrees,
190
193
  wrapLangSmithTraceable: () => wrapLangSmithTraceable,
@@ -202,87 +205,528 @@ __export(browser_exports, {
202
205
  });
203
206
  module.exports = __toCommonJS(browser_exports);
204
207
 
205
- // src/browser/config.ts
206
- var import_dc_browser = require("dc-browser");
207
-
208
- // src/isomorph.ts
209
- var DefaultAsyncLocalStorage = class {
210
- constructor() {
211
- }
212
- enterWith(_) {
213
- }
214
- run(_, callback) {
215
- return callback();
208
+ // src/global-instrumentation-hooks.ts
209
+ var GLOBAL_INSTRUMENTATION_HOOKS_KEY = "__braintrust_instrumentation_hooks";
210
+ var GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION = 1;
211
+ var GLOBAL_INSTRUMENTATION_HOOKS_REGISTRY_BRAND = "braintrust.global-instrumentation-hooks.registry";
212
+ var GLOBAL_INSTRUMENTATION_HOOK_BRAND = "braintrust.global-instrumentation-hooks.hook";
213
+ var registryBrand = Symbol.for(GLOBAL_INSTRUMENTATION_HOOKS_REGISTRY_BRAND);
214
+ var hookBrand = Symbol.for(GLOBAL_INSTRUMENTATION_HOOK_BRAND);
215
+ var errorReporter;
216
+ function setGlobalHookErrorReporter(reporter) {
217
+ const previousReporter = errorReporter;
218
+ errorReporter = reporter;
219
+ return () => {
220
+ if (errorReporter === reporter) {
221
+ errorReporter = previousReporter;
222
+ }
223
+ };
224
+ }
225
+ function reportError(error) {
226
+ try {
227
+ errorReporter?.(error);
228
+ } catch {
216
229
  }
217
- getStore() {
218
- return void 0;
230
+ }
231
+ function setContextValue(context, key, value) {
232
+ try {
233
+ context[key] = value;
234
+ } catch (error) {
235
+ reportError(error);
219
236
  }
220
- };
221
- var DefaultChannel = class {
237
+ }
238
+ function wrapStoreRun(store, message, next, transform) {
239
+ return () => {
240
+ let context;
241
+ try {
242
+ context = transform ? transform(message) : message;
243
+ } catch (error) {
244
+ reportError(error);
245
+ return next();
246
+ }
247
+ let called = false;
248
+ let result;
249
+ let providerError;
250
+ let providerThrew = false;
251
+ const runNext = () => {
252
+ if (called) {
253
+ reportError(
254
+ new Error(
255
+ "Instrumentation store invoked its callback more than once"
256
+ )
257
+ );
258
+ if (providerThrew) {
259
+ throw providerError;
260
+ }
261
+ return result;
262
+ }
263
+ called = true;
264
+ try {
265
+ result = next();
266
+ return result;
267
+ } catch (error) {
268
+ providerThrew = true;
269
+ providerError = error;
270
+ throw error;
271
+ }
272
+ };
273
+ try {
274
+ store.run(context, runNext);
275
+ } catch (error) {
276
+ if (!providerThrew || error !== providerError) {
277
+ reportError(error);
278
+ }
279
+ }
280
+ if (!called) {
281
+ reportError(
282
+ new Error("Instrumentation store did not invoke its callback")
283
+ );
284
+ return runNext();
285
+ }
286
+ if (providerThrew) {
287
+ throw providerError;
288
+ }
289
+ return result;
290
+ };
291
+ }
292
+ var HookChannel = class {
222
293
  constructor(name) {
223
294
  this.name = name;
224
295
  }
225
296
  name;
226
- hasSubscribers = false;
227
- subscribe(_subscription) {
297
+ subscribers = [];
298
+ stores = /* @__PURE__ */ new Map();
299
+ get hasSubscribers() {
300
+ return this.subscribers.length > 0 || this.stores.size > 0;
228
301
  }
229
- unsubscribe(_subscription) {
230
- return false;
302
+ subscribe(subscription) {
303
+ if (typeof subscription !== "function") {
304
+ throw new TypeError("subscription must be a function");
305
+ }
306
+ this.subscribers = [...this.subscribers, subscription];
231
307
  }
232
- bindStore(_store, _transform) {
308
+ unsubscribe(subscription) {
309
+ const index = this.subscribers.indexOf(subscription);
310
+ if (index === -1) {
311
+ return false;
312
+ }
313
+ this.subscribers = [
314
+ ...this.subscribers.slice(0, index),
315
+ ...this.subscribers.slice(index + 1)
316
+ ];
317
+ return true;
233
318
  }
234
- unbindStore(_store) {
235
- return false;
319
+ bindStore(store, transform) {
320
+ if (!store || typeof store.run !== "function") {
321
+ throw new TypeError("store must have a run method");
322
+ }
323
+ this.stores.set(
324
+ store,
325
+ transform
326
+ );
236
327
  }
237
- publish(_message) {
328
+ unbindStore(store) {
329
+ return this.stores.delete(store);
238
330
  }
239
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
240
- runStores(_message, fn, thisArg, ...args) {
241
- return fn.apply(thisArg, args);
331
+ publish(message) {
332
+ const subscribers = this.subscribers;
333
+ for (const subscriber of subscribers) {
334
+ try {
335
+ subscriber(message, this.name);
336
+ } catch (error) {
337
+ reportError(error);
338
+ }
339
+ }
340
+ }
341
+ runStores(message, fn, thisArg, ...args) {
342
+ let run = () => {
343
+ this.publish(message);
344
+ return Reflect.apply(fn, thisArg, args);
345
+ };
346
+ for (const [store, transform] of this.stores.entries()) {
347
+ run = wrapStoreRun(store, message, run, transform);
348
+ }
349
+ return run();
242
350
  }
243
351
  };
244
- var DefaultTracingChannel = class {
352
+ var traceEvents = [
353
+ "start",
354
+ "end",
355
+ "asyncStart",
356
+ "asyncEnd",
357
+ "error"
358
+ ];
359
+ var TracingHook = class {
245
360
  start;
246
361
  end;
247
362
  asyncStart;
248
363
  asyncEnd;
249
364
  error;
250
365
  constructor(nameOrChannels) {
366
+ Object.defineProperty(this, hookBrand, {
367
+ configurable: false,
368
+ enumerable: false,
369
+ value: GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION,
370
+ writable: false
371
+ });
251
372
  if (typeof nameOrChannels === "string") {
252
- this.start = new DefaultChannel(`tracing:${nameOrChannels}:start`);
253
- this.end = new DefaultChannel(`tracing:${nameOrChannels}:end`);
254
- this.asyncStart = new DefaultChannel(
255
- `tracing:${nameOrChannels}:asyncStart`
256
- );
257
- this.asyncEnd = new DefaultChannel(`tracing:${nameOrChannels}:asyncEnd`);
258
- this.error = new DefaultChannel(`tracing:${nameOrChannels}:error`);
373
+ this.start = new HookChannel(`tracing:${nameOrChannels}:start`);
374
+ this.end = new HookChannel(`tracing:${nameOrChannels}:end`);
375
+ this.asyncStart = new HookChannel(`tracing:${nameOrChannels}:asyncStart`);
376
+ this.asyncEnd = new HookChannel(`tracing:${nameOrChannels}:asyncEnd`);
377
+ this.error = new HookChannel(`tracing:${nameOrChannels}:error`);
259
378
  return;
260
379
  }
261
- this.start = nameOrChannels.start ?? new DefaultChannel("tracing:start");
262
- this.end = nameOrChannels.end ?? new DefaultChannel("tracing:end");
263
- this.asyncStart = nameOrChannels.asyncStart ?? new DefaultChannel("tracing:asyncStart");
264
- this.asyncEnd = nameOrChannels.asyncEnd ?? new DefaultChannel("tracing:asyncEnd");
265
- this.error = nameOrChannels.error ?? new DefaultChannel("tracing:error");
380
+ this.start = nameOrChannels.start ?? new HookChannel("tracing:start");
381
+ this.end = nameOrChannels.end ?? new HookChannel("tracing:end");
382
+ this.asyncStart = nameOrChannels.asyncStart ?? new HookChannel("tracing:asyncStart");
383
+ this.asyncEnd = nameOrChannels.asyncEnd ?? new HookChannel("tracing:asyncEnd");
384
+ this.error = nameOrChannels.error ?? new HookChannel("tracing:error");
266
385
  }
267
386
  get hasSubscribers() {
268
387
  return this.start.hasSubscribers || this.end.hasSubscribers || this.asyncStart.hasSubscribers || this.asyncEnd.hasSubscribers || this.error.hasSubscribers;
269
388
  }
270
- subscribe(_handlers) {
389
+ subscribe(handlers) {
390
+ for (const eventName of traceEvents) {
391
+ const handler = handlers[eventName];
392
+ if (handler) {
393
+ this[eventName].subscribe(handler);
394
+ }
395
+ }
396
+ }
397
+ unsubscribe(handlers) {
398
+ let done = true;
399
+ for (const eventName of traceEvents) {
400
+ const handler = handlers[eventName];
401
+ if (handler && !this[eventName].unsubscribe(handler)) {
402
+ done = false;
403
+ }
404
+ }
405
+ return done;
271
406
  }
272
- unsubscribe(_handlers) {
407
+ traceSync(fn, message = {}, thisArg, ...args) {
408
+ if (!this.hasSubscribers) {
409
+ return Reflect.apply(fn, thisArg, args);
410
+ }
411
+ const context = message;
412
+ return this.start.runStores(message, () => {
413
+ try {
414
+ const result = Reflect.apply(fn, thisArg, args);
415
+ setContextValue(context, "result", result);
416
+ return result;
417
+ } catch (error) {
418
+ setContextValue(context, "error", error);
419
+ this.error.publish(message);
420
+ throw error;
421
+ } finally {
422
+ this.end.publish(message);
423
+ }
424
+ });
425
+ }
426
+ tracePromise(fn, message = {}, thisArg, ...args) {
427
+ if (!this.hasSubscribers) {
428
+ return Reflect.apply(fn, thisArg, args);
429
+ }
430
+ const context = message;
431
+ return this.start.runStores(message, () => {
432
+ let result;
433
+ try {
434
+ result = Reflect.apply(fn, thisArg, args);
435
+ } catch (error) {
436
+ setContextValue(context, "error", error);
437
+ this.error.publish(message);
438
+ this.end.publish(message);
439
+ throw error;
440
+ }
441
+ this.end.publish(message);
442
+ if (!result || typeof result !== "object" && typeof result !== "function") {
443
+ setContextValue(context, "result", result);
444
+ this.asyncStart.publish(message);
445
+ this.asyncEnd.publish(message);
446
+ return result;
447
+ }
448
+ let terminalPublished = false;
449
+ const finishUnobservedResult = (error) => {
450
+ reportError(error);
451
+ if (!terminalPublished) {
452
+ terminalPublished = true;
453
+ setContextValue(context, "result", result);
454
+ this.asyncStart.publish(message);
455
+ this.asyncEnd.publish(message);
456
+ }
457
+ return result;
458
+ };
459
+ let then;
460
+ try {
461
+ then = result.then;
462
+ } catch (error) {
463
+ return finishUnobservedResult(error);
464
+ }
465
+ if (typeof then !== "function") {
466
+ setContextValue(context, "result", result);
467
+ this.asyncStart.publish(message);
468
+ this.asyncEnd.publish(message);
469
+ return result;
470
+ }
471
+ const resolve = (resolved) => {
472
+ if (!terminalPublished) {
473
+ terminalPublished = true;
474
+ setContextValue(context, "result", resolved);
475
+ this.asyncStart.publish(message);
476
+ this.asyncEnd.publish(message);
477
+ }
478
+ return resolved;
479
+ };
480
+ let rejectionThrown = false;
481
+ let rejectionError;
482
+ const reject2 = (error) => {
483
+ if (!terminalPublished) {
484
+ terminalPublished = true;
485
+ setContextValue(context, "error", error);
486
+ this.error.publish(message);
487
+ this.asyncStart.publish(message);
488
+ this.asyncEnd.publish(message);
489
+ }
490
+ rejectionThrown = true;
491
+ rejectionError = error;
492
+ throw error;
493
+ };
494
+ let isPlainPromise;
495
+ try {
496
+ isPlainPromise = result instanceof Promise && result.constructor === Promise;
497
+ } catch (error) {
498
+ return finishUnobservedResult(error);
499
+ }
500
+ try {
501
+ if (isPlainPromise) {
502
+ return Reflect.apply(then, result, [resolve, reject2]);
503
+ }
504
+ Reflect.apply(then, result, [
505
+ resolve,
506
+ (error) => {
507
+ try {
508
+ reject2(error);
509
+ } catch {
510
+ }
511
+ }
512
+ ]);
513
+ } catch (error) {
514
+ if (rejectionThrown && error === rejectionError) {
515
+ return result;
516
+ }
517
+ return finishUnobservedResult(error);
518
+ }
519
+ return result;
520
+ });
521
+ }
522
+ traceCallback(fn, position = -1, message = {}, thisArg, ...args) {
523
+ if (!this.hasSubscribers) {
524
+ return Reflect.apply(fn, thisArg, args);
525
+ }
526
+ const context = message;
527
+ const callArgs = args.length > 0 ? args : context.arguments ?? args;
528
+ const callback = Array.prototype.at.call(callArgs, position);
529
+ if (typeof callback !== "function") {
530
+ return Reflect.apply(fn, thisArg, args);
531
+ }
532
+ const { asyncStart, asyncEnd, error: errorChannel } = this;
533
+ function wrappedCallback(error, result) {
534
+ if (error) {
535
+ setContextValue(context, "error", error);
536
+ errorChannel.publish(message);
537
+ } else {
538
+ setContextValue(context, "result", result);
539
+ }
540
+ return asyncStart.runStores(message, () => {
541
+ try {
542
+ return Reflect.apply(callback, this, arguments);
543
+ } finally {
544
+ asyncEnd.publish(message);
545
+ }
546
+ });
547
+ }
548
+ Array.prototype.splice.call(callArgs, position, 1, wrappedCallback);
549
+ return this.start.runStores(message, () => {
550
+ try {
551
+ return Reflect.apply(fn, thisArg, args);
552
+ } catch (error) {
553
+ setContextValue(context, "error", error);
554
+ this.error.publish(message);
555
+ throw error;
556
+ } finally {
557
+ this.end.publish(message);
558
+ }
559
+ });
560
+ }
561
+ };
562
+ var inertChannel = Object.freeze({
563
+ name: "braintrust:inert",
564
+ hasSubscribers: false,
565
+ subscribe() {
566
+ },
567
+ unsubscribe() {
273
568
  return false;
569
+ },
570
+ bindStore() {
571
+ },
572
+ unbindStore() {
573
+ return false;
574
+ },
575
+ publish() {
576
+ },
577
+ runStores(_message, fn, thisArg, ...args) {
578
+ return Reflect.apply(fn, thisArg, args);
274
579
  }
275
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
276
- traceSync(fn, _message, thisArg, ...args) {
277
- return fn.apply(thisArg, args);
580
+ });
581
+ var inertTracingHook = new TracingHook({
582
+ start: inertChannel,
583
+ end: inertChannel,
584
+ asyncStart: inertChannel,
585
+ asyncEnd: inertChannel,
586
+ error: inertChannel
587
+ });
588
+ function isHookChannel(value) {
589
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
590
+ return false;
278
591
  }
279
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
280
- tracePromise(fn, _message, thisArg, ...args) {
281
- return fn.apply(thisArg, args);
592
+ try {
593
+ const channel2 = value;
594
+ 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";
595
+ } catch {
596
+ return false;
282
597
  }
283
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
284
- traceCallback(fn, _position, _message, thisArg, ...args) {
285
- return fn.apply(thisArg, args);
598
+ }
599
+ function hasTracingHookShape(value) {
600
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
601
+ return false;
602
+ }
603
+ try {
604
+ const hook = value;
605
+ 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);
606
+ } catch {
607
+ return false;
608
+ }
609
+ }
610
+ function isCompatibleTracingHook(value) {
611
+ try {
612
+ return value[hookBrand] === GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION && hasTracingHookShape(value);
613
+ } catch {
614
+ return false;
615
+ }
616
+ }
617
+ function isCompatibleHookRegistry(value) {
618
+ try {
619
+ return value instanceof Map && value[registryBrand] === GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION;
620
+ } catch {
621
+ return false;
622
+ }
623
+ }
624
+ function getHookRegistry() {
625
+ let descriptor;
626
+ try {
627
+ descriptor = Object.getOwnPropertyDescriptor(
628
+ globalThis,
629
+ GLOBAL_INSTRUMENTATION_HOOKS_KEY
630
+ );
631
+ } catch (error) {
632
+ reportError(error);
633
+ return void 0;
634
+ }
635
+ if (descriptor && "value" in descriptor && isCompatibleHookRegistry(descriptor.value) && (descriptor.configurable || descriptor.enumerable === false)) {
636
+ if (descriptor.configurable || descriptor.writable) {
637
+ try {
638
+ Object.defineProperty(globalThis, GLOBAL_INSTRUMENTATION_HOOKS_KEY, {
639
+ configurable: false,
640
+ enumerable: false,
641
+ value: descriptor.value,
642
+ writable: false
643
+ });
644
+ } catch (error) {
645
+ reportError(error);
646
+ return void 0;
647
+ }
648
+ }
649
+ return descriptor.value;
650
+ }
651
+ if (descriptor && !descriptor.configurable) {
652
+ reportError(new Error("Incompatible global instrumentation hook registry"));
653
+ return void 0;
654
+ }
655
+ const registry2 = /* @__PURE__ */ new Map();
656
+ try {
657
+ Object.defineProperty(registry2, registryBrand, {
658
+ configurable: false,
659
+ enumerable: false,
660
+ value: GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION,
661
+ writable: false
662
+ });
663
+ } catch (error) {
664
+ reportError(error);
665
+ return void 0;
666
+ }
667
+ try {
668
+ Object.defineProperty(globalThis, GLOBAL_INSTRUMENTATION_HOOKS_KEY, {
669
+ configurable: false,
670
+ enumerable: false,
671
+ value: registry2,
672
+ writable: false
673
+ });
674
+ return registry2;
675
+ } catch (error) {
676
+ reportError(error);
677
+ return void 0;
678
+ }
679
+ }
680
+ function newGlobalTracingChannel(nameOrChannels) {
681
+ if (typeof nameOrChannels !== "string") {
682
+ return new TracingHook(nameOrChannels);
683
+ }
684
+ const registry2 = getHookRegistry();
685
+ if (!registry2) {
686
+ return inertTracingHook;
687
+ }
688
+ let existing;
689
+ try {
690
+ existing = Map.prototype.get.call(registry2, nameOrChannels);
691
+ } catch (error) {
692
+ reportError(error);
693
+ return inertTracingHook;
694
+ }
695
+ if (isCompatibleTracingHook(existing)) {
696
+ return existing;
697
+ }
698
+ if (existing !== void 0) {
699
+ reportError(
700
+ new Error(`Invalid global instrumentation hook: ${nameOrChannels}`)
701
+ );
702
+ try {
703
+ Map.prototype.delete.call(registry2, nameOrChannels);
704
+ } catch (error) {
705
+ reportError(error);
706
+ return inertTracingHook;
707
+ }
708
+ }
709
+ const hook = new TracingHook(nameOrChannels);
710
+ try {
711
+ Map.prototype.set.call(registry2, nameOrChannels, hook);
712
+ } catch (error) {
713
+ reportError(error);
714
+ return inertTracingHook;
715
+ }
716
+ return hook;
717
+ }
718
+
719
+ // src/isomorph.ts
720
+ var DefaultAsyncLocalStorage = class {
721
+ constructor() {
722
+ }
723
+ enterWith(_) {
724
+ }
725
+ run(_, callback) {
726
+ return callback();
727
+ }
728
+ getStore() {
729
+ return void 0;
286
730
  }
287
731
  };
288
732
  var iso = {
@@ -295,7 +739,7 @@ var iso = {
295
739
  getCallerLocation: () => void 0,
296
740
  newAsyncLocalStorage: () => new DefaultAsyncLocalStorage(),
297
741
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
298
- newTracingChannel: (nameOrChannels) => new DefaultTracingChannel(nameOrChannels),
742
+ newTracingChannel: (nameOrChannels) => newGlobalTracingChannel(nameOrChannels),
299
743
  processOn: (_0, _1) => {
300
744
  },
301
745
  basename: (filepath) => filepath.split(/[\\/]/).pop() || filepath,
@@ -415,6 +859,9 @@ var debugLogger = {
415
859
  return createDebugLogger(state);
416
860
  }
417
861
  };
862
+ setGlobalHookErrorReporter((error) => {
863
+ debugLogger.error("Global instrumentation hook error:", error);
864
+ });
418
865
 
419
866
  // src/queue.ts
420
867
  var DEFAULT_QUEUE_SIZE = 15e3;
@@ -2199,7 +2646,8 @@ var ApiKey = import_v36.z.object({
2199
2646
  user_email: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
2200
2647
  user_given_name: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
2201
2648
  user_family_name: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
2202
- org_id: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional()
2649
+ org_id: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
2650
+ expires_at: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional()
2203
2651
  });
2204
2652
  var TriggeredFunctionState = import_v36.z.object({
2205
2653
  triggered_xact_id: import_v36.z.string(),
@@ -2319,6 +2767,7 @@ var TopicMapData = import_v36.z.object({
2319
2767
  topic_names: import_v36.z.record(import_v36.z.string()).optional(),
2320
2768
  generation_settings: TopicMapGenerationSettings.optional(),
2321
2769
  disable_reconciliation: import_v36.z.boolean().optional(),
2770
+ reconcile_mode: import_v36.z.enum(["evolve", "names_only"]).optional(),
2322
2771
  distance_threshold: import_v36.z.number().optional(),
2323
2772
  btql_filter: import_v36.z.string().optional(),
2324
2773
  automation_btql_filter: import_v36.z.string().optional()
@@ -2899,7 +3348,12 @@ var ModelParams = import_v36.z.union([
2899
3348
  }).partial().passthrough()
2900
3349
  ]);
2901
3350
  var PromptOptionsNullish = import_v36.z.union([
2902
- import_v36.z.object({ model: import_v36.z.string(), params: ModelParams, position: import_v36.z.string() }).partial(),
3351
+ import_v36.z.object({
3352
+ model: import_v36.z.string(),
3353
+ params: ModelParams,
3354
+ position: import_v36.z.string(),
3355
+ endpoint_name: import_v36.z.union([import_v36.z.string(), import_v36.z.null()])
3356
+ }).partial(),
2903
3357
  import_v36.z.null()
2904
3358
  ]);
2905
3359
  var PromptParserNullish = import_v36.z.union([
@@ -2913,11 +3367,25 @@ var PromptParserNullish = import_v36.z.union([
2913
3367
  }),
2914
3368
  import_v36.z.null()
2915
3369
  ]);
3370
+ var PreprocessorSavedFunctionId = import_v36.z.union([
3371
+ import_v36.z.object({
3372
+ type: import_v36.z.literal("function"),
3373
+ id: import_v36.z.string(),
3374
+ version: import_v36.z.string().optional()
3375
+ }),
3376
+ import_v36.z.object({
3377
+ type: import_v36.z.literal("global"),
3378
+ name: import_v36.z.string(),
3379
+ function_type: import_v36.z.literal("preprocessor").optional().default("preprocessor")
3380
+ }),
3381
+ import_v36.z.null()
3382
+ ]);
2916
3383
  var PromptDataNullish = import_v36.z.union([
2917
3384
  import_v36.z.object({
2918
3385
  prompt: PromptBlockDataNullish,
2919
3386
  options: PromptOptionsNullish,
2920
3387
  parser: PromptParserNullish,
3388
+ preprocessor: PreprocessorSavedFunctionId,
2921
3389
  tool_functions: import_v36.z.union([import_v36.z.array(SavedFunctionId), import_v36.z.null()]),
2922
3390
  template_format: import_v36.z.union([
2923
3391
  import_v36.z.enum(["mustache", "nunjucks", "none"]),
@@ -3119,6 +3587,7 @@ var PromptData = import_v36.z.object({
3119
3587
  prompt: PromptBlockDataNullish,
3120
3588
  options: PromptOptionsNullish,
3121
3589
  parser: PromptParserNullish,
3590
+ preprocessor: PreprocessorSavedFunctionId,
3122
3591
  tool_functions: import_v36.z.union([import_v36.z.array(SavedFunctionId), import_v36.z.null()]),
3123
3592
  template_format: import_v36.z.union([
3124
3593
  import_v36.z.enum(["mustache", "nunjucks", "none"]),
@@ -3281,7 +3750,8 @@ var InvokeFunction = FunctionId.and(
3281
3750
  mode: StreamingMode,
3282
3751
  strict: import_v36.z.union([import_v36.z.boolean(), import_v36.z.null()]),
3283
3752
  mcp_auth: import_v36.z.record(import_v36.z.object({ oauth_token: import_v36.z.string() }).partial()),
3284
- overrides: import_v36.z.union([import_v36.z.object({}).partial().passthrough(), import_v36.z.null()])
3753
+ overrides: import_v36.z.union([import_v36.z.object({}).partial().passthrough(), import_v36.z.null()]),
3754
+ endpoint_name: import_v36.z.union([import_v36.z.string(), import_v36.z.null()])
3285
3755
  }).partial()
3286
3756
  );
3287
3757
  var MCPServer = import_v36.z.object({
@@ -3345,6 +3815,24 @@ var Organization = import_v36.z.object({
3345
3815
  created: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
3346
3816
  image_rendering_mode: ImageRenderingMode.optional()
3347
3817
  });
3818
+ var RetentionObjectType = import_v36.z.enum([
3819
+ "project_logs",
3820
+ "experiment",
3821
+ "dataset"
3822
+ ]);
3823
+ var OrgAutomation = import_v36.z.object({
3824
+ id: import_v36.z.string().uuid(),
3825
+ org_id: import_v36.z.string().uuid(),
3826
+ user_id: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
3827
+ created: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
3828
+ name: import_v36.z.string(),
3829
+ description: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
3830
+ config: import_v36.z.object({
3831
+ event_type: import_v36.z.literal("retention"),
3832
+ object_type: RetentionObjectType,
3833
+ retention_days: import_v36.z.number().int().gte(0)
3834
+ })
3835
+ });
3348
3836
  var ProjectSettings = import_v36.z.union([
3349
3837
  import_v36.z.object({
3350
3838
  comparison_key: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]),
@@ -3371,6 +3859,7 @@ var ProjectSettings = import_v36.z.union([
3371
3859
  import_v36.z.null()
3372
3860
  ]),
3373
3861
  disable_realtime_queries: import_v36.z.union([import_v36.z.boolean(), import_v36.z.null()]),
3862
+ monitor_charts_use_metrics_start: import_v36.z.union([import_v36.z.boolean(), import_v36.z.null()]),
3374
3863
  default_preprocessor: NullableSavedFunctionId
3375
3864
  }).partial(),
3376
3865
  import_v36.z.null()
@@ -3385,11 +3874,6 @@ var Project = import_v36.z.object({
3385
3874
  user_id: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
3386
3875
  settings: ProjectSettings.optional()
3387
3876
  });
3388
- var RetentionObjectType = import_v36.z.enum([
3389
- "project_logs",
3390
- "experiment",
3391
- "dataset"
3392
- ]);
3393
3877
  var TopicAutomationFacetModel = import_v36.z.union([
3394
3878
  import_v36.z.enum(["brain-facet-latest", "brain-facet-1", "brain-facet-2"]),
3395
3879
  import_v36.z.null()
@@ -3500,7 +3984,7 @@ var ProjectAutomation = import_v36.z.object({
3500
3984
  import_v36.z.object({
3501
3985
  event_type: import_v36.z.literal("retention"),
3502
3986
  object_type: RetentionObjectType,
3503
- retention_days: import_v36.z.number().gte(0)
3987
+ retention_days: import_v36.z.number().int().gte(0)
3504
3988
  }),
3505
3989
  import_v36.z.object({
3506
3990
  event_type: import_v36.z.literal("environment_update"),
@@ -3672,7 +4156,12 @@ var Prompt = import_v36.z.object({
3672
4156
  metadata: import_v36.z.union([import_v36.z.object({}).partial().passthrough(), import_v36.z.null()]).optional(),
3673
4157
  function_type: FunctionTypeEnumNullish.optional()
3674
4158
  });
3675
- var PromptOptions = import_v36.z.object({ model: import_v36.z.string(), params: ModelParams, position: import_v36.z.string() }).partial();
4159
+ var PromptOptions = import_v36.z.object({
4160
+ model: import_v36.z.string(),
4161
+ params: ModelParams,
4162
+ position: import_v36.z.string(),
4163
+ endpoint_name: import_v36.z.union([import_v36.z.string(), import_v36.z.null()])
4164
+ }).partial();
3676
4165
  var PromptSessionEvent = import_v36.z.object({
3677
4166
  id: import_v36.z.string(),
3678
4167
  _xact_id: import_v36.z.string(),
@@ -3755,7 +4244,8 @@ var RunEval = import_v36.z.object({
3755
4244
  stop_token: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
3756
4245
  extra_messages: import_v36.z.string().optional(),
3757
4246
  tags: import_v36.z.array(import_v36.z.string()).optional(),
3758
- mcp_auth: import_v36.z.record(import_v36.z.object({ oauth_token: import_v36.z.string() }).partial()).optional()
4247
+ mcp_auth: import_v36.z.record(import_v36.z.object({ oauth_token: import_v36.z.string() }).partial()).optional(),
4248
+ endpoint_name: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional()
3759
4249
  });
3760
4250
  var ServiceToken = import_v36.z.object({
3761
4251
  id: import_v36.z.string().uuid(),
@@ -3765,7 +4255,8 @@ var ServiceToken = import_v36.z.object({
3765
4255
  service_account_id: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
3766
4256
  service_account_email: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
3767
4257
  service_account_name: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
3768
- org_id: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional()
4258
+ org_id: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
4259
+ expires_at: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional()
3769
4260
  });
3770
4261
  var SpanIFrame = import_v36.z.object({
3771
4262
  id: import_v36.z.string().uuid(),
@@ -3887,6 +4378,13 @@ var ViewOptions = import_v36.z.union([
3887
4378
  }),
3888
4379
  import_v36.z.null()
3889
4380
  ]),
4381
+ pointSizeMetric: import_v36.z.union([
4382
+ import_v36.z.object({
4383
+ type: import_v36.z.enum(["none", "score", "metric", "metadata"]),
4384
+ value: import_v36.z.string()
4385
+ }),
4386
+ import_v36.z.null()
4387
+ ]),
3890
4388
  xAxisAggregation: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]),
3891
4389
  chartAnnotations: import_v36.z.union([
3892
4390
  import_v36.z.array(import_v36.z.object({ id: import_v36.z.string(), text: import_v36.z.string() })),
@@ -5028,6 +5526,8 @@ var INSTRUMENTATION_NAMES = {
5028
5526
  BEDROCK_RUNTIME: "bedrock-runtime",
5029
5527
  BRAINTRUST_JS_LOGGER: "braintrust-js-logger",
5030
5528
  CLAUDE_AGENT_SDK: "claude-agent-sdk",
5529
+ CLOUDFLARE_AI_CHAT: "cloudflare-ai-chat",
5530
+ CLOUDFLARE_AGENTS: "cloudflare-agents",
5031
5531
  COHERE: "cohere",
5032
5532
  CURSOR_SDK: "cursor-sdk",
5033
5533
  EVE: "eve",
@@ -5053,7 +5553,7 @@ var INSTRUMENTATION_NAMES = {
5053
5553
  var INTERNAL_SPAN_INSTRUMENTATION_NAME = /* @__PURE__ */ Symbol.for(
5054
5554
  "braintrust.spanInstrumentationName"
5055
5555
  );
5056
- var SDK_VERSION = true ? "3.25.0" : "0.0.0";
5556
+ var SDK_VERSION = true ? "3.26.0" : "0.0.0";
5057
5557
  function withSpanInstrumentationName(args, instrumentationName) {
5058
5558
  return {
5059
5559
  ...args,
@@ -5248,12 +5748,13 @@ function applyMaskingToField(maskingFunction, data, fieldName) {
5248
5748
  var INITIAL_SPAN_WRITE_AS_MERGE = /* @__PURE__ */ Symbol(
5249
5749
  "braintrust.initial-span-write-as-merge"
5250
5750
  );
5751
+ var INTERNAL_SPAN_CONTEXT = /* @__PURE__ */ Symbol("braintrust.internal-span-context");
5251
5752
  var BRAINTRUST_CURRENT_SPAN_STORE = /* @__PURE__ */ Symbol.for(
5252
5753
  "braintrust.currentSpanStore"
5253
5754
  );
5254
5755
  var ContextManager = class {
5255
5756
  /**
5256
- * Returns the value to store in the ALS bound to a TracingChannel's start event.
5757
+ * Returns the value to store in the ALS bound to a global hook's start event.
5257
5758
  * In default mode this is the Span itself; in OTEL mode it is the OTEL Context
5258
5759
  * containing the span so that OTEL's own ALS stores a proper Context object.
5259
5760
  */
@@ -8986,6 +9487,12 @@ function _internalStartSpanWithInitialMerge(args) {
8986
9487
  [INITIAL_SPAN_WRITE_AS_MERGE]: true
8987
9488
  }).span;
8988
9489
  }
9490
+ function _internalStartSpanWithContext(args, context) {
9491
+ return startSpanAndIsLogger({
9492
+ ...args,
9493
+ [INTERNAL_SPAN_CONTEXT]: context
9494
+ }).span;
9495
+ }
8989
9496
  async function flush(options) {
8990
9497
  const state = options?.state ?? _globalState;
8991
9498
  return await state.bgLogger().flush();
@@ -9887,7 +10394,7 @@ var SpanImpl = class _SpanImpl {
9887
10394
  start: args.startTime ?? getCurrentUnixTimestamp()
9888
10395
  },
9889
10396
  context: mergeSpanOriginContext(
9890
- { ...callerLocation },
10397
+ { ...callerLocation, ...args[INTERNAL_SPAN_CONTEXT] },
9891
10398
  instrumentationName,
9892
10399
  this._state.spanOriginEnvironment
9893
10400
  ),
@@ -11827,8 +12334,8 @@ function runWithAutoInstrumentationSuppressed(callback) {
11827
12334
  callback
11828
12335
  );
11829
12336
  }
11830
- function bindAutoInstrumentationSuppressionToStart(tracingChannel2) {
11831
- const startChannel = tracingChannel2.start;
12337
+ function bindAutoInstrumentationSuppressionToStart(tracingChannel) {
12338
+ const startChannel = tracingChannel.start;
11832
12339
  if (!startChannel) {
11833
12340
  return void 0;
11834
12341
  }
@@ -11939,9 +12446,9 @@ function ensureSpanStateForEvent(states, config, event, channelName, instrumenta
11939
12446
  states.set(key, created);
11940
12447
  return created;
11941
12448
  }
11942
- function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelName, instrumentationName) {
12449
+ function bindCurrentSpanStoreToStart(tracingChannel, states, config, channelName, instrumentationName) {
11943
12450
  const state = _internalGetGlobalState();
11944
- const startChannel = tracingChannel2.start;
12451
+ const startChannel = tracingChannel.start;
11945
12452
  const contextManager = state?.contextManager;
11946
12453
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
11947
12454
  if (!currentSpanStore || !startChannel) {
@@ -12024,11 +12531,11 @@ function runStreamingErrorHook(args) {
12024
12531
  }
12025
12532
  }
12026
12533
  function traceAsyncChannel(channel2, config) {
12027
- const tracingChannel2 = channel2.tracingChannel();
12534
+ const tracingChannel = channel2.tracingChannel();
12028
12535
  const states = /* @__PURE__ */ new WeakMap();
12029
12536
  const channelName = channel2.channelName;
12030
12537
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart(
12031
- tracingChannel2,
12538
+ tracingChannel,
12032
12539
  states,
12033
12540
  config,
12034
12541
  channelName,
@@ -12084,18 +12591,18 @@ function traceAsyncChannel(channel2, config) {
12084
12591
  logErrorAndEnd(states, event, channelName);
12085
12592
  }
12086
12593
  };
12087
- tracingChannel2.subscribe(handlers);
12594
+ tracingChannel.subscribe(handlers);
12088
12595
  return () => {
12089
12596
  unbindCurrentSpanStore?.();
12090
- tracingChannel2.unsubscribe(handlers);
12597
+ tracingChannel.unsubscribe(handlers);
12091
12598
  };
12092
12599
  }
12093
12600
  function traceStreamingChannel(channel2, config) {
12094
- const tracingChannel2 = channel2.tracingChannel();
12601
+ const tracingChannel = channel2.tracingChannel();
12095
12602
  const states = /* @__PURE__ */ new WeakMap();
12096
12603
  const channelName = channel2.channelName;
12097
12604
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart(
12098
- tracingChannel2,
12605
+ tracingChannel,
12099
12606
  states,
12100
12607
  config,
12101
12608
  channelName,
@@ -12306,18 +12813,18 @@ function traceStreamingChannel(channel2, config) {
12306
12813
  }
12307
12814
  }
12308
12815
  };
12309
- tracingChannel2.subscribe(handlers);
12816
+ tracingChannel.subscribe(handlers);
12310
12817
  return () => {
12311
12818
  unbindCurrentSpanStore?.();
12312
- tracingChannel2.unsubscribe(handlers);
12819
+ tracingChannel.unsubscribe(handlers);
12313
12820
  };
12314
12821
  }
12315
12822
  function traceSyncStreamChannel(channel2, config) {
12316
- const tracingChannel2 = channel2.tracingChannel();
12823
+ const tracingChannel = channel2.tracingChannel();
12317
12824
  const states = /* @__PURE__ */ new WeakMap();
12318
12825
  const channelName = channel2.channelName;
12319
12826
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart(
12320
- tracingChannel2,
12827
+ tracingChannel,
12321
12828
  states,
12322
12829
  config,
12323
12830
  channelName,
@@ -12430,10 +12937,10 @@ function traceSyncStreamChannel(channel2, config) {
12430
12937
  logErrorAndEnd(states, event, channelName);
12431
12938
  }
12432
12939
  };
12433
- tracingChannel2.subscribe(handlers);
12940
+ tracingChannel.subscribe(handlers);
12434
12941
  return () => {
12435
12942
  unbindCurrentSpanStore?.();
12436
- tracingChannel2.unsubscribe(handlers);
12943
+ tracingChannel.unsubscribe(handlers);
12437
12944
  };
12438
12945
  }
12439
12946
  function unsubscribeAll(unsubscribers) {
@@ -12613,7 +13120,7 @@ function defineChannels(pkg, channels, options) {
12613
13120
  const fullChannelName = `orchestrion:${pkg}:${spec.channelName}`;
12614
13121
  if (spec.kind === "async") {
12615
13122
  const asyncSpec = spec;
12616
- const tracingChannel3 = () => isomorph_default.newTracingChannel(
13123
+ const tracingChannel2 = () => isomorph_default.newTracingChannel(
12617
13124
  fullChannelName
12618
13125
  );
12619
13126
  return [
@@ -12621,8 +13128,8 @@ function defineChannels(pkg, channels, options) {
12621
13128
  {
12622
13129
  ...asyncSpec,
12623
13130
  instrumentationName,
12624
- tracingChannel: tracingChannel3,
12625
- tracePromise: (fn, context) => tracingChannel3().tracePromise(
13131
+ tracingChannel: tracingChannel2,
13132
+ tracePromise: (fn, context) => tracingChannel2().tracePromise(
12626
13133
  fn,
12627
13134
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
12628
13135
  context
@@ -12631,7 +13138,7 @@ function defineChannels(pkg, channels, options) {
12631
13138
  ];
12632
13139
  }
12633
13140
  const syncSpec = spec;
12634
- const tracingChannel2 = () => isomorph_default.newTracingChannel(
13141
+ const tracingChannel = () => isomorph_default.newTracingChannel(
12635
13142
  fullChannelName
12636
13143
  );
12637
13144
  return [
@@ -12639,8 +13146,8 @@ function defineChannels(pkg, channels, options) {
12639
13146
  {
12640
13147
  ...syncSpec,
12641
13148
  instrumentationName,
12642
- tracingChannel: tracingChannel2,
12643
- traceSync: (fn, context) => tracingChannel2().traceSync(
13149
+ tracingChannel,
13150
+ traceSync: (fn, context) => tracingChannel().traceSync(
12644
13151
  fn,
12645
13152
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
12646
13153
  context
@@ -13972,7 +14479,7 @@ var AnthropicPlugin = class extends BasePlugin {
13972
14479
  );
13973
14480
  }
13974
14481
  subscribeToAnthropicToolRunner() {
13975
- const tracingChannel2 = anthropicChannels.betaMessagesToolRunner.tracingChannel();
14482
+ const tracingChannel = anthropicChannels.betaMessagesToolRunner.tracingChannel();
13976
14483
  const states = /* @__PURE__ */ new WeakMap();
13977
14484
  const handlers = {
13978
14485
  start: (event) => {
@@ -14029,9 +14536,9 @@ var AnthropicPlugin = class extends BasePlugin {
14029
14536
  states.delete(event);
14030
14537
  }
14031
14538
  };
14032
- tracingChannel2.subscribe(handlers);
14539
+ tracingChannel.subscribe(handlers);
14033
14540
  this.unsubscribers.push(() => {
14034
- tracingChannel2.unsubscribe(handlers);
14541
+ tracingChannel.unsubscribe(handlers);
14035
14542
  });
14036
14543
  }
14037
14544
  };
@@ -14943,8 +15450,8 @@ function registerHarnessSessionParent(session, parent) {
14943
15450
  function currentHarnessTurnParent() {
14944
15451
  return harnessTurnParentStore?.getStore() ?? wrapperTurnParents.get(currentSpan());
14945
15452
  }
14946
- function bindHarnessTurnParentToStart(tracingChannel2, parentFromEvent) {
14947
- const startChannel = tracingChannel2.start;
15453
+ function bindHarnessTurnParentToStart(tracingChannel, parentFromEvent) {
15454
+ const startChannel = tracingChannel.start;
14948
15455
  if (!startChannel) {
14949
15456
  return () => {
14950
15457
  };
@@ -20410,7 +20917,7 @@ var CursorSDKPlugin = class extends BasePlugin {
20410
20917
  this.subscribeToAgentFactory(cursorSDKChannels.resume);
20411
20918
  }
20412
20919
  subscribeToAgentFactory(channel2) {
20413
- const tracingChannel2 = channel2.tracingChannel();
20920
+ const tracingChannel = channel2.tracingChannel();
20414
20921
  const handlers = {
20415
20922
  asyncEnd: (event) => {
20416
20923
  patchCursorAgentInPlace(event.result);
@@ -20418,9 +20925,9 @@ var CursorSDKPlugin = class extends BasePlugin {
20418
20925
  error: () => {
20419
20926
  }
20420
20927
  };
20421
- tracingChannel2.subscribe(handlers);
20928
+ tracingChannel.subscribe(handlers);
20422
20929
  this.unsubscribers.push(() => {
20423
- tracingChannel2.unsubscribe(handlers);
20930
+ tracingChannel.unsubscribe(handlers);
20424
20931
  });
20425
20932
  }
20426
20933
  subscribeToPrompt() {
@@ -21776,10 +22283,10 @@ var GoogleGenAIPlugin = class extends BasePlugin {
21776
22283
  this.subscribeToInteractionsCreateChannel();
21777
22284
  }
21778
22285
  subscribeToGenerateContentChannel() {
21779
- const tracingChannel2 = googleGenAIChannels.generateContent.tracingChannel();
22286
+ const tracingChannel = googleGenAIChannels.generateContent.tracingChannel();
21780
22287
  const states = /* @__PURE__ */ new WeakMap();
21781
22288
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart2(
21782
- tracingChannel2,
22289
+ tracingChannel,
21783
22290
  states,
21784
22291
  (event) => {
21785
22292
  const params = event.arguments[0];
@@ -21853,14 +22360,14 @@ var GoogleGenAIPlugin = class extends BasePlugin {
21853
22360
  logErrorAndEndSpan(states, event);
21854
22361
  }
21855
22362
  };
21856
- tracingChannel2.subscribe(handlers);
22363
+ tracingChannel.subscribe(handlers);
21857
22364
  this.unsubscribers.push(() => {
21858
22365
  unbindCurrentSpanStore?.();
21859
- tracingChannel2.unsubscribe(handlers);
22366
+ tracingChannel.unsubscribe(handlers);
21860
22367
  });
21861
22368
  }
21862
22369
  subscribeToGenerateContentStreamChannel() {
21863
- const tracingChannel2 = googleGenAIChannels.generateContentStream.tracingChannel();
22370
+ const tracingChannel = googleGenAIChannels.generateContentStream.tracingChannel();
21864
22371
  const handlers = {
21865
22372
  start: (event) => {
21866
22373
  const streamEvent = event;
@@ -21881,16 +22388,16 @@ var GoogleGenAIPlugin = class extends BasePlugin {
21881
22388
  error: () => {
21882
22389
  }
21883
22390
  };
21884
- tracingChannel2.subscribe(handlers);
22391
+ tracingChannel.subscribe(handlers);
21885
22392
  this.unsubscribers.push(() => {
21886
- tracingChannel2.unsubscribe(handlers);
22393
+ tracingChannel.unsubscribe(handlers);
21887
22394
  });
21888
22395
  }
21889
22396
  subscribeToEmbedContentChannel() {
21890
- const tracingChannel2 = googleGenAIChannels.embedContent.tracingChannel();
22397
+ const tracingChannel = googleGenAIChannels.embedContent.tracingChannel();
21891
22398
  const states = /* @__PURE__ */ new WeakMap();
21892
22399
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart2(
21893
- tracingChannel2,
22400
+ tracingChannel,
21894
22401
  states,
21895
22402
  (event) => {
21896
22403
  const params = event.arguments[0];
@@ -21960,10 +22467,10 @@ var GoogleGenAIPlugin = class extends BasePlugin {
21960
22467
  logErrorAndEndSpan(states, event);
21961
22468
  }
21962
22469
  };
21963
- tracingChannel2.subscribe(handlers);
22470
+ tracingChannel.subscribe(handlers);
21964
22471
  this.unsubscribers.push(() => {
21965
22472
  unbindCurrentSpanStore?.();
21966
- tracingChannel2.unsubscribe(handlers);
22473
+ tracingChannel.unsubscribe(handlers);
21967
22474
  });
21968
22475
  }
21969
22476
  subscribeToInteractionsCreateChannel() {
@@ -21999,10 +22506,10 @@ function ensureSpanState(states, event, create) {
21999
22506
  states.set(event, created);
22000
22507
  return created;
22001
22508
  }
22002
- function bindCurrentSpanStoreToStart2(tracingChannel2, states, create) {
22509
+ function bindCurrentSpanStoreToStart2(tracingChannel, states, create) {
22003
22510
  const state = _internalGetGlobalState();
22004
22511
  const contextManager = state?.contextManager;
22005
- const startChannel = tracingChannel2.start;
22512
+ const startChannel = tracingChannel.start;
22006
22513
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
22007
22514
  if (!startChannel?.bindStore || !currentSpanStore) {
22008
22515
  return void 0;
@@ -22505,11 +23012,11 @@ function summarizeEmbedContentOutput(response) {
22505
23012
  };
22506
23013
  }
22507
23014
  function populateUsageMetrics(metrics, usage) {
22508
- if (usage.promptTokenCount !== void 0) {
22509
- metrics.prompt_tokens = usage.promptTokenCount;
23015
+ if (usage.promptTokenCount !== void 0 || usage.toolUsePromptTokenCount !== void 0) {
23016
+ metrics.prompt_tokens = (usage.promptTokenCount ?? 0) + (usage.toolUsePromptTokenCount ?? 0);
22510
23017
  }
22511
- if (usage.candidatesTokenCount !== void 0) {
22512
- metrics.completion_tokens = usage.candidatesTokenCount;
23018
+ if (usage.candidatesTokenCount !== void 0 || usage.thoughtsTokenCount !== void 0) {
23019
+ metrics.completion_tokens = (usage.candidatesTokenCount ?? 0) + (usage.thoughtsTokenCount ?? 0);
22513
23020
  }
22514
23021
  if (usage.totalTokenCount !== void 0) {
22515
23022
  metrics.tokens = usage.totalTokenCount;
@@ -22520,13 +23027,26 @@ function populateUsageMetrics(metrics, usage) {
22520
23027
  if (usage.thoughtsTokenCount !== void 0) {
22521
23028
  metrics.completion_reasoning_tokens = usage.thoughtsTokenCount;
22522
23029
  }
23030
+ for (const detail of usage.promptTokensDetails ?? []) {
23031
+ if (detail.modality === "AUDIO" && detail.tokenCount !== void 0) {
23032
+ metrics.prompt_audio_tokens = (metrics.prompt_audio_tokens ?? 0) + detail.tokenCount;
23033
+ }
23034
+ }
23035
+ for (const detail of usage.candidatesTokensDetails ?? []) {
23036
+ if (detail.modality === "AUDIO" && detail.tokenCount !== void 0) {
23037
+ metrics.completion_audio_tokens = (metrics.completion_audio_tokens ?? 0) + detail.tokenCount;
23038
+ }
23039
+ if (detail.modality === "IMAGE" && detail.tokenCount !== void 0) {
23040
+ metrics.completion_image_tokens = (metrics.completion_image_tokens ?? 0) + detail.tokenCount;
23041
+ }
23042
+ }
22523
23043
  }
22524
23044
  function populateInteractionUsageMetrics(metrics, usage) {
22525
23045
  if (typeof usage.total_input_tokens === "number") {
22526
23046
  metrics.prompt_tokens = usage.total_input_tokens;
22527
23047
  }
22528
23048
  if (typeof usage.total_output_tokens === "number") {
22529
- metrics.completion_tokens = usage.total_output_tokens;
23049
+ metrics.completion_tokens = usage.total_output_tokens + (typeof usage.total_thought_tokens === "number" ? usage.total_thought_tokens : 0);
22530
23050
  }
22531
23051
  if (typeof usage.total_tokens === "number") {
22532
23052
  metrics.tokens = usage.total_tokens;
@@ -22537,6 +23057,24 @@ function populateInteractionUsageMetrics(metrics, usage) {
22537
23057
  if (typeof usage.total_thought_tokens === "number") {
22538
23058
  metrics.completion_reasoning_tokens = usage.total_thought_tokens;
22539
23059
  }
23060
+ for (const detail of Array.isArray(usage.input_tokens_by_modality) ? usage.input_tokens_by_modality : []) {
23061
+ if (typeof detail?.modality === "string" && detail.modality.toLowerCase() === "audio" && typeof detail.tokens === "number") {
23062
+ metrics.prompt_audio_tokens = (metrics.prompt_audio_tokens ?? 0) + detail.tokens;
23063
+ }
23064
+ }
23065
+ for (const detail of Array.isArray(usage.output_tokens_by_modality) ? usage.output_tokens_by_modality : []) {
23066
+ if (typeof detail?.modality !== "string" || typeof detail.tokens !== "number") {
23067
+ continue;
23068
+ }
23069
+ switch (detail.modality.toLowerCase()) {
23070
+ case "audio":
23071
+ metrics.completion_audio_tokens = (metrics.completion_audio_tokens ?? 0) + detail.tokens;
23072
+ break;
23073
+ case "image":
23074
+ metrics.completion_image_tokens = (metrics.completion_image_tokens ?? 0) + detail.tokens;
23075
+ break;
23076
+ }
23077
+ }
22540
23078
  }
22541
23079
  function aggregateGenerateContentChunks(chunks, startTime, firstTokenTime) {
22542
23080
  const end = getCurrentUnixTimestamp();
@@ -23275,6 +23813,299 @@ function extractTextGenerationStreamMetadata(chunks) {
23275
23813
  return void 0;
23276
23814
  }
23277
23815
 
23816
+ // src/instrumentation/plugins/huggingface-transformers-channels.ts
23817
+ var SUPPORTED_TASKS = /* @__PURE__ */ new Set([
23818
+ "text-generation",
23819
+ "text2text-generation",
23820
+ "summarization",
23821
+ "feature-extraction",
23822
+ "question-answering"
23823
+ ]);
23824
+ var pipelineInfo = /* @__PURE__ */ new WeakMap();
23825
+ function isSupportedHuggingFaceTransformersTask(task) {
23826
+ return typeof task === "string" && SUPPORTED_TASKS.has(task);
23827
+ }
23828
+ function registerHuggingFaceTransformersPipeline(pipeline, task, model) {
23829
+ if (typeof task !== "string") {
23830
+ return;
23831
+ }
23832
+ const info = { task };
23833
+ if (typeof model === "string") {
23834
+ info.model = model;
23835
+ }
23836
+ pipelineInfo.set(pipeline, info);
23837
+ }
23838
+ function getHuggingFaceTransformersPipelineInfo(pipeline) {
23839
+ return pipeline ? pipelineInfo.get(pipeline) : void 0;
23840
+ }
23841
+ var huggingFaceTransformersChannels = defineChannels(
23842
+ "@huggingface/transformers",
23843
+ {
23844
+ pipeline: channel({
23845
+ channelName: "pipeline",
23846
+ kind: "async"
23847
+ }),
23848
+ pipelineCall: channel({
23849
+ channelName: "pipeline.call",
23850
+ kind: "async"
23851
+ })
23852
+ },
23853
+ { instrumentationName: INSTRUMENTATION_NAMES.HUGGINGFACE }
23854
+ );
23855
+
23856
+ // src/instrumentation/plugins/huggingface-transformers-plugin.ts
23857
+ var REQUEST_METADATA_KEYS = [
23858
+ "temperature",
23859
+ "top_p",
23860
+ "max_tokens",
23861
+ "stop"
23862
+ ];
23863
+ var HuggingFaceTransformersPlugin = class extends BasePlugin {
23864
+ onEnable() {
23865
+ this.subscribeToPipelineFactory();
23866
+ this.unsubscribers.push(
23867
+ traceAsyncChannel(huggingFaceTransformersChannels.pipelineCall, {
23868
+ name: (_args, event) => {
23869
+ const task = getTask(event);
23870
+ const operation = task?.replaceAll("-", "_") ?? "unknown";
23871
+ return `huggingface.transformers.${operation}`;
23872
+ },
23873
+ type: "llm" /* LLM */,
23874
+ shouldTrace: (_args, event) => isSupportedHuggingFaceTransformersTask(
23875
+ getTask(event)
23876
+ ),
23877
+ extractInput: (args, event) => ({
23878
+ input: extractInput(
23879
+ getTask(event),
23880
+ args
23881
+ ),
23882
+ metadata: extractMetadata(
23883
+ event,
23884
+ args
23885
+ )
23886
+ }),
23887
+ extractOutput: (result, event) => extractOutput(
23888
+ getTask(event),
23889
+ result
23890
+ ),
23891
+ extractMetrics: () => ({})
23892
+ })
23893
+ );
23894
+ }
23895
+ onDisable() {
23896
+ this.unsubscribers = unsubscribeAll(this.unsubscribers);
23897
+ }
23898
+ subscribeToPipelineFactory() {
23899
+ const channel2 = huggingFaceTransformersChannels.pipeline.tracingChannel();
23900
+ const handlers = {
23901
+ asyncEnd: (event) => {
23902
+ if (typeof event.result !== "function") {
23903
+ return;
23904
+ }
23905
+ registerHuggingFaceTransformersPipeline(
23906
+ event.result,
23907
+ event.arguments?.[0],
23908
+ event.arguments?.[1]
23909
+ );
23910
+ }
23911
+ };
23912
+ channel2.subscribe(handlers);
23913
+ this.unsubscribers.push(() => channel2.unsubscribe(handlers));
23914
+ }
23915
+ };
23916
+ function getTask(event) {
23917
+ const self = event.self;
23918
+ const registeredTask = getHuggingFaceTransformersPipelineInfo(self)?.task;
23919
+ if (registeredTask !== void 0) {
23920
+ return registeredTask;
23921
+ }
23922
+ if (typeof self?.task === "string") {
23923
+ return self.task;
23924
+ }
23925
+ return void 0;
23926
+ }
23927
+ function extractMetadata(event, args) {
23928
+ const metadata = {
23929
+ provider: "huggingface"
23930
+ };
23931
+ const registeredModel = getHuggingFaceTransformersPipelineInfo(
23932
+ event.self
23933
+ )?.model;
23934
+ const model = registeredModel ?? modelIdentifier(event.self);
23935
+ if (model) {
23936
+ metadata.model = model;
23937
+ }
23938
+ const task = getTask(event);
23939
+ const options = task === "question-answering" ? args[2] : args[1];
23940
+ if (isObject(options)) {
23941
+ for (const key of REQUEST_METADATA_KEYS) {
23942
+ if (options[key] !== void 0) {
23943
+ metadata[key] = options[key];
23944
+ }
23945
+ }
23946
+ }
23947
+ return metadata;
23948
+ }
23949
+ function modelIdentifier(pipeline) {
23950
+ const model = pipeline?.model;
23951
+ if (!isObject(model)) {
23952
+ return void 0;
23953
+ }
23954
+ const config = isObject(model.config) ? model.config : void 0;
23955
+ for (const value of [
23956
+ config?._name_or_path,
23957
+ config?.name_or_path,
23958
+ config?.model_id,
23959
+ config?.modelId,
23960
+ model.name
23961
+ ]) {
23962
+ if (typeof value === "string" && value.length > 0) {
23963
+ return value;
23964
+ }
23965
+ }
23966
+ return void 0;
23967
+ }
23968
+ function extractInput(task, args) {
23969
+ switch (task) {
23970
+ case "feature-extraction":
23971
+ return args[0];
23972
+ case "question-answering": {
23973
+ const question = args[0];
23974
+ const context = args[1];
23975
+ if (Array.isArray(question) && Array.isArray(context) && question.every((value) => typeof value === "string") && context.every((value) => typeof value === "string")) {
23976
+ return question.map((value, index) => [
23977
+ {
23978
+ role: "user",
23979
+ content: `Context:
23980
+ ${context[index] ?? ""}
23981
+
23982
+ Question:
23983
+ ${value}`
23984
+ }
23985
+ ]);
23986
+ }
23987
+ if (typeof question === "string" && typeof context === "string") {
23988
+ return [
23989
+ {
23990
+ role: "user",
23991
+ content: `Context:
23992
+ ${context}
23993
+
23994
+ Question:
23995
+ ${question}`
23996
+ }
23997
+ ];
23998
+ }
23999
+ return { context, question };
24000
+ }
24001
+ }
24002
+ const input = args[0];
24003
+ if (task === "text-generation" && isChat(input)) {
24004
+ return input;
24005
+ }
24006
+ if (task === "text-generation" && Array.isArray(input) && input.every(isChat)) {
24007
+ return input;
24008
+ }
24009
+ if (typeof input === "string") {
24010
+ return [{ role: "user", content: input }];
24011
+ }
24012
+ if (Array.isArray(input) && input.every((value) => typeof value === "string")) {
24013
+ return input.map((value) => [
24014
+ {
24015
+ role: "user",
24016
+ content: value
24017
+ }
24018
+ ]);
24019
+ }
24020
+ return input;
24021
+ }
24022
+ function isChat(value) {
24023
+ return Array.isArray(value) && value.length > 0 && value.every(
24024
+ (message) => isObject(message) && typeof message.role === "string" && "content" in message
24025
+ );
24026
+ }
24027
+ function extractOutput(task, result) {
24028
+ switch (task) {
24029
+ case "feature-extraction":
24030
+ return summarizeEmbedding(result);
24031
+ case "question-answering":
24032
+ return choicesFromAnswers(result);
24033
+ default:
24034
+ return choicesFromGenerations(result);
24035
+ }
24036
+ }
24037
+ function summarizeEmbedding(result) {
24038
+ if (!isObject(result) || !Array.isArray(result.dims)) {
24039
+ return void 0;
24040
+ }
24041
+ const { dims } = result;
24042
+ if (dims.length === 0 || !dims.every((dimension) => typeof dimension === "number")) {
24043
+ return void 0;
24044
+ }
24045
+ if (dims.length === 1) {
24046
+ return { embedding_length: dims[0] };
24047
+ }
24048
+ if (dims.length === 2) {
24049
+ return {
24050
+ embedding_count: dims[0],
24051
+ embedding_length: dims[1]
24052
+ };
24053
+ }
24054
+ return {
24055
+ embedding_batch_count: dims[0],
24056
+ embedding_count: dims[1],
24057
+ embedding_length: dims.at(-1) ?? 0
24058
+ };
24059
+ }
24060
+ function choicesFromAnswers(result) {
24061
+ const answers = Array.isArray(result) ? result.flat() : [result];
24062
+ const choices = answers.flatMap((answer, index) => {
24063
+ if (!isObject(answer) || typeof answer.answer !== "string") {
24064
+ return [];
24065
+ }
24066
+ return [
24067
+ {
24068
+ index,
24069
+ finish_reason: "stop",
24070
+ message: {
24071
+ role: "assistant",
24072
+ content: answer.answer
24073
+ }
24074
+ }
24075
+ ];
24076
+ });
24077
+ return choices.length > 0 ? choices : void 0;
24078
+ }
24079
+ function choicesFromGenerations(result) {
24080
+ const generations = Array.isArray(result) ? result.flat() : [result];
24081
+ const choices = generations.flatMap((generation, index) => {
24082
+ if (!isObject(generation)) {
24083
+ return [];
24084
+ }
24085
+ const generated = generation.generated_text ?? generation.summary_text;
24086
+ let content;
24087
+ if (typeof generated === "string") {
24088
+ content = generated;
24089
+ } else if (isChat(generated)) {
24090
+ content = generated.at(-1)?.content;
24091
+ }
24092
+ if (typeof content !== "string") {
24093
+ return [];
24094
+ }
24095
+ return [
24096
+ {
24097
+ index,
24098
+ finish_reason: "stop",
24099
+ message: {
24100
+ role: "assistant",
24101
+ content
24102
+ }
24103
+ }
24104
+ ];
24105
+ });
24106
+ return choices.length > 0 ? choices : void 0;
24107
+ }
24108
+
23278
24109
  // src/instrumentation/plugins/openrouter-agent-channels.ts
23279
24110
  var openRouterAgentChannels = defineChannels(
23280
24111
  "@openrouter/agent",
@@ -23674,7 +24505,7 @@ function isWrappedTool(tool) {
23674
24505
  return Boolean(tool[OPENROUTER_WRAPPED_TOOL]);
23675
24506
  }
23676
24507
  function traceToolExecution(args) {
23677
- const tracingChannel2 = openRouterAgentChannels.toolExecute.tracingChannel();
24508
+ const tracingChannel = openRouterAgentChannels.toolExecute.tracingChannel();
23678
24509
  const input = args.args.length > 0 ? args.args[0] : void 0;
23679
24510
  const event = {
23680
24511
  arguments: [input],
@@ -23684,33 +24515,33 @@ function traceToolExecution(args) {
23684
24515
  toolCallId: args.toolCallId,
23685
24516
  toolName: args.toolName
23686
24517
  };
23687
- tracingChannel2.start.publish(event);
24518
+ tracingChannel.start.publish(event);
23688
24519
  try {
23689
24520
  const result = args.execute();
23690
- return publishToolResult(tracingChannel2, event, result);
24521
+ return publishToolResult(tracingChannel, event, result);
23691
24522
  } catch (error) {
23692
24523
  event.error = normalizeError(error);
23693
- tracingChannel2.error.publish(event);
24524
+ tracingChannel.error.publish(event);
23694
24525
  throw error;
23695
24526
  }
23696
24527
  }
23697
- function publishToolResult(tracingChannel2, event, result) {
24528
+ function publishToolResult(tracingChannel, event, result) {
23698
24529
  if (isPromiseLike(result)) {
23699
24530
  return result.then(
23700
24531
  (resolved) => {
23701
24532
  event.result = resolved;
23702
- tracingChannel2.asyncEnd.publish(event);
24533
+ tracingChannel.asyncEnd.publish(event);
23703
24534
  return resolved;
23704
24535
  },
23705
24536
  (error) => {
23706
24537
  event.error = normalizeError(error);
23707
- tracingChannel2.error.publish(event);
24538
+ tracingChannel.error.publish(event);
23708
24539
  throw error;
23709
24540
  }
23710
24541
  );
23711
24542
  }
23712
24543
  event.result = result;
23713
- tracingChannel2.asyncEnd.publish(event);
24544
+ tracingChannel.asyncEnd.publish(event);
23714
24545
  return result;
23715
24546
  }
23716
24547
  function getToolCallId(context) {
@@ -24616,7 +25447,7 @@ function isWrappedTool2(tool) {
24616
25447
  return Boolean(tool[OPENROUTER_WRAPPED_TOOL2]);
24617
25448
  }
24618
25449
  function traceToolExecution2(args) {
24619
- const tracingChannel2 = openRouterChannels.toolExecute.tracingChannel();
25450
+ const tracingChannel = openRouterChannels.toolExecute.tracingChannel();
24620
25451
  const input = args.args.length > 0 ? args.args[0] : void 0;
24621
25452
  const event = {
24622
25453
  arguments: [input],
@@ -24626,33 +25457,33 @@ function traceToolExecution2(args) {
24626
25457
  toolCallId: args.toolCallId,
24627
25458
  toolName: args.toolName
24628
25459
  };
24629
- tracingChannel2.start.publish(event);
25460
+ tracingChannel.start.publish(event);
24630
25461
  try {
24631
25462
  const result = args.execute();
24632
- return publishToolResult2(tracingChannel2, event, result);
25463
+ return publishToolResult2(tracingChannel, event, result);
24633
25464
  } catch (error) {
24634
25465
  event.error = normalizeError2(error);
24635
- tracingChannel2.error.publish(event);
25466
+ tracingChannel.error.publish(event);
24636
25467
  throw error;
24637
25468
  }
24638
25469
  }
24639
- function publishToolResult2(tracingChannel2, event, result) {
25470
+ function publishToolResult2(tracingChannel, event, result) {
24640
25471
  if (isPromiseLike(result)) {
24641
25472
  return result.then(
24642
25473
  (resolved) => {
24643
25474
  event.result = resolved;
24644
- tracingChannel2.asyncEnd.publish(event);
25475
+ tracingChannel.asyncEnd.publish(event);
24645
25476
  return resolved;
24646
25477
  },
24647
25478
  (error) => {
24648
25479
  event.error = normalizeError2(error);
24649
- tracingChannel2.error.publish(event);
25480
+ tracingChannel.error.publish(event);
24650
25481
  throw error;
24651
25482
  }
24652
25483
  );
24653
25484
  }
24654
25485
  event.result = result;
24655
- tracingChannel2.asyncEnd.publish(event);
25486
+ tracingChannel.asyncEnd.publish(event);
24656
25487
  return result;
24657
25488
  }
24658
25489
  function getToolCallId2(context) {
@@ -25842,7 +26673,7 @@ var GoogleADKPlugin = class extends BasePlugin {
25842
26673
  this.activeAgentSpans.clear();
25843
26674
  }
25844
26675
  subscribeToRunnerRunAsync() {
25845
- const tracingChannel2 = googleADKChannels.runnerRunAsync.tracingChannel();
26676
+ const tracingChannel = googleADKChannels.runnerRunAsync.tracingChannel();
25846
26677
  const states = /* @__PURE__ */ new WeakMap();
25847
26678
  const createState = (event) => {
25848
26679
  const params = event.arguments[0] ?? {};
@@ -25873,7 +26704,7 @@ var GoogleADKPlugin = class extends BasePlugin {
25873
26704
  return { span, startTime, events: [], contextKey };
25874
26705
  };
25875
26706
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart3(
25876
- tracingChannel2,
26707
+ tracingChannel,
25877
26708
  states,
25878
26709
  createState
25879
26710
  );
@@ -25925,14 +26756,14 @@ var GoogleADKPlugin = class extends BasePlugin {
25925
26756
  states.delete(event);
25926
26757
  }
25927
26758
  };
25928
- tracingChannel2.subscribe(handlers);
26759
+ tracingChannel.subscribe(handlers);
25929
26760
  this.unsubscribers.push(() => {
25930
26761
  unbindCurrentSpanStore?.();
25931
- tracingChannel2.unsubscribe(handlers);
26762
+ tracingChannel.unsubscribe(handlers);
25932
26763
  });
25933
26764
  }
25934
26765
  subscribeToAgentRunAsync() {
25935
- const tracingChannel2 = googleADKChannels.agentRunAsync.tracingChannel();
26766
+ const tracingChannel = googleADKChannels.agentRunAsync.tracingChannel();
25936
26767
  const states = /* @__PURE__ */ new WeakMap();
25937
26768
  const createState = (event) => {
25938
26769
  const parentContext = event.arguments[0];
@@ -25981,7 +26812,7 @@ var GoogleADKPlugin = class extends BasePlugin {
25981
26812
  return { span, startTime, events: [], contextKey, name: agentName };
25982
26813
  };
25983
26814
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart3(
25984
- tracingChannel2,
26815
+ tracingChannel,
25985
26816
  states,
25986
26817
  createState
25987
26818
  );
@@ -26033,14 +26864,14 @@ var GoogleADKPlugin = class extends BasePlugin {
26033
26864
  states.delete(event);
26034
26865
  }
26035
26866
  };
26036
- tracingChannel2.subscribe(handlers);
26867
+ tracingChannel.subscribe(handlers);
26037
26868
  this.unsubscribers.push(() => {
26038
26869
  unbindCurrentSpanStore?.();
26039
- tracingChannel2.unsubscribe(handlers);
26870
+ tracingChannel.unsubscribe(handlers);
26040
26871
  });
26041
26872
  }
26042
26873
  subscribeToToolRunAsync() {
26043
- const tracingChannel2 = googleADKChannels.toolRunAsync.tracingChannel();
26874
+ const tracingChannel = googleADKChannels.toolRunAsync.tracingChannel();
26044
26875
  const states = /* @__PURE__ */ new WeakMap();
26045
26876
  const handlers = {
26046
26877
  start: (event) => {
@@ -26107,9 +26938,9 @@ var GoogleADKPlugin = class extends BasePlugin {
26107
26938
  states.delete(event);
26108
26939
  }
26109
26940
  };
26110
- tracingChannel2.subscribe(handlers);
26941
+ tracingChannel.subscribe(handlers);
26111
26942
  this.unsubscribers.push(() => {
26112
- tracingChannel2.unsubscribe(handlers);
26943
+ tracingChannel.unsubscribe(handlers);
26113
26944
  });
26114
26945
  }
26115
26946
  };
@@ -26185,10 +27016,10 @@ function bindAsyncIterableToCurrentSpan(stream, span) {
26185
27016
  }
26186
27017
  return stream;
26187
27018
  }
26188
- function bindCurrentSpanStoreToStart3(tracingChannel2, states, create) {
27019
+ function bindCurrentSpanStoreToStart3(tracingChannel, states, create) {
26189
27020
  const state = _internalGetGlobalState();
26190
27021
  const contextManager = state?.contextManager;
26191
- const startChannel = tracingChannel2.start;
27022
+ const startChannel = tracingChannel.start;
26192
27023
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
26193
27024
  if (!startChannel?.bindStore || !currentSpanStore) {
26194
27025
  return void 0;
@@ -26440,15 +27271,32 @@ function aggregateUsageFromEvents(events) {
26440
27271
  if (usage.thoughtsTokenCount !== void 0) {
26441
27272
  aggregated.thoughtsTokenCount = (aggregated.thoughtsTokenCount ?? 0) + usage.thoughtsTokenCount;
26442
27273
  }
27274
+ if (usage.toolUsePromptTokenCount !== void 0) {
27275
+ aggregated.toolUsePromptTokenCount = (aggregated.toolUsePromptTokenCount ?? 0) + usage.toolUsePromptTokenCount;
27276
+ }
27277
+ for (const detailsField of [
27278
+ "promptTokensDetails",
27279
+ "cacheTokensDetails",
27280
+ "candidatesTokensDetails",
27281
+ "toolUsePromptTokensDetails"
27282
+ ]) {
27283
+ const details = usage[detailsField];
27284
+ if (details !== void 0) {
27285
+ aggregated[detailsField] = [
27286
+ ...aggregated[detailsField] ?? [],
27287
+ ...details
27288
+ ];
27289
+ }
27290
+ }
26443
27291
  }
26444
27292
  return hasUsage ? aggregated : void 0;
26445
27293
  }
26446
27294
  function populateUsageMetrics2(metrics, usage) {
26447
- if (usage.promptTokenCount !== void 0) {
26448
- metrics.prompt_tokens = usage.promptTokenCount;
27295
+ if (usage.promptTokenCount !== void 0 || usage.toolUsePromptTokenCount !== void 0) {
27296
+ metrics.prompt_tokens = (usage.promptTokenCount ?? 0) + (usage.toolUsePromptTokenCount ?? 0);
26449
27297
  }
26450
- if (usage.candidatesTokenCount !== void 0) {
26451
- metrics.completion_tokens = usage.candidatesTokenCount;
27298
+ if (usage.candidatesTokenCount !== void 0 || usage.thoughtsTokenCount !== void 0) {
27299
+ metrics.completion_tokens = (usage.candidatesTokenCount ?? 0) + (usage.thoughtsTokenCount ?? 0);
26452
27300
  }
26453
27301
  if (usage.totalTokenCount !== void 0) {
26454
27302
  metrics.tokens = usage.totalTokenCount;
@@ -26459,6 +27307,19 @@ function populateUsageMetrics2(metrics, usage) {
26459
27307
  if (usage.thoughtsTokenCount !== void 0) {
26460
27308
  metrics.completion_reasoning_tokens = usage.thoughtsTokenCount;
26461
27309
  }
27310
+ for (const detail of usage.promptTokensDetails ?? []) {
27311
+ if (detail.modality === "AUDIO" && detail.tokenCount !== void 0) {
27312
+ metrics.prompt_audio_tokens = (metrics.prompt_audio_tokens ?? 0) + detail.tokenCount;
27313
+ }
27314
+ }
27315
+ for (const detail of usage.candidatesTokensDetails ?? []) {
27316
+ if (detail.modality === "AUDIO" && detail.tokenCount !== void 0) {
27317
+ metrics.completion_audio_tokens = (metrics.completion_audio_tokens ?? 0) + detail.tokenCount;
27318
+ }
27319
+ if (detail.modality === "IMAGE" && detail.tokenCount !== void 0) {
27320
+ metrics.completion_image_tokens = (metrics.completion_image_tokens ?? 0) + detail.tokenCount;
27321
+ }
27322
+ }
26462
27323
  }
26463
27324
  function cleanMetrics4(metrics) {
26464
27325
  const cleaned = {};
@@ -28024,10 +28885,10 @@ var GenkitPlugin = class extends BasePlugin {
28024
28885
  this.subscribeToActionStream();
28025
28886
  }
28026
28887
  subscribeToActionRun() {
28027
- const tracingChannel2 = genkitChannels.actionRun.tracingChannel();
28888
+ const tracingChannel = genkitChannels.actionRun.tracingChannel();
28028
28889
  const states = /* @__PURE__ */ new WeakMap();
28029
28890
  const unbindCurrentSpanStore = bindActionCurrentSpanStoreToStart(
28030
- tracingChannel2,
28891
+ tracingChannel,
28031
28892
  states,
28032
28893
  (event) => startActionRunSpan(event)
28033
28894
  );
@@ -28064,17 +28925,17 @@ var GenkitPlugin = class extends BasePlugin {
28064
28925
  states.delete(event);
28065
28926
  }
28066
28927
  };
28067
- tracingChannel2.subscribe(handlers);
28928
+ tracingChannel.subscribe(handlers);
28068
28929
  this.unsubscribers.push(() => {
28069
28930
  unbindCurrentSpanStore?.();
28070
- tracingChannel2.unsubscribe(handlers);
28931
+ tracingChannel.unsubscribe(handlers);
28071
28932
  });
28072
28933
  }
28073
28934
  subscribeToActionSpan() {
28074
- const tracingChannel2 = genkitCoreChannels.actionSpan.tracingChannel();
28935
+ const tracingChannel = genkitCoreChannels.actionSpan.tracingChannel();
28075
28936
  const states = /* @__PURE__ */ new WeakMap();
28076
28937
  const unbindCurrentSpanStore = bindActionCurrentSpanStoreToStart(
28077
- tracingChannel2,
28938
+ tracingChannel,
28078
28939
  states,
28079
28940
  (event) => startActionSpan(event)
28080
28941
  );
@@ -28112,10 +28973,10 @@ var GenkitPlugin = class extends BasePlugin {
28112
28973
  states.delete(event);
28113
28974
  }
28114
28975
  };
28115
- tracingChannel2.subscribe(handlers);
28976
+ tracingChannel.subscribe(handlers);
28116
28977
  this.unsubscribers.push(() => {
28117
28978
  unbindCurrentSpanStore?.();
28118
- tracingChannel2.unsubscribe(handlers);
28979
+ tracingChannel.unsubscribe(handlers);
28119
28980
  });
28120
28981
  }
28121
28982
  subscribeToActionStream() {
@@ -28184,10 +29045,10 @@ function ensureActionSpanState(states, event, create) {
28184
29045
  }
28185
29046
  return created;
28186
29047
  }
28187
- function bindActionCurrentSpanStoreToStart(tracingChannel2, states, create) {
29048
+ function bindActionCurrentSpanStoreToStart(tracingChannel, states, create) {
28188
29049
  const state = _internalGetGlobalState();
28189
29050
  const contextManager = state?.contextManager;
28190
- const startChannel = tracingChannel2.start;
29051
+ const startChannel = tracingChannel.start;
28191
29052
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
28192
29053
  if (!startChannel?.bindStore || !currentSpanStore) {
28193
29054
  return void 0;
@@ -30549,7 +31410,7 @@ var LangChainPlugin = class extends BasePlugin {
30549
31410
  this.injectedManagers = /* @__PURE__ */ new WeakSet();
30550
31411
  }
30551
31412
  subscribeToConfigure(channel2) {
30552
- const tracingChannel2 = channel2.tracingChannel();
31413
+ const tracingChannel = channel2.tracingChannel();
30553
31414
  const handlers = {
30554
31415
  start: (event) => {
30555
31416
  injectHandlerIntoArguments(event.arguments);
@@ -30558,9 +31419,9 @@ var LangChainPlugin = class extends BasePlugin {
30558
31419
  this.injectHandler(event.result);
30559
31420
  }
30560
31421
  };
30561
- tracingChannel2.subscribe(handlers);
31422
+ tracingChannel.subscribe(handlers);
30562
31423
  this.unsubscribers.push(() => {
30563
- tracingChannel2.unsubscribe(handlers);
31424
+ tracingChannel.unsubscribe(handlers);
30564
31425
  });
30565
31426
  }
30566
31427
  injectHandler(result) {
@@ -30824,7 +31685,7 @@ var LangSmithPlugin = class extends BasePlugin {
30824
31685
  const inputs = preferOwnValue(run, previous, "inputs");
30825
31686
  const outputs = preferOwnValue(run, previous, "outputs");
30826
31687
  const error = errorMessage(preferOwnValue(run, previous, "error"));
30827
- const metadata = extractMetadata(run, previous);
31688
+ const metadata = extractMetadata2(run, previous);
30828
31689
  const tags = extractTags(preferOwnValue(run, previous, "tags"));
30829
31690
  const metrics = extractMetrics(run, previous);
30830
31691
  span.log({
@@ -30929,7 +31790,7 @@ function mapRunType(runType) {
30929
31790
  return "task" /* TASK */;
30930
31791
  }
30931
31792
  }
30932
- function extractMetadata(run, previous) {
31793
+ function extractMetadata2(run, previous) {
30933
31794
  const extra = preferOwnValue(run, previous, "extra");
30934
31795
  const rawMetadata = ownValue(extra, "metadata");
30935
31796
  if (!isRecord2(rawMetadata)) {
@@ -32060,9 +32921,9 @@ var StrandsAgentSDKPlugin = class extends BasePlugin {
32060
32921
  });
32061
32922
  }
32062
32923
  subscribeToMultiAgentStream(channel2, operation) {
32063
- const tracingChannel2 = channel2.tracingChannel();
32924
+ const tracingChannel = channel2.tracingChannel();
32064
32925
  const states = /* @__PURE__ */ new WeakMap();
32065
- const unbindAutoInstrumentationSuppression = bindAutoInstrumentationSuppressionToStart(tracingChannel2);
32926
+ const unbindAutoInstrumentationSuppression = bindAutoInstrumentationSuppressionToStart(tracingChannel);
32066
32927
  const handlers = {
32067
32928
  start: (event) => {
32068
32929
  const state = startMultiAgentStream(
@@ -32116,10 +32977,10 @@ var StrandsAgentSDKPlugin = class extends BasePlugin {
32116
32977
  states.delete(event);
32117
32978
  }
32118
32979
  };
32119
- tracingChannel2.subscribe(handlers);
32980
+ tracingChannel.subscribe(handlers);
32120
32981
  this.unsubscribers.push(() => {
32121
32982
  unbindAutoInstrumentationSuppression?.();
32122
- tracingChannel2.unsubscribe(handlers);
32983
+ tracingChannel.unsubscribe(handlers);
32123
32984
  });
32124
32985
  }
32125
32986
  };
@@ -32302,6 +33163,15 @@ function handleMultiAgentStreamEvent(state, event, activeChildParents) {
32302
33163
  logInstrumentationError5("Strands Agent SDK multi-agent event", error);
32303
33164
  }
32304
33165
  }
33166
+ function buildModelSpanInput(event, attachmentCache) {
33167
+ const systemPrompt = typeof event.agent?.systemPrompt === "string" && event.agent.systemPrompt.length > 0 ? event.agent.systemPrompt : void 0;
33168
+ const processedMessages = Array.isArray(event.agent?.messages) ? processStrandsInputAttachments(event.agent.messages, attachmentCache) : void 0;
33169
+ if (!systemPrompt) {
33170
+ return processedMessages;
33171
+ }
33172
+ const systemMessage = { role: "system", content: systemPrompt };
33173
+ return Array.isArray(processedMessages) ? [systemMessage, ...processedMessages] : [systemMessage];
33174
+ }
32305
33175
  function startModelSpan(state, event) {
32306
33176
  if (state.activeModel) {
32307
33177
  finalizeModelSpan(state);
@@ -32319,10 +33189,7 @@ function startModelSpan(state, event) {
32319
33189
  withSpanInstrumentationName(
32320
33190
  {
32321
33191
  event: {
32322
- input: Array.isArray(event.agent?.messages) ? processStrandsInputAttachments(
32323
- event.agent.messages,
32324
- state.attachmentCache
32325
- ) : void 0,
33192
+ input: buildModelSpanInput(event, state.attachmentCache),
32326
33193
  metadata
32327
33194
  },
32328
33195
  name: formatModelSpanName(model),
@@ -32962,6 +33829,555 @@ function logInstrumentationError5(context, error) {
32962
33829
  debugLogger.debug(`${context}:`, error);
32963
33830
  }
32964
33831
 
33832
+ // src/instrumentation/plugins/cloudflare-ai-chat-channels.ts
33833
+ var cloudflareAIChatChannels = defineChannels(
33834
+ "@cloudflare/ai-chat",
33835
+ {
33836
+ runExclusiveChatTurn: channel({
33837
+ channelName: "AIChatAgent._runExclusiveChatTurn",
33838
+ kind: "async"
33839
+ }),
33840
+ onChatResponse: channel({
33841
+ channelName: "AIChatAgent.onChatResponse",
33842
+ kind: "sync-stream"
33843
+ })
33844
+ },
33845
+ { instrumentationName: INSTRUMENTATION_NAMES.CLOUDFLARE_AI_CHAT }
33846
+ );
33847
+
33848
+ // src/instrumentation/plugins/cloudflare-ai-chat-instrumentation.ts
33849
+ var wrappedTurnRunners = /* @__PURE__ */ new WeakSet();
33850
+ var wrappedResponseHooks = /* @__PURE__ */ new WeakSet();
33851
+ function instrumentCloudflareAIChatAgent(agent) {
33852
+ try {
33853
+ const original = Reflect.get(agent, "_runExclusiveChatTurn");
33854
+ if (typeof original !== "function" || wrappedTurnRunners.has(original)) {
33855
+ return agent;
33856
+ }
33857
+ const wrapped = async function(...args) {
33858
+ return cloudflareAIChatChannels.runExclusiveChatTurn.tracePromise(
33859
+ () => Reflect.apply(original, this, args),
33860
+ {
33861
+ arguments: args,
33862
+ self: this
33863
+ }
33864
+ );
33865
+ };
33866
+ wrappedTurnRunners.add(wrapped);
33867
+ defineWrappedMethod(agent, "_runExclusiveChatTurn", original, wrapped);
33868
+ } catch (error) {
33869
+ debugLogger.debug("Failed to wrap @cloudflare/ai-chat turn runner:", error);
33870
+ }
33871
+ return agent;
33872
+ }
33873
+ function instrumentCloudflareAIChatResponseHook(agent) {
33874
+ try {
33875
+ const original = Reflect.get(agent, "onChatResponse");
33876
+ if (typeof original !== "function" || wrappedResponseHooks.has(original)) {
33877
+ return;
33878
+ }
33879
+ const wrapped = function(result) {
33880
+ const args = [result];
33881
+ return cloudflareAIChatChannels.onChatResponse.traceSync(
33882
+ () => Reflect.apply(original, this, args),
33883
+ {
33884
+ arguments: args,
33885
+ self: this
33886
+ }
33887
+ );
33888
+ };
33889
+ wrappedResponseHooks.add(wrapped);
33890
+ defineWrappedMethod(agent, "onChatResponse", original, wrapped);
33891
+ } catch (error) {
33892
+ debugLogger.debug(
33893
+ "Failed to wrap @cloudflare/ai-chat response hook:",
33894
+ error
33895
+ );
33896
+ }
33897
+ }
33898
+ function defineWrappedMethod(target, property, original, wrapped) {
33899
+ const ownDescriptor = Object.getOwnPropertyDescriptor(target, property);
33900
+ Object.defineProperty(target, property, {
33901
+ configurable: ownDescriptor?.configurable ?? true,
33902
+ enumerable: ownDescriptor?.enumerable ?? false,
33903
+ value: wrapped,
33904
+ writable: ownDescriptor && "writable" in ownDescriptor ? ownDescriptor.writable : true
33905
+ });
33906
+ try {
33907
+ Object.defineProperty(wrapped, "name", {
33908
+ configurable: true,
33909
+ value: original.name
33910
+ });
33911
+ } catch {
33912
+ }
33913
+ }
33914
+
33915
+ // src/instrumentation/plugins/cloudflare-ai-chat-plugin.ts
33916
+ var BLOCKED_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
33917
+ var RESPONSE_STATE_RETENTION_MS = 6e4;
33918
+ var CloudflareAIChatPlugin = class extends BasePlugin {
33919
+ activeStates = /* @__PURE__ */ new Set();
33920
+ activeTurns = /* @__PURE__ */ new WeakMap();
33921
+ eventStates = /* @__PURE__ */ new WeakMap();
33922
+ onEnable() {
33923
+ this.subscribeToResponseHook();
33924
+ this.subscribeToTurnRunner();
33925
+ }
33926
+ onDisable() {
33927
+ for (const unsubscribe of this.unsubscribers) {
33928
+ unsubscribe();
33929
+ }
33930
+ this.unsubscribers = [];
33931
+ for (const state of this.activeStates) {
33932
+ this.cleanupState(state);
33933
+ }
33934
+ this.activeStates.clear();
33935
+ }
33936
+ subscribeToTurnRunner() {
33937
+ const tracingChannel = cloudflareAIChatChannels.runExclusiveChatTurn.tracingChannel();
33938
+ const unbindCurrentSpanStore = this.bindCurrentSpanStore(tracingChannel);
33939
+ const handlers = {
33940
+ start: (event) => {
33941
+ this.ensureEventState(event);
33942
+ },
33943
+ asyncEnd: (event) => {
33944
+ this.finishEvent(event);
33945
+ },
33946
+ error: (event) => {
33947
+ this.finishEvent(event, event.error);
33948
+ }
33949
+ };
33950
+ tracingChannel.subscribe(handlers);
33951
+ this.unsubscribers.push(() => {
33952
+ unbindCurrentSpanStore?.();
33953
+ tracingChannel.unsubscribe(handlers);
33954
+ });
33955
+ }
33956
+ subscribeToResponseHook() {
33957
+ const tracingChannel = cloudflareAIChatChannels.onChatResponse.tracingChannel();
33958
+ const handlers = {
33959
+ start: (event) => {
33960
+ let state;
33961
+ try {
33962
+ const agent = asObject(event.self);
33963
+ const result = event.arguments[0];
33964
+ state = agent ? this.findResponseState(
33965
+ agent,
33966
+ stringValue3(ownValue2(result, "requestId"))
33967
+ ) : void 0;
33968
+ if (!state) {
33969
+ return;
33970
+ }
33971
+ state.responseObserved = true;
33972
+ const output = serializeMessage(ownValue2(result, "message"));
33973
+ const status = stringValue3(ownValue2(result, "status"));
33974
+ const error = ownValue2(result, "error");
33975
+ const input = ownValue2(result, "continuation") === true ? state.input : serializeMessages(readProperty(agent, "messages"))?.filter(
33976
+ (message) => typeof output?.id !== "string" || message.id !== output.id
33977
+ );
33978
+ state.span.log({
33979
+ ...input !== void 0 ? { input } : {},
33980
+ ...output !== void 0 ? { output } : {},
33981
+ ...status === "error" && error !== void 0 ? { error } : {}
33982
+ });
33983
+ } catch (error) {
33984
+ debugLogger.debug(
33985
+ "Failed to process @cloudflare/ai-chat response hook:",
33986
+ error
33987
+ );
33988
+ } finally {
33989
+ if (state?.settled) {
33990
+ this.cleanupState(state);
33991
+ }
33992
+ }
33993
+ }
33994
+ };
33995
+ tracingChannel.subscribe(handlers);
33996
+ this.unsubscribers.push(() => tracingChannel.unsubscribe(handlers));
33997
+ }
33998
+ bindCurrentSpanStore(tracingChannel) {
33999
+ const globalState = _internalGetGlobalState();
34000
+ const contextManager = globalState?.contextManager;
34001
+ const startChannel = tracingChannel.start;
34002
+ const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
34003
+ if (!startChannel || !currentSpanStore || !contextManager) {
34004
+ return void 0;
34005
+ }
34006
+ startChannel.bindStore(currentSpanStore, (event) => {
34007
+ const state = this.ensureEventState(event);
34008
+ return state ? contextManager.wrapSpanForStore(state.span) : currentSpanStore.getStore();
34009
+ });
34010
+ return () => startChannel.unbindStore(currentSpanStore);
34011
+ }
34012
+ ensureEventState(event) {
34013
+ const eventKey = event;
34014
+ const known = this.eventStates.get(eventKey);
34015
+ if (known) {
34016
+ return known;
34017
+ }
34018
+ try {
34019
+ const agent = asObject(event.self);
34020
+ const requestId = stringValue3(event.arguments[0]);
34021
+ const key = requestId ?? /* @__PURE__ */ Symbol("cloudflare-ai-chat-turn");
34022
+ const activeForAgent = agent ? this.getActiveTurns(agent) : void 0;
34023
+ const existing = activeForAgent?.get(key);
34024
+ const state = existing && !existing.settled ? existing : this.createTurnState(agent, key);
34025
+ if (existing && !existing.settled) {
34026
+ state.depth += 1;
34027
+ }
34028
+ this.eventStates.set(eventKey, state);
34029
+ this.bindTurnCallback(event, agent, state);
34030
+ if (agent) {
34031
+ instrumentCloudflareAIChatResponseHook(agent);
34032
+ }
34033
+ return state;
34034
+ } catch (error) {
34035
+ debugLogger.debug(
34036
+ "Failed to start @cloudflare/ai-chat instrumentation:",
34037
+ error
34038
+ );
34039
+ return void 0;
34040
+ }
34041
+ }
34042
+ createTurnState(agent, key) {
34043
+ const span = startSpan(
34044
+ withSpanInstrumentationName(
34045
+ {
34046
+ name: "AIChatAgent.onChatMessage",
34047
+ spanAttributes: { type: "task" /* TASK */ }
34048
+ },
34049
+ INSTRUMENTATION_NAMES.CLOUDFLARE_AI_CHAT
34050
+ )
34051
+ );
34052
+ const state = {
34053
+ agent,
34054
+ depth: 1,
34055
+ ended: false,
34056
+ key,
34057
+ responseObserved: false,
34058
+ settled: false,
34059
+ span
34060
+ };
34061
+ this.activeStates.add(state);
34062
+ if (agent) {
34063
+ this.getActiveTurns(agent).set(key, state);
34064
+ }
34065
+ return state;
34066
+ }
34067
+ bindTurnCallback(event, agent, state) {
34068
+ const callback = event.arguments[1];
34069
+ if (typeof callback !== "function") {
34070
+ return;
34071
+ }
34072
+ try {
34073
+ event.arguments[1] = function(...args) {
34074
+ return withCurrent(state.span, () => {
34075
+ try {
34076
+ const input = serializeMessages(readProperty(agent, "messages"));
34077
+ if (input !== void 0 && state.input === void 0) {
34078
+ state.input = input;
34079
+ state.span.log({ input });
34080
+ }
34081
+ } catch (error) {
34082
+ debugLogger.debug(
34083
+ "Failed to capture @cloudflare/ai-chat messages:",
34084
+ error
34085
+ );
34086
+ }
34087
+ return Reflect.apply(callback, this, args);
34088
+ });
34089
+ };
34090
+ } catch (error) {
34091
+ debugLogger.debug(
34092
+ "Failed to bind @cloudflare/ai-chat turn callback context:",
34093
+ error
34094
+ );
34095
+ }
34096
+ }
34097
+ finishEvent(event, error) {
34098
+ const eventKey = event;
34099
+ const state = this.eventStates.get(eventKey);
34100
+ if (!state || state.ended) {
34101
+ return;
34102
+ }
34103
+ this.eventStates.delete(eventKey);
34104
+ if (error !== void 0 && state.pendingError === void 0) {
34105
+ state.pendingError = error;
34106
+ }
34107
+ state.depth -= 1;
34108
+ if (state.depth === 0) {
34109
+ state.settled = true;
34110
+ this.endState(state);
34111
+ if (state.responseObserved || error !== void 0) {
34112
+ this.cleanupState(state);
34113
+ } else {
34114
+ state.cleanupTimer = setTimeout(
34115
+ () => this.cleanupState(state),
34116
+ RESPONSE_STATE_RETENTION_MS
34117
+ );
34118
+ if (typeof state.cleanupTimer === "object" && state.cleanupTimer !== null && "unref" in state.cleanupTimer && typeof state.cleanupTimer.unref === "function") {
34119
+ state.cleanupTimer.unref();
34120
+ }
34121
+ }
34122
+ }
34123
+ }
34124
+ endState(state) {
34125
+ if (state.ended) {
34126
+ return;
34127
+ }
34128
+ state.ended = true;
34129
+ try {
34130
+ if (state.pendingError !== void 0) {
34131
+ state.span.log({ error: state.pendingError });
34132
+ }
34133
+ } finally {
34134
+ state.span.end();
34135
+ }
34136
+ }
34137
+ cleanupState(state) {
34138
+ if (state.cleanupTimer !== void 0) {
34139
+ clearTimeout(state.cleanupTimer);
34140
+ state.cleanupTimer = void 0;
34141
+ }
34142
+ try {
34143
+ this.endState(state);
34144
+ } finally {
34145
+ this.activeStates.delete(state);
34146
+ if (state.agent) {
34147
+ const activeForAgent = this.activeTurns.get(state.agent);
34148
+ if (activeForAgent?.get(state.key) === state) {
34149
+ activeForAgent.delete(state.key);
34150
+ }
34151
+ }
34152
+ }
34153
+ }
34154
+ getActiveTurns(agent) {
34155
+ let turns = this.activeTurns.get(agent);
34156
+ if (!turns) {
34157
+ turns = /* @__PURE__ */ new Map();
34158
+ this.activeTurns.set(agent, turns);
34159
+ }
34160
+ return turns;
34161
+ }
34162
+ findResponseState(agent, requestId) {
34163
+ const turns = this.activeTurns.get(agent);
34164
+ if (!turns) {
34165
+ return void 0;
34166
+ }
34167
+ if (requestId !== void 0) {
34168
+ return turns.get(requestId);
34169
+ }
34170
+ const active = [...turns.values()];
34171
+ return active.length === 1 ? active[0] : void 0;
34172
+ }
34173
+ };
34174
+ function asObject(value) {
34175
+ return value !== null && (typeof value === "object" || typeof value === "function") ? value : void 0;
34176
+ }
34177
+ function readProperty(value, key) {
34178
+ const object = asObject(value);
34179
+ return object ? Reflect.get(object, key) : void 0;
34180
+ }
34181
+ function ownValue2(value, key) {
34182
+ const object = asObject(value);
34183
+ if (!object) {
34184
+ return void 0;
34185
+ }
34186
+ const descriptor = Object.getOwnPropertyDescriptor(object, key);
34187
+ return descriptor && "value" in descriptor ? descriptor.value : void 0;
34188
+ }
34189
+ function stringValue3(value) {
34190
+ return typeof value === "string" ? value : void 0;
34191
+ }
34192
+ function serializeMessages(value) {
34193
+ if (!Array.isArray(value)) {
34194
+ return void 0;
34195
+ }
34196
+ return value.flatMap((message) => {
34197
+ const serialized = serializeMessage(message);
34198
+ return serialized === void 0 ? [] : [serialized];
34199
+ });
34200
+ }
34201
+ function serializeMessage(value) {
34202
+ const message = asObject(value);
34203
+ if (!message) {
34204
+ return void 0;
34205
+ }
34206
+ const serialized = [];
34207
+ const id = ownValue2(message, "id");
34208
+ const role = ownValue2(message, "role");
34209
+ const parts = ownValue2(message, "parts");
34210
+ if (typeof id === "string") {
34211
+ serialized.push(["id", id]);
34212
+ }
34213
+ if (typeof role === "string") {
34214
+ serialized.push(["role", role]);
34215
+ }
34216
+ const sanitizedParts = sanitizeLoggedValue2(parts);
34217
+ if (sanitizedParts !== void 0) {
34218
+ serialized.push(["parts", sanitizedParts]);
34219
+ }
34220
+ return serialized.length > 0 ? Object.fromEntries(serialized) : void 0;
34221
+ }
34222
+ function sanitizeLoggedValue2(value, seen = /* @__PURE__ */ new WeakSet(), depth = 0) {
34223
+ if (value === null || typeof value === "string" || typeof value === "boolean") {
34224
+ return value;
34225
+ }
34226
+ if (typeof value === "number") {
34227
+ return Number.isFinite(value) ? value : void 0;
34228
+ }
34229
+ const object = asObject(value);
34230
+ if (!object || depth >= 20 || typeof value === "function") {
34231
+ return void 0;
34232
+ }
34233
+ if (seen.has(object)) {
34234
+ return "[Circular]";
34235
+ }
34236
+ seen.add(object);
34237
+ if (Array.isArray(value)) {
34238
+ return value.map((entry) => sanitizeLoggedValue2(entry, seen, depth + 1));
34239
+ }
34240
+ const entries = [];
34241
+ for (const [key, descriptor] of Object.entries(
34242
+ Object.getOwnPropertyDescriptors(object)
34243
+ )) {
34244
+ if (BLOCKED_KEYS.has(key) || !descriptor.enumerable || !("value" in descriptor)) {
34245
+ continue;
34246
+ }
34247
+ const sanitized = sanitizeLoggedValue2(descriptor.value, seen, depth + 1);
34248
+ if (sanitized !== void 0) {
34249
+ entries.push([key, sanitized]);
34250
+ }
34251
+ }
34252
+ return Object.fromEntries(entries);
34253
+ }
34254
+
34255
+ // src/instrumentation/plugins/cloudflare-agents-channels.ts
34256
+ var cloudflareAgentsChannels = defineChannels(
34257
+ "agents",
34258
+ {
34259
+ runAgentTool: channel({
34260
+ channelName: "Agent.runAgentTool",
34261
+ kind: "async"
34262
+ })
34263
+ },
34264
+ { instrumentationName: INSTRUMENTATION_NAMES.CLOUDFLARE_AGENTS }
34265
+ );
34266
+
34267
+ // src/instrumentation/plugins/cloudflare-agents-plugin.ts
34268
+ var CLOUDFLARE_WORKERS_CONTEXT = {
34269
+ span_origin: {
34270
+ environment: { type: "server", name: "cloudflare_workers" }
34271
+ }
34272
+ };
34273
+ var CloudflareAgentsPlugin = class extends BasePlugin {
34274
+ onEnable() {
34275
+ const channel2 = cloudflareAgentsChannels.runAgentTool.tracingChannel();
34276
+ const spans = /* @__PURE__ */ new WeakMap();
34277
+ const handlers = {
34278
+ start: (event) => {
34279
+ try {
34280
+ const agentClass = event.arguments[0];
34281
+ const options = event.arguments[1];
34282
+ if (ownValue3(options, "detached")) {
34283
+ return;
34284
+ }
34285
+ const name = ownValue3(agentClass, "name");
34286
+ if (typeof name !== "string" || name.length === 0) {
34287
+ debugLogger.warn(
34288
+ "Skipping Cloudflare Agents runAgentTool span because the child agent class has no name."
34289
+ );
34290
+ return;
34291
+ }
34292
+ const span = _internalStartSpanWithContext(
34293
+ withSpanInstrumentationName(
34294
+ {
34295
+ name,
34296
+ spanAttributes: { type: "tool" /* TOOL */ },
34297
+ event: {
34298
+ input: ownValue3(options, "input")
34299
+ }
34300
+ },
34301
+ INSTRUMENTATION_NAMES.CLOUDFLARE_AGENTS
34302
+ ),
34303
+ CLOUDFLARE_WORKERS_CONTEXT
34304
+ );
34305
+ spans.set(event, span);
34306
+ } catch (error) {
34307
+ logInstrumentationError6("start", error);
34308
+ }
34309
+ },
34310
+ asyncEnd: (event) => {
34311
+ const span = spans.get(event);
34312
+ if (!span) {
34313
+ return;
34314
+ }
34315
+ spans.delete(event);
34316
+ try {
34317
+ const status = ownValue3(event.result, "status");
34318
+ if (status === "completed") {
34319
+ span.log({ output: ownValue3(event.result, "output") });
34320
+ } else {
34321
+ const error = ownValue3(event.result, "error");
34322
+ if (typeof error === "string") {
34323
+ span.log({ error });
34324
+ }
34325
+ }
34326
+ } catch (error) {
34327
+ logInstrumentationError6("completion", error);
34328
+ } finally {
34329
+ safelyEndSpan(span);
34330
+ }
34331
+ },
34332
+ error: (event) => {
34333
+ const span = spans.get(event);
34334
+ if (!span) {
34335
+ return;
34336
+ }
34337
+ spans.delete(event);
34338
+ try {
34339
+ span.log({ error: event.error });
34340
+ } catch (error) {
34341
+ logInstrumentationError6("rejection", error);
34342
+ } finally {
34343
+ safelyEndSpan(span);
34344
+ }
34345
+ }
34346
+ };
34347
+ channel2.subscribe(handlers);
34348
+ this.unsubscribers.push(() => channel2.unsubscribe(handlers));
34349
+ }
34350
+ onDisable() {
34351
+ for (const unsubscribe of this.unsubscribers) {
34352
+ unsubscribe();
34353
+ }
34354
+ this.unsubscribers = [];
34355
+ }
34356
+ };
34357
+ function ownValue3(value, key) {
34358
+ if (!isObjectLike2(value)) {
34359
+ return void 0;
34360
+ }
34361
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
34362
+ return descriptor && "value" in descriptor ? descriptor.value : void 0;
34363
+ }
34364
+ function isObjectLike2(value) {
34365
+ return typeof value === "object" && value !== null || typeof value === "function";
34366
+ }
34367
+ function safelyEndSpan(span) {
34368
+ try {
34369
+ span.end();
34370
+ } catch (error) {
34371
+ logInstrumentationError6("span end", error);
34372
+ }
34373
+ }
34374
+ function logInstrumentationError6(operation, error) {
34375
+ debugLogger.error(
34376
+ `Failed to process Cloudflare Agents ${operation} instrumentation:`,
34377
+ error
34378
+ );
34379
+ }
34380
+
32965
34381
  // src/instrumentation/braintrust-plugin.ts
32966
34382
  var BraintrustPlugin = class extends BasePlugin {
32967
34383
  config;
@@ -32974,6 +34390,7 @@ var BraintrustPlugin = class extends BasePlugin {
32974
34390
  openAIAgentsPlugin = null;
32975
34391
  googleGenAIPlugin = null;
32976
34392
  huggingFacePlugin = null;
34393
+ huggingFaceTransformersPlugin = null;
32977
34394
  openRouterPlugin = null;
32978
34395
  openRouterAgentPlugin = null;
32979
34396
  mistralPlugin = null;
@@ -32988,6 +34405,8 @@ var BraintrustPlugin = class extends BasePlugin {
32988
34405
  langSmithPlugin = null;
32989
34406
  piCodingAgentPlugin = null;
32990
34407
  strandsAgentSDKPlugin = null;
34408
+ cloudflareAIChatPlugin = null;
34409
+ cloudflareAgentsPlugin = null;
32991
34410
  constructor(config = {}) {
32992
34411
  super();
32993
34412
  this.config = config;
@@ -33029,6 +34448,8 @@ var BraintrustPlugin = class extends BasePlugin {
33029
34448
  if (integrations.huggingface !== false) {
33030
34449
  this.huggingFacePlugin = new HuggingFacePlugin();
33031
34450
  this.huggingFacePlugin.enable();
34451
+ this.huggingFaceTransformersPlugin = new HuggingFaceTransformersPlugin();
34452
+ this.huggingFaceTransformersPlugin.enable();
33032
34453
  }
33033
34454
  if (integrations.openrouter !== false) {
33034
34455
  this.openRouterPlugin = new OpenRouterPlugin();
@@ -33074,6 +34495,14 @@ var BraintrustPlugin = class extends BasePlugin {
33074
34495
  this.strandsAgentSDKPlugin = new StrandsAgentSDKPlugin();
33075
34496
  this.strandsAgentSDKPlugin.enable();
33076
34497
  }
34498
+ if (integrations.cloudflareAIChat !== false) {
34499
+ this.cloudflareAIChatPlugin = new CloudflareAIChatPlugin();
34500
+ this.cloudflareAIChatPlugin.enable();
34501
+ }
34502
+ if (integrations.cloudflareAgents !== false) {
34503
+ this.cloudflareAgentsPlugin = new CloudflareAgentsPlugin();
34504
+ this.cloudflareAgentsPlugin.enable();
34505
+ }
33077
34506
  if (integrations.flue !== false) {
33078
34507
  this.fluePlugin = new FluePlugin();
33079
34508
  this.fluePlugin.enable();
@@ -33126,6 +34555,10 @@ var BraintrustPlugin = class extends BasePlugin {
33126
34555
  this.huggingFacePlugin.disable();
33127
34556
  this.huggingFacePlugin = null;
33128
34557
  }
34558
+ if (this.huggingFaceTransformersPlugin) {
34559
+ this.huggingFaceTransformersPlugin.disable();
34560
+ this.huggingFaceTransformersPlugin = null;
34561
+ }
33129
34562
  if (this.openRouterPlugin) {
33130
34563
  this.openRouterPlugin.disable();
33131
34564
  this.openRouterPlugin = null;
@@ -33170,6 +34603,14 @@ var BraintrustPlugin = class extends BasePlugin {
33170
34603
  this.strandsAgentSDKPlugin.disable();
33171
34604
  this.strandsAgentSDKPlugin = null;
33172
34605
  }
34606
+ if (this.cloudflareAIChatPlugin) {
34607
+ this.cloudflareAIChatPlugin.disable();
34608
+ this.cloudflareAIChatPlugin = null;
34609
+ }
34610
+ if (this.cloudflareAgentsPlugin) {
34611
+ this.cloudflareAgentsPlugin.disable();
34612
+ this.cloudflareAgentsPlugin = null;
34613
+ }
33173
34614
  if (this.fluePlugin) {
33174
34615
  this.fluePlugin.disable();
33175
34616
  this.fluePlugin = null;
@@ -33202,6 +34643,9 @@ var envIntegrationAliases = {
33202
34643
  strandsagentsdk: "strandsAgentSDK",
33203
34644
  "strands-agent-sdk": "strandsAgentSDK",
33204
34645
  "@strands-agents/sdk": "strandsAgentSDK",
34646
+ agents: "cloudflareAgents",
34647
+ "cloudflare-agents": "cloudflareAgents",
34648
+ cloudflareagents: "cloudflareAgents",
33205
34649
  anthropic: "anthropic",
33206
34650
  aisdk: "aisdk",
33207
34651
  "ai-sdk": "aisdk",
@@ -33209,6 +34653,9 @@ var envIntegrationAliases = {
33209
34653
  vercel: "vercel",
33210
34654
  claudeagentsdk: "claudeAgentSDK",
33211
34655
  "claude-agent-sdk": "claudeAgentSDK",
34656
+ cloudflareaichat: "cloudflareAIChat",
34657
+ "cloudflare-ai-chat": "cloudflareAIChat",
34658
+ "@cloudflare/ai-chat": "cloudflareAIChat",
33212
34659
  cursor: "cursor",
33213
34660
  "cursor-sdk": "cursorSDK",
33214
34661
  cursorsdk: "cursorSDK",
@@ -33223,6 +34670,8 @@ var envIntegrationAliases = {
33223
34670
  "google-genai": "googleGenAI",
33224
34671
  googlegenai: "googleGenAI",
33225
34672
  huggingface: "huggingface",
34673
+ "@huggingface/transformers": "huggingface",
34674
+ transformers: "huggingface",
33226
34675
  openrouter: "openrouter",
33227
34676
  openrouteragent: "openrouterAgent",
33228
34677
  "openrouter-agent": "openrouterAgent",
@@ -33261,6 +34710,7 @@ function getDefaultInstrumentationIntegrations() {
33261
34710
  googleADK: true,
33262
34711
  huggingface: true,
33263
34712
  claudeAgentSDK: true,
34713
+ cloudflareAIChat: true,
33264
34714
  cursor: true,
33265
34715
  cursorSDK: true,
33266
34716
  flue: true,
@@ -33280,7 +34730,8 @@ function getDefaultInstrumentationIntegrations() {
33280
34730
  langgraph: true,
33281
34731
  langsmith: true,
33282
34732
  piCodingAgent: true,
33283
- strandsAgentSDK: true
34733
+ strandsAgentSDK: true,
34734
+ cloudflareAgents: true
33284
34735
  };
33285
34736
  }
33286
34737
  function readDisabledInstrumentationEnvConfig(disabledList) {
@@ -33298,7 +34749,9 @@ function readDisabledInstrumentationEnvConfig(disabledList) {
33298
34749
  }
33299
34750
 
33300
34751
  // src/instrumentation/registry.ts
33301
- var REGISTRY_STATE_KEY = /* @__PURE__ */ Symbol.for("braintrust.registry");
34752
+ var REGISTRY_STATE_KEY = /* @__PURE__ */ Symbol.for(
34753
+ `braintrust.registry.global-hooks.v${GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION}`
34754
+ );
33302
34755
  function getSharedState() {
33303
34756
  const state = globalThis[/* @__PURE__ */ Symbol.for("braintrust-state")];
33304
34757
  return state && typeof state === "object" ? state : void 0;
@@ -33392,92 +34845,6 @@ function configureInstrumentation(config) {
33392
34845
  registry.configure(config);
33393
34846
  }
33394
34847
 
33395
- // src/auto-instrumentations/patch-tracing-channel.ts
33396
- function patchTracingChannel(tracingChannelFn) {
33397
- const dummyChannel = tracingChannelFn("__braintrust_probe__");
33398
- const TracingChannel = dummyChannel?.constructor;
33399
- if (!TracingChannel?.prototype) {
33400
- return;
33401
- }
33402
- if (!Object.getOwnPropertyDescriptor(TracingChannel.prototype, "hasSubscribers")) {
33403
- Object.defineProperty(TracingChannel.prototype, "hasSubscribers", {
33404
- configurable: true,
33405
- enumerable: false,
33406
- get() {
33407
- return Boolean(
33408
- this.start?.hasSubscribers || this.end?.hasSubscribers || this.asyncStart?.hasSubscribers || this.asyncEnd?.hasSubscribers || this.error?.hasSubscribers
33409
- );
33410
- }
33411
- });
33412
- }
33413
- if (TracingChannel.prototype.tracePromise) {
33414
- TracingChannel.prototype.tracePromise = function(fn, context = {}, thisArg, ...args) {
33415
- const start = this.start;
33416
- const end = this.end;
33417
- const asyncStart = this.asyncStart;
33418
- const asyncEnd = this.asyncEnd;
33419
- const error = this.error;
33420
- function publishRejected(err) {
33421
- context.error = err;
33422
- error?.publish(context);
33423
- asyncStart?.publish(context);
33424
- asyncEnd?.publish(context);
33425
- }
33426
- function publishResolved(result) {
33427
- context.result = result;
33428
- asyncStart?.publish(context);
33429
- asyncEnd?.publish(context);
33430
- }
33431
- return start.runStores(context, () => {
33432
- try {
33433
- const result = Reflect.apply(fn, thisArg, args);
33434
- end?.publish(context);
33435
- if (result && (typeof result === "object" || typeof result === "function") && typeof result.then === "function") {
33436
- if (result.constructor === Promise) {
33437
- return result.then(
33438
- (res) => {
33439
- publishResolved(res);
33440
- return res;
33441
- },
33442
- (err) => {
33443
- publishRejected(err);
33444
- return Promise.reject(err);
33445
- }
33446
- );
33447
- }
33448
- void result.then(
33449
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
33450
- (resolved) => {
33451
- try {
33452
- publishResolved(resolved);
33453
- } catch {
33454
- }
33455
- },
33456
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
33457
- (err) => {
33458
- try {
33459
- publishRejected(err);
33460
- } catch {
33461
- }
33462
- }
33463
- );
33464
- return result;
33465
- }
33466
- context.result = result;
33467
- asyncStart?.publish(context);
33468
- asyncEnd?.publish(context);
33469
- return result;
33470
- } catch (err) {
33471
- context.error = err;
33472
- error?.publish(context);
33473
- end?.publish(context);
33474
- throw err;
33475
- }
33476
- });
33477
- };
33478
- }
33479
- }
33480
-
33481
34848
  // src/browser/config.ts
33482
34849
  var browserConfigured = false;
33483
34850
  function configureBrowser() {
@@ -33491,8 +34858,6 @@ function configureBrowser() {
33491
34858
  }
33492
34859
  } catch {
33493
34860
  }
33494
- isomorph_default.newTracingChannel = (nameOrChannels) => (0, import_dc_browser.tracingChannel)(nameOrChannels);
33495
- patchTracingChannel(import_dc_browser.tracingChannel);
33496
34861
  isomorph_default.getEnv = (name) => {
33497
34862
  if (typeof process === "undefined" || typeof process.env === "undefined") {
33498
34863
  return void 0;
@@ -33667,6 +35032,8 @@ __export(exports_exports, {
33667
35032
  wrapAnthropic: () => wrapAnthropic,
33668
35033
  wrapBedrockRuntime: () => wrapBedrockRuntime,
33669
35034
  wrapClaudeAgentSDK: () => wrapClaudeAgentSDK,
35035
+ wrapCloudflareAIChat: () => wrapCloudflareAIChat,
35036
+ wrapCloudflareAgent: () => wrapCloudflareAgent,
33670
35037
  wrapCohere: () => wrapCohere,
33671
35038
  wrapCopilotClient: () => wrapCopilotClient,
33672
35039
  wrapCursorSDK: () => wrapCursorSDK,
@@ -33675,6 +35042,7 @@ __export(exports_exports, {
33675
35042
  wrapGoogleGenAI: () => wrapGoogleGenAI,
33676
35043
  wrapGroq: () => wrapGroq,
33677
35044
  wrapHuggingFace: () => wrapHuggingFace,
35045
+ wrapHuggingFaceTransformers: () => wrapHuggingFaceTransformers,
33678
35046
  wrapLangSmithClient: () => wrapLangSmithClient,
33679
35047
  wrapLangSmithRunTrees: () => wrapLangSmithRunTrees,
33680
35048
  wrapLangSmithTraceable: () => wrapLangSmithTraceable,
@@ -34998,7 +36366,7 @@ function extractToolCallsFromBlocks(blocks) {
34998
36366
  if (!Array.isArray(blocks)) return [];
34999
36367
  return extractToolCallsFromSteps([{ content: blocks }]);
35000
36368
  }
35001
- function extractInput(params) {
36369
+ function extractInput2(params) {
35002
36370
  return params?.prompt ?? params?.messages ?? params?.system;
35003
36371
  }
35004
36372
  var V2_EXCLUDE_KEYS = /* @__PURE__ */ new Set([
@@ -35020,7 +36388,7 @@ function BraintrustMiddleware(config = {}) {
35020
36388
  params,
35021
36389
  model: modelFromWrapGenerate
35022
36390
  }) => {
35023
- const rawInput = extractInput(params);
36391
+ const rawInput = extractInput2(params);
35024
36392
  const processedInput = processInputAttachments(rawInput);
35025
36393
  const spanArgs = {
35026
36394
  name: config.spanInfo?.name || "ai-sdk.doGenerate",
@@ -35084,7 +36452,7 @@ function BraintrustMiddleware(config = {}) {
35084
36452
  }
35085
36453
  },
35086
36454
  wrapStream: async ({ doStream, params }) => {
35087
- const rawInput = extractInput(params);
36455
+ const rawInput = extractInput2(params);
35088
36456
  const processedInput = processInputAttachments(rawInput);
35089
36457
  const spanArgs = {
35090
36458
  name: config.spanInfo?.name || "ai-sdk.doStream",
@@ -37606,6 +38974,67 @@ function patchAgentSessionClass(AgentSession) {
37606
38974
  });
37607
38975
  }
37608
38976
 
38977
+ // src/wrappers/cloudflare-agent.ts
38978
+ var WRAPPED_RUN_AGENT_TOOL = /* @__PURE__ */ Symbol.for(
38979
+ "braintrust.cloudflare-agents.wrapped-run-agent-tool"
38980
+ );
38981
+ function wrapCloudflareAgent(Agent2) {
38982
+ if (typeof Agent2 !== "function") {
38983
+ warnUnsupportedAgent();
38984
+ return Agent2;
38985
+ }
38986
+ const prototypeDescriptor = Object.getOwnPropertyDescriptor(
38987
+ Agent2,
38988
+ "prototype"
38989
+ );
38990
+ const prototype = prototypeDescriptor && "value" in prototypeDescriptor ? prototypeDescriptor.value : void 0;
38991
+ if (!isObjectLike3(prototype)) {
38992
+ warnUnsupportedAgent();
38993
+ return Agent2;
38994
+ }
38995
+ if (ownValue4(prototype, WRAPPED_RUN_AGENT_TOOL) === true) {
38996
+ return Agent2;
38997
+ }
38998
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, "runAgentTool");
38999
+ if (!descriptor || typeof descriptor.value !== "function") {
39000
+ warnUnsupportedAgent();
39001
+ return Agent2;
39002
+ }
39003
+ const originalRunAgentTool = descriptor.value;
39004
+ Object.defineProperty(prototype, "runAgentTool", {
39005
+ ...descriptor,
39006
+ value: function wrappedRunAgentTool(...args) {
39007
+ const options = args[1];
39008
+ if (ownValue4(options, "detached")) {
39009
+ return Reflect.apply(originalRunAgentTool, this, args);
39010
+ }
39011
+ return cloudflareAgentsChannels.runAgentTool.tracePromise(
39012
+ () => Reflect.apply(originalRunAgentTool, this, args),
39013
+ { arguments: args, self: this }
39014
+ );
39015
+ }
39016
+ });
39017
+ Object.defineProperty(prototype, WRAPPED_RUN_AGENT_TOOL, {
39018
+ configurable: false,
39019
+ enumerable: false,
39020
+ value: true
39021
+ });
39022
+ return Agent2;
39023
+ }
39024
+ function ownValue4(value, key) {
39025
+ if (!isObjectLike3(value)) {
39026
+ return void 0;
39027
+ }
39028
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
39029
+ return descriptor && "value" in descriptor ? descriptor.value : void 0;
39030
+ }
39031
+ function isObjectLike3(value) {
39032
+ return typeof value === "object" && value !== null || typeof value === "function";
39033
+ }
39034
+ function warnUnsupportedAgent() {
39035
+ debugLogger.warn("Unsupported Cloudflare Agents Agent class. Not wrapping.");
39036
+ }
39037
+
37609
39038
  // src/wrappers/strands-agent-sdk.ts
37610
39039
  var WRAPPED_CLASS = /* @__PURE__ */ Symbol.for("braintrust.strands-agent-sdk.wrapped-class");
37611
39040
  var WRAPPED_INSTANCE = /* @__PURE__ */ Symbol.for(
@@ -37774,6 +39203,81 @@ async function consumeAsyncGenerator(generator) {
37774
39203
  return result.value;
37775
39204
  }
37776
39205
 
39206
+ // src/wrappers/cloudflare-ai-chat.ts
39207
+ var wrappedClasses = /* @__PURE__ */ new WeakMap();
39208
+ function wrapCloudflareAIChat(module2) {
39209
+ if (!module2 || typeof module2 !== "object") {
39210
+ return module2;
39211
+ }
39212
+ const candidate = module2;
39213
+ let AIChatAgent;
39214
+ try {
39215
+ AIChatAgent = Reflect.get(candidate, "AIChatAgent");
39216
+ } catch (error) {
39217
+ debugLogger.debug("Failed to inspect @cloudflare/ai-chat module:", error);
39218
+ return module2;
39219
+ }
39220
+ if (typeof AIChatAgent !== "function") {
39221
+ debugLogger.warn(
39222
+ "Unsupported @cloudflare/ai-chat module. AIChatAgent was not found; not wrapping."
39223
+ );
39224
+ return module2;
39225
+ }
39226
+ const target = isModuleNamespace5(module2) ? Object.setPrototypeOf({}, module2) : candidate;
39227
+ return new Proxy(target, {
39228
+ get(target2, property, receiver) {
39229
+ const value = Reflect.get(target2, property, receiver);
39230
+ if (property === "AIChatAgent" && typeof value === "function") {
39231
+ return wrapAIChatAgentClass(
39232
+ value
39233
+ );
39234
+ }
39235
+ return value;
39236
+ }
39237
+ });
39238
+ }
39239
+ function wrapAIChatAgentClass(AgentClass) {
39240
+ const cached = wrappedClasses.get(AgentClass);
39241
+ if (cached) {
39242
+ return cached;
39243
+ }
39244
+ const wrapped = new Proxy(AgentClass, {
39245
+ get(target, property) {
39246
+ const value = Reflect.get(target, property, target);
39247
+ return typeof value === "function" ? value.bind(target) : value;
39248
+ },
39249
+ construct(target, args, newTarget) {
39250
+ const instance = Reflect.construct(
39251
+ target,
39252
+ args,
39253
+ newTarget
39254
+ );
39255
+ return instrumentCloudflareAIChatAgent(instance);
39256
+ }
39257
+ });
39258
+ wrappedClasses.set(AgentClass, wrapped);
39259
+ wrappedClasses.set(wrapped, wrapped);
39260
+ return wrapped;
39261
+ }
39262
+ function isModuleNamespace5(value) {
39263
+ if (!value || typeof value !== "object") {
39264
+ return false;
39265
+ }
39266
+ try {
39267
+ if (Reflect.get(value, Symbol.toStringTag) === "Module") {
39268
+ return true;
39269
+ }
39270
+ const keys = Object.keys(value);
39271
+ if (keys.length === 0) {
39272
+ return false;
39273
+ }
39274
+ const descriptor = Object.getOwnPropertyDescriptor(value, keys[0]);
39275
+ return descriptor ? !descriptor.configurable && !descriptor.writable : false;
39276
+ } catch {
39277
+ return false;
39278
+ }
39279
+ }
39280
+
37777
39281
  // src/wrappers/google-genai.ts
37778
39282
  function wrapGoogleGenAI(googleGenAI) {
37779
39283
  if (!googleGenAI || typeof googleGenAI !== "object") {
@@ -38426,6 +39930,120 @@ function wrapFeatureExtraction(original, endpointUrl) {
38426
39930
  };
38427
39931
  }
38428
39932
 
39933
+ // src/wrappers/huggingface-transformers.ts
39934
+ var PIPELINE_CONSTRUCTOR_KEYS = /* @__PURE__ */ new Set([
39935
+ "TextGenerationPipeline",
39936
+ "Text2TextGenerationPipeline",
39937
+ "SummarizationPipeline",
39938
+ "FeatureExtractionPipeline",
39939
+ "QuestionAnsweringPipeline"
39940
+ ]);
39941
+ var wrappedValues = /* @__PURE__ */ new WeakMap();
39942
+ function wrapHuggingFaceTransformers(transformers) {
39943
+ const pipelineTask = transformers?.task;
39944
+ if (typeof transformers === "function" && isSupportedHuggingFaceTransformersTask(pipelineTask)) {
39945
+ return wrapPipeline(transformers);
39946
+ }
39947
+ if (!isSupportedModule(transformers)) {
39948
+ return transformers;
39949
+ }
39950
+ const existing = wrappedValues.get(transformers);
39951
+ if (existing) {
39952
+ return existing;
39953
+ }
39954
+ const proxy = new Proxy(Object.create(transformers), {
39955
+ get(_target, property, receiver) {
39956
+ const value = Reflect.get(transformers, property, receiver);
39957
+ if (property === "pipeline" && typeof value === "function") {
39958
+ return wrapPipelineFactory(value);
39959
+ }
39960
+ if (typeof property === "string" && PIPELINE_CONSTRUCTOR_KEYS.has(property) && typeof value === "function") {
39961
+ return wrapPipelineConstructor(
39962
+ value
39963
+ );
39964
+ }
39965
+ return value;
39966
+ }
39967
+ });
39968
+ wrappedValues.set(transformers, proxy);
39969
+ wrappedValues.set(proxy, proxy);
39970
+ return proxy;
39971
+ }
39972
+ function isSupportedModule(value) {
39973
+ if (value === null || typeof value !== "object" && typeof value !== "function") {
39974
+ return false;
39975
+ }
39976
+ if (typeof Reflect.get(value, "pipeline") === "function") {
39977
+ return true;
39978
+ }
39979
+ for (const key of PIPELINE_CONSTRUCTOR_KEYS) {
39980
+ if (typeof Reflect.get(value, key) === "function") {
39981
+ return true;
39982
+ }
39983
+ }
39984
+ return false;
39985
+ }
39986
+ function wrapPipelineFactory(factory) {
39987
+ const existing = wrappedValues.get(factory);
39988
+ if (existing) {
39989
+ return existing;
39990
+ }
39991
+ const wrapped = function(...args) {
39992
+ const [task] = args;
39993
+ const context = {
39994
+ arguments: args
39995
+ };
39996
+ return huggingFaceTransformersChannels.pipeline.tracePromise(() => Reflect.apply(factory, this, args), context).then((pipeline) => {
39997
+ if (isSupportedHuggingFaceTransformersTask(pipeline.task ?? task)) {
39998
+ return wrapPipeline(pipeline);
39999
+ }
40000
+ return pipeline;
40001
+ });
40002
+ };
40003
+ wrappedValues.set(factory, wrapped);
40004
+ wrappedValues.set(wrapped, wrapped);
40005
+ return wrapped;
40006
+ }
40007
+ function wrapPipelineConstructor(constructor) {
40008
+ const existing = wrappedValues.get(constructor);
40009
+ if (existing) {
40010
+ return existing;
40011
+ }
40012
+ const proxy = new Proxy(constructor, {
40013
+ construct(target, args, newTarget) {
40014
+ const pipeline = Reflect.construct(target, args, newTarget);
40015
+ if (isSupportedHuggingFaceTransformersTask(pipeline.task)) {
40016
+ return wrapPipeline(pipeline);
40017
+ }
40018
+ return pipeline;
40019
+ }
40020
+ });
40021
+ wrappedValues.set(constructor, proxy);
40022
+ wrappedValues.set(proxy, proxy);
40023
+ return proxy;
40024
+ }
40025
+ function wrapPipeline(pipeline) {
40026
+ const existing = wrappedValues.get(pipeline);
40027
+ if (existing) {
40028
+ return existing;
40029
+ }
40030
+ const proxy = new Proxy(pipeline, {
40031
+ apply(target, thisArg, args) {
40032
+ const context = {
40033
+ arguments: args,
40034
+ self: target
40035
+ };
40036
+ return huggingFaceTransformersChannels.pipelineCall.tracePromise(
40037
+ () => Reflect.apply(target, thisArg, args),
40038
+ context
40039
+ );
40040
+ }
40041
+ });
40042
+ wrappedValues.set(pipeline, proxy);
40043
+ wrappedValues.set(proxy, proxy);
40044
+ return proxy;
40045
+ }
40046
+
38429
40047
  // src/wrappers/openrouter-agent.ts
38430
40048
  function wrapOpenRouterAgent(agent) {
38431
40049
  const candidate = agent;
@@ -39142,7 +40760,7 @@ function wrapNamespaceExport(namespace, exportName, marker, wrap2) {
39142
40760
  );
39143
40761
  return namespace;
39144
40762
  }
39145
- const target = isModuleNamespace5(namespace) ? Object.setPrototypeOf({}, namespace) : candidate;
40763
+ const target = isModuleNamespace6(namespace) ? Object.setPrototypeOf({}, namespace) : candidate;
39146
40764
  const moduleNamespace = target !== candidate;
39147
40765
  let wrappedExport;
39148
40766
  return new Proxy(target, {
@@ -39176,7 +40794,7 @@ function wrapNamespaceExport(namespace, exportName, marker, wrap2) {
39176
40794
  }
39177
40795
  });
39178
40796
  }
39179
- function isModuleNamespace5(value) {
40797
+ function isModuleNamespace6(value) {
39180
40798
  if (!value || typeof value !== "object") {
39181
40799
  return false;
39182
40800
  }