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
@@ -177,6 +177,8 @@ __export(edge_light_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(edge_light_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,84 +205,528 @@ __export(edge_light_exports, {
202
205
  });
203
206
  module.exports = __toCommonJS(edge_light_exports);
204
207
 
205
- // src/isomorph.ts
206
- var DefaultAsyncLocalStorage = class {
207
- constructor() {
208
- }
209
- enterWith(_) {
210
- }
211
- run(_, callback) {
212
- 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 {
213
229
  }
214
- getStore() {
215
- return void 0;
230
+ }
231
+ function setContextValue(context, key, value) {
232
+ try {
233
+ context[key] = value;
234
+ } catch (error) {
235
+ reportError(error);
216
236
  }
217
- };
218
- 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 {
219
293
  constructor(name) {
220
294
  this.name = name;
221
295
  }
222
296
  name;
223
- hasSubscribers = false;
224
- subscribe(_subscription) {
297
+ subscribers = [];
298
+ stores = /* @__PURE__ */ new Map();
299
+ get hasSubscribers() {
300
+ return this.subscribers.length > 0 || this.stores.size > 0;
225
301
  }
226
- unsubscribe(_subscription) {
227
- 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];
228
307
  }
229
- 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;
230
318
  }
231
- unbindStore(_store) {
232
- 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
+ );
233
327
  }
234
- publish(_message) {
328
+ unbindStore(store) {
329
+ return this.stores.delete(store);
235
330
  }
236
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
237
- runStores(_message, fn, thisArg, ...args) {
238
- 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();
239
350
  }
240
351
  };
241
- var DefaultTracingChannel = class {
352
+ var traceEvents = [
353
+ "start",
354
+ "end",
355
+ "asyncStart",
356
+ "asyncEnd",
357
+ "error"
358
+ ];
359
+ var TracingHook = class {
242
360
  start;
243
361
  end;
244
362
  asyncStart;
245
363
  asyncEnd;
246
364
  error;
247
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
+ });
248
372
  if (typeof nameOrChannels === "string") {
249
- this.start = new DefaultChannel(`tracing:${nameOrChannels}:start`);
250
- this.end = new DefaultChannel(`tracing:${nameOrChannels}:end`);
251
- this.asyncStart = new DefaultChannel(
252
- `tracing:${nameOrChannels}:asyncStart`
253
- );
254
- this.asyncEnd = new DefaultChannel(`tracing:${nameOrChannels}:asyncEnd`);
255
- 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`);
256
378
  return;
257
379
  }
258
- this.start = nameOrChannels.start ?? new DefaultChannel("tracing:start");
259
- this.end = nameOrChannels.end ?? new DefaultChannel("tracing:end");
260
- this.asyncStart = nameOrChannels.asyncStart ?? new DefaultChannel("tracing:asyncStart");
261
- this.asyncEnd = nameOrChannels.asyncEnd ?? new DefaultChannel("tracing:asyncEnd");
262
- 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");
263
385
  }
264
386
  get hasSubscribers() {
265
387
  return this.start.hasSubscribers || this.end.hasSubscribers || this.asyncStart.hasSubscribers || this.asyncEnd.hasSubscribers || this.error.hasSubscribers;
266
388
  }
267
- 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;
406
+ }
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() {
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);
268
579
  }
269
- unsubscribe(_handlers) {
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) {
270
590
  return false;
271
591
  }
272
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
273
- traceSync(fn, _message, thisArg, ...args) {
274
- 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;
275
597
  }
276
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
277
- tracePromise(fn, _message, thisArg, ...args) {
278
- return fn.apply(thisArg, args);
598
+ }
599
+ function hasTracingHookShape(value) {
600
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
601
+ return false;
279
602
  }
280
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
281
- traceCallback(fn, _position, _message, thisArg, ...args) {
282
- return fn.apply(thisArg, args);
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;
283
730
  }
284
731
  };
285
732
  var iso = {
@@ -292,7 +739,7 @@ var iso = {
292
739
  getCallerLocation: () => void 0,
293
740
  newAsyncLocalStorage: () => new DefaultAsyncLocalStorage(),
294
741
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
295
- newTracingChannel: (nameOrChannels) => new DefaultTracingChannel(nameOrChannels),
742
+ newTracingChannel: (nameOrChannels) => newGlobalTracingChannel(nameOrChannels),
296
743
  processOn: (_0, _1) => {
297
744
  },
298
745
  basename: (filepath) => filepath.split(/[\\/]/).pop() || filepath,
@@ -412,6 +859,9 @@ var debugLogger = {
412
859
  return createDebugLogger(state);
413
860
  }
414
861
  };
862
+ setGlobalHookErrorReporter((error) => {
863
+ debugLogger.error("Global instrumentation hook error:", error);
864
+ });
415
865
 
416
866
  // src/queue.ts
417
867
  var DEFAULT_QUEUE_SIZE = 15e3;
@@ -2196,7 +2646,8 @@ var ApiKey = import_v36.z.object({
2196
2646
  user_email: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
2197
2647
  user_given_name: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
2198
2648
  user_family_name: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
2199
- 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()
2200
2651
  });
2201
2652
  var TriggeredFunctionState = import_v36.z.object({
2202
2653
  triggered_xact_id: import_v36.z.string(),
@@ -2316,6 +2767,7 @@ var TopicMapData = import_v36.z.object({
2316
2767
  topic_names: import_v36.z.record(import_v36.z.string()).optional(),
2317
2768
  generation_settings: TopicMapGenerationSettings.optional(),
2318
2769
  disable_reconciliation: import_v36.z.boolean().optional(),
2770
+ reconcile_mode: import_v36.z.enum(["evolve", "names_only"]).optional(),
2319
2771
  distance_threshold: import_v36.z.number().optional(),
2320
2772
  btql_filter: import_v36.z.string().optional(),
2321
2773
  automation_btql_filter: import_v36.z.string().optional()
@@ -2896,7 +3348,12 @@ var ModelParams = import_v36.z.union([
2896
3348
  }).partial().passthrough()
2897
3349
  ]);
2898
3350
  var PromptOptionsNullish = import_v36.z.union([
2899
- 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(),
2900
3357
  import_v36.z.null()
2901
3358
  ]);
2902
3359
  var PromptParserNullish = import_v36.z.union([
@@ -2910,11 +3367,25 @@ var PromptParserNullish = import_v36.z.union([
2910
3367
  }),
2911
3368
  import_v36.z.null()
2912
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
+ ]);
2913
3383
  var PromptDataNullish = import_v36.z.union([
2914
3384
  import_v36.z.object({
2915
3385
  prompt: PromptBlockDataNullish,
2916
3386
  options: PromptOptionsNullish,
2917
3387
  parser: PromptParserNullish,
3388
+ preprocessor: PreprocessorSavedFunctionId,
2918
3389
  tool_functions: import_v36.z.union([import_v36.z.array(SavedFunctionId), import_v36.z.null()]),
2919
3390
  template_format: import_v36.z.union([
2920
3391
  import_v36.z.enum(["mustache", "nunjucks", "none"]),
@@ -3116,6 +3587,7 @@ var PromptData = import_v36.z.object({
3116
3587
  prompt: PromptBlockDataNullish,
3117
3588
  options: PromptOptionsNullish,
3118
3589
  parser: PromptParserNullish,
3590
+ preprocessor: PreprocessorSavedFunctionId,
3119
3591
  tool_functions: import_v36.z.union([import_v36.z.array(SavedFunctionId), import_v36.z.null()]),
3120
3592
  template_format: import_v36.z.union([
3121
3593
  import_v36.z.enum(["mustache", "nunjucks", "none"]),
@@ -3278,7 +3750,8 @@ var InvokeFunction = FunctionId.and(
3278
3750
  mode: StreamingMode,
3279
3751
  strict: import_v36.z.union([import_v36.z.boolean(), import_v36.z.null()]),
3280
3752
  mcp_auth: import_v36.z.record(import_v36.z.object({ oauth_token: import_v36.z.string() }).partial()),
3281
- 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()])
3282
3755
  }).partial()
3283
3756
  );
3284
3757
  var MCPServer = import_v36.z.object({
@@ -3342,6 +3815,24 @@ var Organization = import_v36.z.object({
3342
3815
  created: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
3343
3816
  image_rendering_mode: ImageRenderingMode.optional()
3344
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
+ });
3345
3836
  var ProjectSettings = import_v36.z.union([
3346
3837
  import_v36.z.object({
3347
3838
  comparison_key: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]),
@@ -3368,6 +3859,7 @@ var ProjectSettings = import_v36.z.union([
3368
3859
  import_v36.z.null()
3369
3860
  ]),
3370
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()]),
3371
3863
  default_preprocessor: NullableSavedFunctionId
3372
3864
  }).partial(),
3373
3865
  import_v36.z.null()
@@ -3382,11 +3874,6 @@ var Project = import_v36.z.object({
3382
3874
  user_id: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
3383
3875
  settings: ProjectSettings.optional()
3384
3876
  });
3385
- var RetentionObjectType = import_v36.z.enum([
3386
- "project_logs",
3387
- "experiment",
3388
- "dataset"
3389
- ]);
3390
3877
  var TopicAutomationFacetModel = import_v36.z.union([
3391
3878
  import_v36.z.enum(["brain-facet-latest", "brain-facet-1", "brain-facet-2"]),
3392
3879
  import_v36.z.null()
@@ -3497,7 +3984,7 @@ var ProjectAutomation = import_v36.z.object({
3497
3984
  import_v36.z.object({
3498
3985
  event_type: import_v36.z.literal("retention"),
3499
3986
  object_type: RetentionObjectType,
3500
- retention_days: import_v36.z.number().gte(0)
3987
+ retention_days: import_v36.z.number().int().gte(0)
3501
3988
  }),
3502
3989
  import_v36.z.object({
3503
3990
  event_type: import_v36.z.literal("environment_update"),
@@ -3669,7 +4156,12 @@ var Prompt = import_v36.z.object({
3669
4156
  metadata: import_v36.z.union([import_v36.z.object({}).partial().passthrough(), import_v36.z.null()]).optional(),
3670
4157
  function_type: FunctionTypeEnumNullish.optional()
3671
4158
  });
3672
- 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();
3673
4165
  var PromptSessionEvent = import_v36.z.object({
3674
4166
  id: import_v36.z.string(),
3675
4167
  _xact_id: import_v36.z.string(),
@@ -3752,7 +4244,8 @@ var RunEval = import_v36.z.object({
3752
4244
  stop_token: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
3753
4245
  extra_messages: import_v36.z.string().optional(),
3754
4246
  tags: import_v36.z.array(import_v36.z.string()).optional(),
3755
- 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()
3756
4249
  });
3757
4250
  var ServiceToken = import_v36.z.object({
3758
4251
  id: import_v36.z.string().uuid(),
@@ -3762,7 +4255,8 @@ var ServiceToken = import_v36.z.object({
3762
4255
  service_account_id: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
3763
4256
  service_account_email: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
3764
4257
  service_account_name: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
3765
- 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()
3766
4260
  });
3767
4261
  var SpanIFrame = import_v36.z.object({
3768
4262
  id: import_v36.z.string().uuid(),
@@ -3884,6 +4378,13 @@ var ViewOptions = import_v36.z.union([
3884
4378
  }),
3885
4379
  import_v36.z.null()
3886
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
+ ]),
3887
4388
  xAxisAggregation: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]),
3888
4389
  chartAnnotations: import_v36.z.union([
3889
4390
  import_v36.z.array(import_v36.z.object({ id: import_v36.z.string(), text: import_v36.z.string() })),
@@ -5025,6 +5526,8 @@ var INSTRUMENTATION_NAMES = {
5025
5526
  BEDROCK_RUNTIME: "bedrock-runtime",
5026
5527
  BRAINTRUST_JS_LOGGER: "braintrust-js-logger",
5027
5528
  CLAUDE_AGENT_SDK: "claude-agent-sdk",
5529
+ CLOUDFLARE_AI_CHAT: "cloudflare-ai-chat",
5530
+ CLOUDFLARE_AGENTS: "cloudflare-agents",
5028
5531
  COHERE: "cohere",
5029
5532
  CURSOR_SDK: "cursor-sdk",
5030
5533
  EVE: "eve",
@@ -5050,7 +5553,7 @@ var INSTRUMENTATION_NAMES = {
5050
5553
  var INTERNAL_SPAN_INSTRUMENTATION_NAME = /* @__PURE__ */ Symbol.for(
5051
5554
  "braintrust.spanInstrumentationName"
5052
5555
  );
5053
- var SDK_VERSION = true ? "3.25.0" : "0.0.0";
5556
+ var SDK_VERSION = true ? "3.26.0" : "0.0.0";
5054
5557
  function withSpanInstrumentationName(args, instrumentationName) {
5055
5558
  return {
5056
5559
  ...args,
@@ -5245,12 +5748,13 @@ function applyMaskingToField(maskingFunction, data, fieldName) {
5245
5748
  var INITIAL_SPAN_WRITE_AS_MERGE = /* @__PURE__ */ Symbol(
5246
5749
  "braintrust.initial-span-write-as-merge"
5247
5750
  );
5751
+ var INTERNAL_SPAN_CONTEXT = /* @__PURE__ */ Symbol("braintrust.internal-span-context");
5248
5752
  var BRAINTRUST_CURRENT_SPAN_STORE = /* @__PURE__ */ Symbol.for(
5249
5753
  "braintrust.currentSpanStore"
5250
5754
  );
5251
5755
  var ContextManager = class {
5252
5756
  /**
5253
- * 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.
5254
5758
  * In default mode this is the Span itself; in OTEL mode it is the OTEL Context
5255
5759
  * containing the span so that OTEL's own ALS stores a proper Context object.
5256
5760
  */
@@ -8983,6 +9487,12 @@ function _internalStartSpanWithInitialMerge(args) {
8983
9487
  [INITIAL_SPAN_WRITE_AS_MERGE]: true
8984
9488
  }).span;
8985
9489
  }
9490
+ function _internalStartSpanWithContext(args, context) {
9491
+ return startSpanAndIsLogger({
9492
+ ...args,
9493
+ [INTERNAL_SPAN_CONTEXT]: context
9494
+ }).span;
9495
+ }
8986
9496
  async function flush(options) {
8987
9497
  const state = options?.state ?? _globalState;
8988
9498
  return await state.bgLogger().flush();
@@ -9884,7 +10394,7 @@ var SpanImpl = class _SpanImpl {
9884
10394
  start: args.startTime ?? getCurrentUnixTimestamp()
9885
10395
  },
9886
10396
  context: mergeSpanOriginContext(
9887
- { ...callerLocation },
10397
+ { ...callerLocation, ...args[INTERNAL_SPAN_CONTEXT] },
9888
10398
  instrumentationName,
9889
10399
  this._state.spanOriginEnvironment
9890
10400
  ),
@@ -11192,95 +11702,6 @@ function resolveRuntimeAsyncLocalStorage() {
11192
11702
  }
11193
11703
  }
11194
11704
 
11195
- // src/edge-light/config.ts
11196
- var import_dc_browser = require("dc-browser");
11197
-
11198
- // src/auto-instrumentations/patch-tracing-channel.ts
11199
- function patchTracingChannel(tracingChannelFn) {
11200
- const dummyChannel = tracingChannelFn("__braintrust_probe__");
11201
- const TracingChannel = dummyChannel?.constructor;
11202
- if (!TracingChannel?.prototype) {
11203
- return;
11204
- }
11205
- if (!Object.getOwnPropertyDescriptor(TracingChannel.prototype, "hasSubscribers")) {
11206
- Object.defineProperty(TracingChannel.prototype, "hasSubscribers", {
11207
- configurable: true,
11208
- enumerable: false,
11209
- get() {
11210
- return Boolean(
11211
- this.start?.hasSubscribers || this.end?.hasSubscribers || this.asyncStart?.hasSubscribers || this.asyncEnd?.hasSubscribers || this.error?.hasSubscribers
11212
- );
11213
- }
11214
- });
11215
- }
11216
- if (TracingChannel.prototype.tracePromise) {
11217
- TracingChannel.prototype.tracePromise = function(fn, context = {}, thisArg, ...args) {
11218
- const start = this.start;
11219
- const end = this.end;
11220
- const asyncStart = this.asyncStart;
11221
- const asyncEnd = this.asyncEnd;
11222
- const error = this.error;
11223
- function publishRejected(err) {
11224
- context.error = err;
11225
- error?.publish(context);
11226
- asyncStart?.publish(context);
11227
- asyncEnd?.publish(context);
11228
- }
11229
- function publishResolved(result) {
11230
- context.result = result;
11231
- asyncStart?.publish(context);
11232
- asyncEnd?.publish(context);
11233
- }
11234
- return start.runStores(context, () => {
11235
- try {
11236
- const result = Reflect.apply(fn, thisArg, args);
11237
- end?.publish(context);
11238
- if (result && (typeof result === "object" || typeof result === "function") && typeof result.then === "function") {
11239
- if (result.constructor === Promise) {
11240
- return result.then(
11241
- (res) => {
11242
- publishResolved(res);
11243
- return res;
11244
- },
11245
- (err) => {
11246
- publishRejected(err);
11247
- return Promise.reject(err);
11248
- }
11249
- );
11250
- }
11251
- void result.then(
11252
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
11253
- (resolved) => {
11254
- try {
11255
- publishResolved(resolved);
11256
- } catch {
11257
- }
11258
- },
11259
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
11260
- (err) => {
11261
- try {
11262
- publishRejected(err);
11263
- } catch {
11264
- }
11265
- }
11266
- );
11267
- return result;
11268
- }
11269
- context.result = result;
11270
- asyncStart?.publish(context);
11271
- asyncEnd?.publish(context);
11272
- return result;
11273
- } catch (err) {
11274
- context.error = err;
11275
- error?.publish(context);
11276
- end?.publish(context);
11277
- throw err;
11278
- }
11279
- });
11280
- };
11281
- }
11282
- }
11283
-
11284
11705
  // src/instrumentation/core/stream-patcher.ts
11285
11706
  function isAsyncIterable(value) {
11286
11707
  return value !== null && typeof value === "object" && Symbol.asyncIterator in value && typeof value[Symbol.asyncIterator] === "function";
@@ -11947,8 +12368,8 @@ function runWithAutoInstrumentationSuppressed(callback) {
11947
12368
  callback
11948
12369
  );
11949
12370
  }
11950
- function bindAutoInstrumentationSuppressionToStart(tracingChannel2) {
11951
- const startChannel = tracingChannel2.start;
12371
+ function bindAutoInstrumentationSuppressionToStart(tracingChannel) {
12372
+ const startChannel = tracingChannel.start;
11952
12373
  if (!startChannel) {
11953
12374
  return void 0;
11954
12375
  }
@@ -12059,9 +12480,9 @@ function ensureSpanStateForEvent(states, config, event, channelName, instrumenta
12059
12480
  states.set(key, created);
12060
12481
  return created;
12061
12482
  }
12062
- function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelName, instrumentationName) {
12483
+ function bindCurrentSpanStoreToStart(tracingChannel, states, config, channelName, instrumentationName) {
12063
12484
  const state = _internalGetGlobalState();
12064
- const startChannel = tracingChannel2.start;
12485
+ const startChannel = tracingChannel.start;
12065
12486
  const contextManager = state?.contextManager;
12066
12487
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
12067
12488
  if (!currentSpanStore || !startChannel) {
@@ -12144,11 +12565,11 @@ function runStreamingErrorHook(args) {
12144
12565
  }
12145
12566
  }
12146
12567
  function traceAsyncChannel(channel2, config) {
12147
- const tracingChannel2 = channel2.tracingChannel();
12568
+ const tracingChannel = channel2.tracingChannel();
12148
12569
  const states = /* @__PURE__ */ new WeakMap();
12149
12570
  const channelName = channel2.channelName;
12150
12571
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart(
12151
- tracingChannel2,
12572
+ tracingChannel,
12152
12573
  states,
12153
12574
  config,
12154
12575
  channelName,
@@ -12204,18 +12625,18 @@ function traceAsyncChannel(channel2, config) {
12204
12625
  logErrorAndEnd(states, event, channelName);
12205
12626
  }
12206
12627
  };
12207
- tracingChannel2.subscribe(handlers);
12628
+ tracingChannel.subscribe(handlers);
12208
12629
  return () => {
12209
12630
  unbindCurrentSpanStore?.();
12210
- tracingChannel2.unsubscribe(handlers);
12631
+ tracingChannel.unsubscribe(handlers);
12211
12632
  };
12212
12633
  }
12213
12634
  function traceStreamingChannel(channel2, config) {
12214
- const tracingChannel2 = channel2.tracingChannel();
12635
+ const tracingChannel = channel2.tracingChannel();
12215
12636
  const states = /* @__PURE__ */ new WeakMap();
12216
12637
  const channelName = channel2.channelName;
12217
12638
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart(
12218
- tracingChannel2,
12639
+ tracingChannel,
12219
12640
  states,
12220
12641
  config,
12221
12642
  channelName,
@@ -12426,18 +12847,18 @@ function traceStreamingChannel(channel2, config) {
12426
12847
  }
12427
12848
  }
12428
12849
  };
12429
- tracingChannel2.subscribe(handlers);
12850
+ tracingChannel.subscribe(handlers);
12430
12851
  return () => {
12431
12852
  unbindCurrentSpanStore?.();
12432
- tracingChannel2.unsubscribe(handlers);
12853
+ tracingChannel.unsubscribe(handlers);
12433
12854
  };
12434
12855
  }
12435
12856
  function traceSyncStreamChannel(channel2, config) {
12436
- const tracingChannel2 = channel2.tracingChannel();
12857
+ const tracingChannel = channel2.tracingChannel();
12437
12858
  const states = /* @__PURE__ */ new WeakMap();
12438
12859
  const channelName = channel2.channelName;
12439
12860
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart(
12440
- tracingChannel2,
12861
+ tracingChannel,
12441
12862
  states,
12442
12863
  config,
12443
12864
  channelName,
@@ -12550,10 +12971,10 @@ function traceSyncStreamChannel(channel2, config) {
12550
12971
  logErrorAndEnd(states, event, channelName);
12551
12972
  }
12552
12973
  };
12553
- tracingChannel2.subscribe(handlers);
12974
+ tracingChannel.subscribe(handlers);
12554
12975
  return () => {
12555
12976
  unbindCurrentSpanStore?.();
12556
- tracingChannel2.unsubscribe(handlers);
12977
+ tracingChannel.unsubscribe(handlers);
12557
12978
  };
12558
12979
  }
12559
12980
  function unsubscribeAll(unsubscribers) {
@@ -12733,7 +13154,7 @@ function defineChannels(pkg, channels, options) {
12733
13154
  const fullChannelName = `orchestrion:${pkg}:${spec.channelName}`;
12734
13155
  if (spec.kind === "async") {
12735
13156
  const asyncSpec = spec;
12736
- const tracingChannel3 = () => isomorph_default.newTracingChannel(
13157
+ const tracingChannel2 = () => isomorph_default.newTracingChannel(
12737
13158
  fullChannelName
12738
13159
  );
12739
13160
  return [
@@ -12741,8 +13162,8 @@ function defineChannels(pkg, channels, options) {
12741
13162
  {
12742
13163
  ...asyncSpec,
12743
13164
  instrumentationName,
12744
- tracingChannel: tracingChannel3,
12745
- tracePromise: (fn, context) => tracingChannel3().tracePromise(
13165
+ tracingChannel: tracingChannel2,
13166
+ tracePromise: (fn, context) => tracingChannel2().tracePromise(
12746
13167
  fn,
12747
13168
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
12748
13169
  context
@@ -12751,7 +13172,7 @@ function defineChannels(pkg, channels, options) {
12751
13172
  ];
12752
13173
  }
12753
13174
  const syncSpec = spec;
12754
- const tracingChannel2 = () => isomorph_default.newTracingChannel(
13175
+ const tracingChannel = () => isomorph_default.newTracingChannel(
12755
13176
  fullChannelName
12756
13177
  );
12757
13178
  return [
@@ -12759,8 +13180,8 @@ function defineChannels(pkg, channels, options) {
12759
13180
  {
12760
13181
  ...syncSpec,
12761
13182
  instrumentationName,
12762
- tracingChannel: tracingChannel2,
12763
- traceSync: (fn, context) => tracingChannel2().traceSync(
13183
+ tracingChannel,
13184
+ traceSync: (fn, context) => tracingChannel().traceSync(
12764
13185
  fn,
12765
13186
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
12766
13187
  context
@@ -14092,7 +14513,7 @@ var AnthropicPlugin = class extends BasePlugin {
14092
14513
  );
14093
14514
  }
14094
14515
  subscribeToAnthropicToolRunner() {
14095
- const tracingChannel2 = anthropicChannels.betaMessagesToolRunner.tracingChannel();
14516
+ const tracingChannel = anthropicChannels.betaMessagesToolRunner.tracingChannel();
14096
14517
  const states = /* @__PURE__ */ new WeakMap();
14097
14518
  const handlers = {
14098
14519
  start: (event) => {
@@ -14149,9 +14570,9 @@ var AnthropicPlugin = class extends BasePlugin {
14149
14570
  states.delete(event);
14150
14571
  }
14151
14572
  };
14152
- tracingChannel2.subscribe(handlers);
14573
+ tracingChannel.subscribe(handlers);
14153
14574
  this.unsubscribers.push(() => {
14154
- tracingChannel2.unsubscribe(handlers);
14575
+ tracingChannel.unsubscribe(handlers);
14155
14576
  });
14156
14577
  }
14157
14578
  };
@@ -15063,8 +15484,8 @@ function registerHarnessSessionParent(session, parent) {
15063
15484
  function currentHarnessTurnParent() {
15064
15485
  return harnessTurnParentStore?.getStore() ?? wrapperTurnParents.get(currentSpan());
15065
15486
  }
15066
- function bindHarnessTurnParentToStart(tracingChannel2, parentFromEvent) {
15067
- const startChannel = tracingChannel2.start;
15487
+ function bindHarnessTurnParentToStart(tracingChannel, parentFromEvent) {
15488
+ const startChannel = tracingChannel.start;
15068
15489
  if (!startChannel) {
15069
15490
  return () => {
15070
15491
  };
@@ -20530,7 +20951,7 @@ var CursorSDKPlugin = class extends BasePlugin {
20530
20951
  this.subscribeToAgentFactory(cursorSDKChannels.resume);
20531
20952
  }
20532
20953
  subscribeToAgentFactory(channel2) {
20533
- const tracingChannel2 = channel2.tracingChannel();
20954
+ const tracingChannel = channel2.tracingChannel();
20534
20955
  const handlers = {
20535
20956
  asyncEnd: (event) => {
20536
20957
  patchCursorAgentInPlace(event.result);
@@ -20538,9 +20959,9 @@ var CursorSDKPlugin = class extends BasePlugin {
20538
20959
  error: () => {
20539
20960
  }
20540
20961
  };
20541
- tracingChannel2.subscribe(handlers);
20962
+ tracingChannel.subscribe(handlers);
20542
20963
  this.unsubscribers.push(() => {
20543
- tracingChannel2.unsubscribe(handlers);
20964
+ tracingChannel.unsubscribe(handlers);
20544
20965
  });
20545
20966
  }
20546
20967
  subscribeToPrompt() {
@@ -21896,10 +22317,10 @@ var GoogleGenAIPlugin = class extends BasePlugin {
21896
22317
  this.subscribeToInteractionsCreateChannel();
21897
22318
  }
21898
22319
  subscribeToGenerateContentChannel() {
21899
- const tracingChannel2 = googleGenAIChannels.generateContent.tracingChannel();
22320
+ const tracingChannel = googleGenAIChannels.generateContent.tracingChannel();
21900
22321
  const states = /* @__PURE__ */ new WeakMap();
21901
22322
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart2(
21902
- tracingChannel2,
22323
+ tracingChannel,
21903
22324
  states,
21904
22325
  (event) => {
21905
22326
  const params = event.arguments[0];
@@ -21973,14 +22394,14 @@ var GoogleGenAIPlugin = class extends BasePlugin {
21973
22394
  logErrorAndEndSpan(states, event);
21974
22395
  }
21975
22396
  };
21976
- tracingChannel2.subscribe(handlers);
22397
+ tracingChannel.subscribe(handlers);
21977
22398
  this.unsubscribers.push(() => {
21978
22399
  unbindCurrentSpanStore?.();
21979
- tracingChannel2.unsubscribe(handlers);
22400
+ tracingChannel.unsubscribe(handlers);
21980
22401
  });
21981
22402
  }
21982
22403
  subscribeToGenerateContentStreamChannel() {
21983
- const tracingChannel2 = googleGenAIChannels.generateContentStream.tracingChannel();
22404
+ const tracingChannel = googleGenAIChannels.generateContentStream.tracingChannel();
21984
22405
  const handlers = {
21985
22406
  start: (event) => {
21986
22407
  const streamEvent = event;
@@ -22001,16 +22422,16 @@ var GoogleGenAIPlugin = class extends BasePlugin {
22001
22422
  error: () => {
22002
22423
  }
22003
22424
  };
22004
- tracingChannel2.subscribe(handlers);
22425
+ tracingChannel.subscribe(handlers);
22005
22426
  this.unsubscribers.push(() => {
22006
- tracingChannel2.unsubscribe(handlers);
22427
+ tracingChannel.unsubscribe(handlers);
22007
22428
  });
22008
22429
  }
22009
22430
  subscribeToEmbedContentChannel() {
22010
- const tracingChannel2 = googleGenAIChannels.embedContent.tracingChannel();
22431
+ const tracingChannel = googleGenAIChannels.embedContent.tracingChannel();
22011
22432
  const states = /* @__PURE__ */ new WeakMap();
22012
22433
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart2(
22013
- tracingChannel2,
22434
+ tracingChannel,
22014
22435
  states,
22015
22436
  (event) => {
22016
22437
  const params = event.arguments[0];
@@ -22080,10 +22501,10 @@ var GoogleGenAIPlugin = class extends BasePlugin {
22080
22501
  logErrorAndEndSpan(states, event);
22081
22502
  }
22082
22503
  };
22083
- tracingChannel2.subscribe(handlers);
22504
+ tracingChannel.subscribe(handlers);
22084
22505
  this.unsubscribers.push(() => {
22085
22506
  unbindCurrentSpanStore?.();
22086
- tracingChannel2.unsubscribe(handlers);
22507
+ tracingChannel.unsubscribe(handlers);
22087
22508
  });
22088
22509
  }
22089
22510
  subscribeToInteractionsCreateChannel() {
@@ -22119,10 +22540,10 @@ function ensureSpanState(states, event, create) {
22119
22540
  states.set(event, created);
22120
22541
  return created;
22121
22542
  }
22122
- function bindCurrentSpanStoreToStart2(tracingChannel2, states, create) {
22543
+ function bindCurrentSpanStoreToStart2(tracingChannel, states, create) {
22123
22544
  const state = _internalGetGlobalState();
22124
22545
  const contextManager = state?.contextManager;
22125
- const startChannel = tracingChannel2.start;
22546
+ const startChannel = tracingChannel.start;
22126
22547
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
22127
22548
  if (!startChannel?.bindStore || !currentSpanStore) {
22128
22549
  return void 0;
@@ -22625,11 +23046,11 @@ function summarizeEmbedContentOutput(response) {
22625
23046
  };
22626
23047
  }
22627
23048
  function populateUsageMetrics(metrics, usage) {
22628
- if (usage.promptTokenCount !== void 0) {
22629
- metrics.prompt_tokens = usage.promptTokenCount;
23049
+ if (usage.promptTokenCount !== void 0 || usage.toolUsePromptTokenCount !== void 0) {
23050
+ metrics.prompt_tokens = (usage.promptTokenCount ?? 0) + (usage.toolUsePromptTokenCount ?? 0);
22630
23051
  }
22631
- if (usage.candidatesTokenCount !== void 0) {
22632
- metrics.completion_tokens = usage.candidatesTokenCount;
23052
+ if (usage.candidatesTokenCount !== void 0 || usage.thoughtsTokenCount !== void 0) {
23053
+ metrics.completion_tokens = (usage.candidatesTokenCount ?? 0) + (usage.thoughtsTokenCount ?? 0);
22633
23054
  }
22634
23055
  if (usage.totalTokenCount !== void 0) {
22635
23056
  metrics.tokens = usage.totalTokenCount;
@@ -22640,13 +23061,26 @@ function populateUsageMetrics(metrics, usage) {
22640
23061
  if (usage.thoughtsTokenCount !== void 0) {
22641
23062
  metrics.completion_reasoning_tokens = usage.thoughtsTokenCount;
22642
23063
  }
23064
+ for (const detail of usage.promptTokensDetails ?? []) {
23065
+ if (detail.modality === "AUDIO" && detail.tokenCount !== void 0) {
23066
+ metrics.prompt_audio_tokens = (metrics.prompt_audio_tokens ?? 0) + detail.tokenCount;
23067
+ }
23068
+ }
23069
+ for (const detail of usage.candidatesTokensDetails ?? []) {
23070
+ if (detail.modality === "AUDIO" && detail.tokenCount !== void 0) {
23071
+ metrics.completion_audio_tokens = (metrics.completion_audio_tokens ?? 0) + detail.tokenCount;
23072
+ }
23073
+ if (detail.modality === "IMAGE" && detail.tokenCount !== void 0) {
23074
+ metrics.completion_image_tokens = (metrics.completion_image_tokens ?? 0) + detail.tokenCount;
23075
+ }
23076
+ }
22643
23077
  }
22644
23078
  function populateInteractionUsageMetrics(metrics, usage) {
22645
23079
  if (typeof usage.total_input_tokens === "number") {
22646
23080
  metrics.prompt_tokens = usage.total_input_tokens;
22647
23081
  }
22648
23082
  if (typeof usage.total_output_tokens === "number") {
22649
- metrics.completion_tokens = usage.total_output_tokens;
23083
+ metrics.completion_tokens = usage.total_output_tokens + (typeof usage.total_thought_tokens === "number" ? usage.total_thought_tokens : 0);
22650
23084
  }
22651
23085
  if (typeof usage.total_tokens === "number") {
22652
23086
  metrics.tokens = usage.total_tokens;
@@ -22657,6 +23091,24 @@ function populateInteractionUsageMetrics(metrics, usage) {
22657
23091
  if (typeof usage.total_thought_tokens === "number") {
22658
23092
  metrics.completion_reasoning_tokens = usage.total_thought_tokens;
22659
23093
  }
23094
+ for (const detail of Array.isArray(usage.input_tokens_by_modality) ? usage.input_tokens_by_modality : []) {
23095
+ if (typeof detail?.modality === "string" && detail.modality.toLowerCase() === "audio" && typeof detail.tokens === "number") {
23096
+ metrics.prompt_audio_tokens = (metrics.prompt_audio_tokens ?? 0) + detail.tokens;
23097
+ }
23098
+ }
23099
+ for (const detail of Array.isArray(usage.output_tokens_by_modality) ? usage.output_tokens_by_modality : []) {
23100
+ if (typeof detail?.modality !== "string" || typeof detail.tokens !== "number") {
23101
+ continue;
23102
+ }
23103
+ switch (detail.modality.toLowerCase()) {
23104
+ case "audio":
23105
+ metrics.completion_audio_tokens = (metrics.completion_audio_tokens ?? 0) + detail.tokens;
23106
+ break;
23107
+ case "image":
23108
+ metrics.completion_image_tokens = (metrics.completion_image_tokens ?? 0) + detail.tokens;
23109
+ break;
23110
+ }
23111
+ }
22660
23112
  }
22661
23113
  function aggregateGenerateContentChunks(chunks, startTime, firstTokenTime) {
22662
23114
  const end = getCurrentUnixTimestamp();
@@ -23395,6 +23847,299 @@ function extractTextGenerationStreamMetadata(chunks) {
23395
23847
  return void 0;
23396
23848
  }
23397
23849
 
23850
+ // src/instrumentation/plugins/huggingface-transformers-channels.ts
23851
+ var SUPPORTED_TASKS = /* @__PURE__ */ new Set([
23852
+ "text-generation",
23853
+ "text2text-generation",
23854
+ "summarization",
23855
+ "feature-extraction",
23856
+ "question-answering"
23857
+ ]);
23858
+ var pipelineInfo = /* @__PURE__ */ new WeakMap();
23859
+ function isSupportedHuggingFaceTransformersTask(task) {
23860
+ return typeof task === "string" && SUPPORTED_TASKS.has(task);
23861
+ }
23862
+ function registerHuggingFaceTransformersPipeline(pipeline, task, model) {
23863
+ if (typeof task !== "string") {
23864
+ return;
23865
+ }
23866
+ const info = { task };
23867
+ if (typeof model === "string") {
23868
+ info.model = model;
23869
+ }
23870
+ pipelineInfo.set(pipeline, info);
23871
+ }
23872
+ function getHuggingFaceTransformersPipelineInfo(pipeline) {
23873
+ return pipeline ? pipelineInfo.get(pipeline) : void 0;
23874
+ }
23875
+ var huggingFaceTransformersChannels = defineChannels(
23876
+ "@huggingface/transformers",
23877
+ {
23878
+ pipeline: channel({
23879
+ channelName: "pipeline",
23880
+ kind: "async"
23881
+ }),
23882
+ pipelineCall: channel({
23883
+ channelName: "pipeline.call",
23884
+ kind: "async"
23885
+ })
23886
+ },
23887
+ { instrumentationName: INSTRUMENTATION_NAMES.HUGGINGFACE }
23888
+ );
23889
+
23890
+ // src/instrumentation/plugins/huggingface-transformers-plugin.ts
23891
+ var REQUEST_METADATA_KEYS = [
23892
+ "temperature",
23893
+ "top_p",
23894
+ "max_tokens",
23895
+ "stop"
23896
+ ];
23897
+ var HuggingFaceTransformersPlugin = class extends BasePlugin {
23898
+ onEnable() {
23899
+ this.subscribeToPipelineFactory();
23900
+ this.unsubscribers.push(
23901
+ traceAsyncChannel(huggingFaceTransformersChannels.pipelineCall, {
23902
+ name: (_args, event) => {
23903
+ const task = getTask(event);
23904
+ const operation = task?.replaceAll("-", "_") ?? "unknown";
23905
+ return `huggingface.transformers.${operation}`;
23906
+ },
23907
+ type: "llm" /* LLM */,
23908
+ shouldTrace: (_args, event) => isSupportedHuggingFaceTransformersTask(
23909
+ getTask(event)
23910
+ ),
23911
+ extractInput: (args, event) => ({
23912
+ input: extractInput(
23913
+ getTask(event),
23914
+ args
23915
+ ),
23916
+ metadata: extractMetadata(
23917
+ event,
23918
+ args
23919
+ )
23920
+ }),
23921
+ extractOutput: (result, event) => extractOutput(
23922
+ getTask(event),
23923
+ result
23924
+ ),
23925
+ extractMetrics: () => ({})
23926
+ })
23927
+ );
23928
+ }
23929
+ onDisable() {
23930
+ this.unsubscribers = unsubscribeAll(this.unsubscribers);
23931
+ }
23932
+ subscribeToPipelineFactory() {
23933
+ const channel2 = huggingFaceTransformersChannels.pipeline.tracingChannel();
23934
+ const handlers = {
23935
+ asyncEnd: (event) => {
23936
+ if (typeof event.result !== "function") {
23937
+ return;
23938
+ }
23939
+ registerHuggingFaceTransformersPipeline(
23940
+ event.result,
23941
+ event.arguments?.[0],
23942
+ event.arguments?.[1]
23943
+ );
23944
+ }
23945
+ };
23946
+ channel2.subscribe(handlers);
23947
+ this.unsubscribers.push(() => channel2.unsubscribe(handlers));
23948
+ }
23949
+ };
23950
+ function getTask(event) {
23951
+ const self = event.self;
23952
+ const registeredTask = getHuggingFaceTransformersPipelineInfo(self)?.task;
23953
+ if (registeredTask !== void 0) {
23954
+ return registeredTask;
23955
+ }
23956
+ if (typeof self?.task === "string") {
23957
+ return self.task;
23958
+ }
23959
+ return void 0;
23960
+ }
23961
+ function extractMetadata(event, args) {
23962
+ const metadata = {
23963
+ provider: "huggingface"
23964
+ };
23965
+ const registeredModel = getHuggingFaceTransformersPipelineInfo(
23966
+ event.self
23967
+ )?.model;
23968
+ const model = registeredModel ?? modelIdentifier(event.self);
23969
+ if (model) {
23970
+ metadata.model = model;
23971
+ }
23972
+ const task = getTask(event);
23973
+ const options = task === "question-answering" ? args[2] : args[1];
23974
+ if (isObject(options)) {
23975
+ for (const key of REQUEST_METADATA_KEYS) {
23976
+ if (options[key] !== void 0) {
23977
+ metadata[key] = options[key];
23978
+ }
23979
+ }
23980
+ }
23981
+ return metadata;
23982
+ }
23983
+ function modelIdentifier(pipeline) {
23984
+ const model = pipeline?.model;
23985
+ if (!isObject(model)) {
23986
+ return void 0;
23987
+ }
23988
+ const config = isObject(model.config) ? model.config : void 0;
23989
+ for (const value of [
23990
+ config?._name_or_path,
23991
+ config?.name_or_path,
23992
+ config?.model_id,
23993
+ config?.modelId,
23994
+ model.name
23995
+ ]) {
23996
+ if (typeof value === "string" && value.length > 0) {
23997
+ return value;
23998
+ }
23999
+ }
24000
+ return void 0;
24001
+ }
24002
+ function extractInput(task, args) {
24003
+ switch (task) {
24004
+ case "feature-extraction":
24005
+ return args[0];
24006
+ case "question-answering": {
24007
+ const question = args[0];
24008
+ const context = args[1];
24009
+ if (Array.isArray(question) && Array.isArray(context) && question.every((value) => typeof value === "string") && context.every((value) => typeof value === "string")) {
24010
+ return question.map((value, index) => [
24011
+ {
24012
+ role: "user",
24013
+ content: `Context:
24014
+ ${context[index] ?? ""}
24015
+
24016
+ Question:
24017
+ ${value}`
24018
+ }
24019
+ ]);
24020
+ }
24021
+ if (typeof question === "string" && typeof context === "string") {
24022
+ return [
24023
+ {
24024
+ role: "user",
24025
+ content: `Context:
24026
+ ${context}
24027
+
24028
+ Question:
24029
+ ${question}`
24030
+ }
24031
+ ];
24032
+ }
24033
+ return { context, question };
24034
+ }
24035
+ }
24036
+ const input = args[0];
24037
+ if (task === "text-generation" && isChat(input)) {
24038
+ return input;
24039
+ }
24040
+ if (task === "text-generation" && Array.isArray(input) && input.every(isChat)) {
24041
+ return input;
24042
+ }
24043
+ if (typeof input === "string") {
24044
+ return [{ role: "user", content: input }];
24045
+ }
24046
+ if (Array.isArray(input) && input.every((value) => typeof value === "string")) {
24047
+ return input.map((value) => [
24048
+ {
24049
+ role: "user",
24050
+ content: value
24051
+ }
24052
+ ]);
24053
+ }
24054
+ return input;
24055
+ }
24056
+ function isChat(value) {
24057
+ return Array.isArray(value) && value.length > 0 && value.every(
24058
+ (message) => isObject(message) && typeof message.role === "string" && "content" in message
24059
+ );
24060
+ }
24061
+ function extractOutput(task, result) {
24062
+ switch (task) {
24063
+ case "feature-extraction":
24064
+ return summarizeEmbedding(result);
24065
+ case "question-answering":
24066
+ return choicesFromAnswers(result);
24067
+ default:
24068
+ return choicesFromGenerations(result);
24069
+ }
24070
+ }
24071
+ function summarizeEmbedding(result) {
24072
+ if (!isObject(result) || !Array.isArray(result.dims)) {
24073
+ return void 0;
24074
+ }
24075
+ const { dims } = result;
24076
+ if (dims.length === 0 || !dims.every((dimension) => typeof dimension === "number")) {
24077
+ return void 0;
24078
+ }
24079
+ if (dims.length === 1) {
24080
+ return { embedding_length: dims[0] };
24081
+ }
24082
+ if (dims.length === 2) {
24083
+ return {
24084
+ embedding_count: dims[0],
24085
+ embedding_length: dims[1]
24086
+ };
24087
+ }
24088
+ return {
24089
+ embedding_batch_count: dims[0],
24090
+ embedding_count: dims[1],
24091
+ embedding_length: dims.at(-1) ?? 0
24092
+ };
24093
+ }
24094
+ function choicesFromAnswers(result) {
24095
+ const answers = Array.isArray(result) ? result.flat() : [result];
24096
+ const choices = answers.flatMap((answer, index) => {
24097
+ if (!isObject(answer) || typeof answer.answer !== "string") {
24098
+ return [];
24099
+ }
24100
+ return [
24101
+ {
24102
+ index,
24103
+ finish_reason: "stop",
24104
+ message: {
24105
+ role: "assistant",
24106
+ content: answer.answer
24107
+ }
24108
+ }
24109
+ ];
24110
+ });
24111
+ return choices.length > 0 ? choices : void 0;
24112
+ }
24113
+ function choicesFromGenerations(result) {
24114
+ const generations = Array.isArray(result) ? result.flat() : [result];
24115
+ const choices = generations.flatMap((generation, index) => {
24116
+ if (!isObject(generation)) {
24117
+ return [];
24118
+ }
24119
+ const generated = generation.generated_text ?? generation.summary_text;
24120
+ let content;
24121
+ if (typeof generated === "string") {
24122
+ content = generated;
24123
+ } else if (isChat(generated)) {
24124
+ content = generated.at(-1)?.content;
24125
+ }
24126
+ if (typeof content !== "string") {
24127
+ return [];
24128
+ }
24129
+ return [
24130
+ {
24131
+ index,
24132
+ finish_reason: "stop",
24133
+ message: {
24134
+ role: "assistant",
24135
+ content
24136
+ }
24137
+ }
24138
+ ];
24139
+ });
24140
+ return choices.length > 0 ? choices : void 0;
24141
+ }
24142
+
23398
24143
  // src/instrumentation/plugins/openrouter-agent-channels.ts
23399
24144
  var openRouterAgentChannels = defineChannels(
23400
24145
  "@openrouter/agent",
@@ -23794,7 +24539,7 @@ function isWrappedTool(tool) {
23794
24539
  return Boolean(tool[OPENROUTER_WRAPPED_TOOL]);
23795
24540
  }
23796
24541
  function traceToolExecution(args) {
23797
- const tracingChannel2 = openRouterAgentChannels.toolExecute.tracingChannel();
24542
+ const tracingChannel = openRouterAgentChannels.toolExecute.tracingChannel();
23798
24543
  const input = args.args.length > 0 ? args.args[0] : void 0;
23799
24544
  const event = {
23800
24545
  arguments: [input],
@@ -23804,33 +24549,33 @@ function traceToolExecution(args) {
23804
24549
  toolCallId: args.toolCallId,
23805
24550
  toolName: args.toolName
23806
24551
  };
23807
- tracingChannel2.start.publish(event);
24552
+ tracingChannel.start.publish(event);
23808
24553
  try {
23809
24554
  const result = args.execute();
23810
- return publishToolResult(tracingChannel2, event, result);
24555
+ return publishToolResult(tracingChannel, event, result);
23811
24556
  } catch (error) {
23812
24557
  event.error = normalizeError(error);
23813
- tracingChannel2.error.publish(event);
24558
+ tracingChannel.error.publish(event);
23814
24559
  throw error;
23815
24560
  }
23816
24561
  }
23817
- function publishToolResult(tracingChannel2, event, result) {
24562
+ function publishToolResult(tracingChannel, event, result) {
23818
24563
  if (isPromiseLike(result)) {
23819
24564
  return result.then(
23820
24565
  (resolved) => {
23821
24566
  event.result = resolved;
23822
- tracingChannel2.asyncEnd.publish(event);
24567
+ tracingChannel.asyncEnd.publish(event);
23823
24568
  return resolved;
23824
24569
  },
23825
24570
  (error) => {
23826
24571
  event.error = normalizeError(error);
23827
- tracingChannel2.error.publish(event);
24572
+ tracingChannel.error.publish(event);
23828
24573
  throw error;
23829
24574
  }
23830
24575
  );
23831
24576
  }
23832
24577
  event.result = result;
23833
- tracingChannel2.asyncEnd.publish(event);
24578
+ tracingChannel.asyncEnd.publish(event);
23834
24579
  return result;
23835
24580
  }
23836
24581
  function getToolCallId(context) {
@@ -24736,7 +25481,7 @@ function isWrappedTool2(tool) {
24736
25481
  return Boolean(tool[OPENROUTER_WRAPPED_TOOL2]);
24737
25482
  }
24738
25483
  function traceToolExecution2(args) {
24739
- const tracingChannel2 = openRouterChannels.toolExecute.tracingChannel();
25484
+ const tracingChannel = openRouterChannels.toolExecute.tracingChannel();
24740
25485
  const input = args.args.length > 0 ? args.args[0] : void 0;
24741
25486
  const event = {
24742
25487
  arguments: [input],
@@ -24746,33 +25491,33 @@ function traceToolExecution2(args) {
24746
25491
  toolCallId: args.toolCallId,
24747
25492
  toolName: args.toolName
24748
25493
  };
24749
- tracingChannel2.start.publish(event);
25494
+ tracingChannel.start.publish(event);
24750
25495
  try {
24751
25496
  const result = args.execute();
24752
- return publishToolResult2(tracingChannel2, event, result);
25497
+ return publishToolResult2(tracingChannel, event, result);
24753
25498
  } catch (error) {
24754
25499
  event.error = normalizeError2(error);
24755
- tracingChannel2.error.publish(event);
25500
+ tracingChannel.error.publish(event);
24756
25501
  throw error;
24757
25502
  }
24758
25503
  }
24759
- function publishToolResult2(tracingChannel2, event, result) {
25504
+ function publishToolResult2(tracingChannel, event, result) {
24760
25505
  if (isPromiseLike(result)) {
24761
25506
  return result.then(
24762
25507
  (resolved) => {
24763
25508
  event.result = resolved;
24764
- tracingChannel2.asyncEnd.publish(event);
25509
+ tracingChannel.asyncEnd.publish(event);
24765
25510
  return resolved;
24766
25511
  },
24767
25512
  (error) => {
24768
25513
  event.error = normalizeError2(error);
24769
- tracingChannel2.error.publish(event);
25514
+ tracingChannel.error.publish(event);
24770
25515
  throw error;
24771
25516
  }
24772
25517
  );
24773
25518
  }
24774
25519
  event.result = result;
24775
- tracingChannel2.asyncEnd.publish(event);
25520
+ tracingChannel.asyncEnd.publish(event);
24776
25521
  return result;
24777
25522
  }
24778
25523
  function getToolCallId2(context) {
@@ -25962,7 +26707,7 @@ var GoogleADKPlugin = class extends BasePlugin {
25962
26707
  this.activeAgentSpans.clear();
25963
26708
  }
25964
26709
  subscribeToRunnerRunAsync() {
25965
- const tracingChannel2 = googleADKChannels.runnerRunAsync.tracingChannel();
26710
+ const tracingChannel = googleADKChannels.runnerRunAsync.tracingChannel();
25966
26711
  const states = /* @__PURE__ */ new WeakMap();
25967
26712
  const createState = (event) => {
25968
26713
  const params = event.arguments[0] ?? {};
@@ -25993,7 +26738,7 @@ var GoogleADKPlugin = class extends BasePlugin {
25993
26738
  return { span, startTime, events: [], contextKey };
25994
26739
  };
25995
26740
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart3(
25996
- tracingChannel2,
26741
+ tracingChannel,
25997
26742
  states,
25998
26743
  createState
25999
26744
  );
@@ -26045,14 +26790,14 @@ var GoogleADKPlugin = class extends BasePlugin {
26045
26790
  states.delete(event);
26046
26791
  }
26047
26792
  };
26048
- tracingChannel2.subscribe(handlers);
26793
+ tracingChannel.subscribe(handlers);
26049
26794
  this.unsubscribers.push(() => {
26050
26795
  unbindCurrentSpanStore?.();
26051
- tracingChannel2.unsubscribe(handlers);
26796
+ tracingChannel.unsubscribe(handlers);
26052
26797
  });
26053
26798
  }
26054
26799
  subscribeToAgentRunAsync() {
26055
- const tracingChannel2 = googleADKChannels.agentRunAsync.tracingChannel();
26800
+ const tracingChannel = googleADKChannels.agentRunAsync.tracingChannel();
26056
26801
  const states = /* @__PURE__ */ new WeakMap();
26057
26802
  const createState = (event) => {
26058
26803
  const parentContext = event.arguments[0];
@@ -26101,7 +26846,7 @@ var GoogleADKPlugin = class extends BasePlugin {
26101
26846
  return { span, startTime, events: [], contextKey, name: agentName };
26102
26847
  };
26103
26848
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart3(
26104
- tracingChannel2,
26849
+ tracingChannel,
26105
26850
  states,
26106
26851
  createState
26107
26852
  );
@@ -26153,14 +26898,14 @@ var GoogleADKPlugin = class extends BasePlugin {
26153
26898
  states.delete(event);
26154
26899
  }
26155
26900
  };
26156
- tracingChannel2.subscribe(handlers);
26901
+ tracingChannel.subscribe(handlers);
26157
26902
  this.unsubscribers.push(() => {
26158
26903
  unbindCurrentSpanStore?.();
26159
- tracingChannel2.unsubscribe(handlers);
26904
+ tracingChannel.unsubscribe(handlers);
26160
26905
  });
26161
26906
  }
26162
26907
  subscribeToToolRunAsync() {
26163
- const tracingChannel2 = googleADKChannels.toolRunAsync.tracingChannel();
26908
+ const tracingChannel = googleADKChannels.toolRunAsync.tracingChannel();
26164
26909
  const states = /* @__PURE__ */ new WeakMap();
26165
26910
  const handlers = {
26166
26911
  start: (event) => {
@@ -26227,9 +26972,9 @@ var GoogleADKPlugin = class extends BasePlugin {
26227
26972
  states.delete(event);
26228
26973
  }
26229
26974
  };
26230
- tracingChannel2.subscribe(handlers);
26975
+ tracingChannel.subscribe(handlers);
26231
26976
  this.unsubscribers.push(() => {
26232
- tracingChannel2.unsubscribe(handlers);
26977
+ tracingChannel.unsubscribe(handlers);
26233
26978
  });
26234
26979
  }
26235
26980
  };
@@ -26305,10 +27050,10 @@ function bindAsyncIterableToCurrentSpan(stream, span) {
26305
27050
  }
26306
27051
  return stream;
26307
27052
  }
26308
- function bindCurrentSpanStoreToStart3(tracingChannel2, states, create) {
27053
+ function bindCurrentSpanStoreToStart3(tracingChannel, states, create) {
26309
27054
  const state = _internalGetGlobalState();
26310
27055
  const contextManager = state?.contextManager;
26311
- const startChannel = tracingChannel2.start;
27056
+ const startChannel = tracingChannel.start;
26312
27057
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
26313
27058
  if (!startChannel?.bindStore || !currentSpanStore) {
26314
27059
  return void 0;
@@ -26560,15 +27305,32 @@ function aggregateUsageFromEvents(events) {
26560
27305
  if (usage.thoughtsTokenCount !== void 0) {
26561
27306
  aggregated.thoughtsTokenCount = (aggregated.thoughtsTokenCount ?? 0) + usage.thoughtsTokenCount;
26562
27307
  }
27308
+ if (usage.toolUsePromptTokenCount !== void 0) {
27309
+ aggregated.toolUsePromptTokenCount = (aggregated.toolUsePromptTokenCount ?? 0) + usage.toolUsePromptTokenCount;
27310
+ }
27311
+ for (const detailsField of [
27312
+ "promptTokensDetails",
27313
+ "cacheTokensDetails",
27314
+ "candidatesTokensDetails",
27315
+ "toolUsePromptTokensDetails"
27316
+ ]) {
27317
+ const details = usage[detailsField];
27318
+ if (details !== void 0) {
27319
+ aggregated[detailsField] = [
27320
+ ...aggregated[detailsField] ?? [],
27321
+ ...details
27322
+ ];
27323
+ }
27324
+ }
26563
27325
  }
26564
27326
  return hasUsage ? aggregated : void 0;
26565
27327
  }
26566
27328
  function populateUsageMetrics2(metrics, usage) {
26567
- if (usage.promptTokenCount !== void 0) {
26568
- metrics.prompt_tokens = usage.promptTokenCount;
27329
+ if (usage.promptTokenCount !== void 0 || usage.toolUsePromptTokenCount !== void 0) {
27330
+ metrics.prompt_tokens = (usage.promptTokenCount ?? 0) + (usage.toolUsePromptTokenCount ?? 0);
26569
27331
  }
26570
- if (usage.candidatesTokenCount !== void 0) {
26571
- metrics.completion_tokens = usage.candidatesTokenCount;
27332
+ if (usage.candidatesTokenCount !== void 0 || usage.thoughtsTokenCount !== void 0) {
27333
+ metrics.completion_tokens = (usage.candidatesTokenCount ?? 0) + (usage.thoughtsTokenCount ?? 0);
26572
27334
  }
26573
27335
  if (usage.totalTokenCount !== void 0) {
26574
27336
  metrics.tokens = usage.totalTokenCount;
@@ -26579,6 +27341,19 @@ function populateUsageMetrics2(metrics, usage) {
26579
27341
  if (usage.thoughtsTokenCount !== void 0) {
26580
27342
  metrics.completion_reasoning_tokens = usage.thoughtsTokenCount;
26581
27343
  }
27344
+ for (const detail of usage.promptTokensDetails ?? []) {
27345
+ if (detail.modality === "AUDIO" && detail.tokenCount !== void 0) {
27346
+ metrics.prompt_audio_tokens = (metrics.prompt_audio_tokens ?? 0) + detail.tokenCount;
27347
+ }
27348
+ }
27349
+ for (const detail of usage.candidatesTokensDetails ?? []) {
27350
+ if (detail.modality === "AUDIO" && detail.tokenCount !== void 0) {
27351
+ metrics.completion_audio_tokens = (metrics.completion_audio_tokens ?? 0) + detail.tokenCount;
27352
+ }
27353
+ if (detail.modality === "IMAGE" && detail.tokenCount !== void 0) {
27354
+ metrics.completion_image_tokens = (metrics.completion_image_tokens ?? 0) + detail.tokenCount;
27355
+ }
27356
+ }
26582
27357
  }
26583
27358
  function cleanMetrics4(metrics) {
26584
27359
  const cleaned = {};
@@ -28144,10 +28919,10 @@ var GenkitPlugin = class extends BasePlugin {
28144
28919
  this.subscribeToActionStream();
28145
28920
  }
28146
28921
  subscribeToActionRun() {
28147
- const tracingChannel2 = genkitChannels.actionRun.tracingChannel();
28922
+ const tracingChannel = genkitChannels.actionRun.tracingChannel();
28148
28923
  const states = /* @__PURE__ */ new WeakMap();
28149
28924
  const unbindCurrentSpanStore = bindActionCurrentSpanStoreToStart(
28150
- tracingChannel2,
28925
+ tracingChannel,
28151
28926
  states,
28152
28927
  (event) => startActionRunSpan(event)
28153
28928
  );
@@ -28184,17 +28959,17 @@ var GenkitPlugin = class extends BasePlugin {
28184
28959
  states.delete(event);
28185
28960
  }
28186
28961
  };
28187
- tracingChannel2.subscribe(handlers);
28962
+ tracingChannel.subscribe(handlers);
28188
28963
  this.unsubscribers.push(() => {
28189
28964
  unbindCurrentSpanStore?.();
28190
- tracingChannel2.unsubscribe(handlers);
28965
+ tracingChannel.unsubscribe(handlers);
28191
28966
  });
28192
28967
  }
28193
28968
  subscribeToActionSpan() {
28194
- const tracingChannel2 = genkitCoreChannels.actionSpan.tracingChannel();
28969
+ const tracingChannel = genkitCoreChannels.actionSpan.tracingChannel();
28195
28970
  const states = /* @__PURE__ */ new WeakMap();
28196
28971
  const unbindCurrentSpanStore = bindActionCurrentSpanStoreToStart(
28197
- tracingChannel2,
28972
+ tracingChannel,
28198
28973
  states,
28199
28974
  (event) => startActionSpan(event)
28200
28975
  );
@@ -28232,10 +29007,10 @@ var GenkitPlugin = class extends BasePlugin {
28232
29007
  states.delete(event);
28233
29008
  }
28234
29009
  };
28235
- tracingChannel2.subscribe(handlers);
29010
+ tracingChannel.subscribe(handlers);
28236
29011
  this.unsubscribers.push(() => {
28237
29012
  unbindCurrentSpanStore?.();
28238
- tracingChannel2.unsubscribe(handlers);
29013
+ tracingChannel.unsubscribe(handlers);
28239
29014
  });
28240
29015
  }
28241
29016
  subscribeToActionStream() {
@@ -28304,10 +29079,10 @@ function ensureActionSpanState(states, event, create) {
28304
29079
  }
28305
29080
  return created;
28306
29081
  }
28307
- function bindActionCurrentSpanStoreToStart(tracingChannel2, states, create) {
29082
+ function bindActionCurrentSpanStoreToStart(tracingChannel, states, create) {
28308
29083
  const state = _internalGetGlobalState();
28309
29084
  const contextManager = state?.contextManager;
28310
- const startChannel = tracingChannel2.start;
29085
+ const startChannel = tracingChannel.start;
28311
29086
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
28312
29087
  if (!startChannel?.bindStore || !currentSpanStore) {
28313
29088
  return void 0;
@@ -30669,7 +31444,7 @@ var LangChainPlugin = class extends BasePlugin {
30669
31444
  this.injectedManagers = /* @__PURE__ */ new WeakSet();
30670
31445
  }
30671
31446
  subscribeToConfigure(channel2) {
30672
- const tracingChannel2 = channel2.tracingChannel();
31447
+ const tracingChannel = channel2.tracingChannel();
30673
31448
  const handlers = {
30674
31449
  start: (event) => {
30675
31450
  injectHandlerIntoArguments(event.arguments);
@@ -30678,9 +31453,9 @@ var LangChainPlugin = class extends BasePlugin {
30678
31453
  this.injectHandler(event.result);
30679
31454
  }
30680
31455
  };
30681
- tracingChannel2.subscribe(handlers);
31456
+ tracingChannel.subscribe(handlers);
30682
31457
  this.unsubscribers.push(() => {
30683
- tracingChannel2.unsubscribe(handlers);
31458
+ tracingChannel.unsubscribe(handlers);
30684
31459
  });
30685
31460
  }
30686
31461
  injectHandler(result) {
@@ -30944,7 +31719,7 @@ var LangSmithPlugin = class extends BasePlugin {
30944
31719
  const inputs = preferOwnValue(run, previous, "inputs");
30945
31720
  const outputs = preferOwnValue(run, previous, "outputs");
30946
31721
  const error = errorMessage(preferOwnValue(run, previous, "error"));
30947
- const metadata = extractMetadata(run, previous);
31722
+ const metadata = extractMetadata2(run, previous);
30948
31723
  const tags = extractTags(preferOwnValue(run, previous, "tags"));
30949
31724
  const metrics = extractMetrics(run, previous);
30950
31725
  span.log({
@@ -31049,7 +31824,7 @@ function mapRunType(runType) {
31049
31824
  return "task" /* TASK */;
31050
31825
  }
31051
31826
  }
31052
- function extractMetadata(run, previous) {
31827
+ function extractMetadata2(run, previous) {
31053
31828
  const extra = preferOwnValue(run, previous, "extra");
31054
31829
  const rawMetadata = ownValue(extra, "metadata");
31055
31830
  if (!isRecord2(rawMetadata)) {
@@ -32180,9 +32955,9 @@ var StrandsAgentSDKPlugin = class extends BasePlugin {
32180
32955
  });
32181
32956
  }
32182
32957
  subscribeToMultiAgentStream(channel2, operation) {
32183
- const tracingChannel2 = channel2.tracingChannel();
32958
+ const tracingChannel = channel2.tracingChannel();
32184
32959
  const states = /* @__PURE__ */ new WeakMap();
32185
- const unbindAutoInstrumentationSuppression = bindAutoInstrumentationSuppressionToStart(tracingChannel2);
32960
+ const unbindAutoInstrumentationSuppression = bindAutoInstrumentationSuppressionToStart(tracingChannel);
32186
32961
  const handlers = {
32187
32962
  start: (event) => {
32188
32963
  const state = startMultiAgentStream(
@@ -32236,10 +33011,10 @@ var StrandsAgentSDKPlugin = class extends BasePlugin {
32236
33011
  states.delete(event);
32237
33012
  }
32238
33013
  };
32239
- tracingChannel2.subscribe(handlers);
33014
+ tracingChannel.subscribe(handlers);
32240
33015
  this.unsubscribers.push(() => {
32241
33016
  unbindAutoInstrumentationSuppression?.();
32242
- tracingChannel2.unsubscribe(handlers);
33017
+ tracingChannel.unsubscribe(handlers);
32243
33018
  });
32244
33019
  }
32245
33020
  };
@@ -32422,6 +33197,15 @@ function handleMultiAgentStreamEvent(state, event, activeChildParents) {
32422
33197
  logInstrumentationError5("Strands Agent SDK multi-agent event", error);
32423
33198
  }
32424
33199
  }
33200
+ function buildModelSpanInput(event, attachmentCache) {
33201
+ const systemPrompt = typeof event.agent?.systemPrompt === "string" && event.agent.systemPrompt.length > 0 ? event.agent.systemPrompt : void 0;
33202
+ const processedMessages = Array.isArray(event.agent?.messages) ? processStrandsInputAttachments(event.agent.messages, attachmentCache) : void 0;
33203
+ if (!systemPrompt) {
33204
+ return processedMessages;
33205
+ }
33206
+ const systemMessage = { role: "system", content: systemPrompt };
33207
+ return Array.isArray(processedMessages) ? [systemMessage, ...processedMessages] : [systemMessage];
33208
+ }
32425
33209
  function startModelSpan(state, event) {
32426
33210
  if (state.activeModel) {
32427
33211
  finalizeModelSpan(state);
@@ -32439,10 +33223,7 @@ function startModelSpan(state, event) {
32439
33223
  withSpanInstrumentationName(
32440
33224
  {
32441
33225
  event: {
32442
- input: Array.isArray(event.agent?.messages) ? processStrandsInputAttachments(
32443
- event.agent.messages,
32444
- state.attachmentCache
32445
- ) : void 0,
33226
+ input: buildModelSpanInput(event, state.attachmentCache),
32446
33227
  metadata
32447
33228
  },
32448
33229
  name: formatModelSpanName(model),
@@ -33082,6 +33863,555 @@ function logInstrumentationError5(context, error) {
33082
33863
  debugLogger.debug(`${context}:`, error);
33083
33864
  }
33084
33865
 
33866
+ // src/instrumentation/plugins/cloudflare-ai-chat-channels.ts
33867
+ var cloudflareAIChatChannels = defineChannels(
33868
+ "@cloudflare/ai-chat",
33869
+ {
33870
+ runExclusiveChatTurn: channel({
33871
+ channelName: "AIChatAgent._runExclusiveChatTurn",
33872
+ kind: "async"
33873
+ }),
33874
+ onChatResponse: channel({
33875
+ channelName: "AIChatAgent.onChatResponse",
33876
+ kind: "sync-stream"
33877
+ })
33878
+ },
33879
+ { instrumentationName: INSTRUMENTATION_NAMES.CLOUDFLARE_AI_CHAT }
33880
+ );
33881
+
33882
+ // src/instrumentation/plugins/cloudflare-ai-chat-instrumentation.ts
33883
+ var wrappedTurnRunners = /* @__PURE__ */ new WeakSet();
33884
+ var wrappedResponseHooks = /* @__PURE__ */ new WeakSet();
33885
+ function instrumentCloudflareAIChatAgent(agent) {
33886
+ try {
33887
+ const original = Reflect.get(agent, "_runExclusiveChatTurn");
33888
+ if (typeof original !== "function" || wrappedTurnRunners.has(original)) {
33889
+ return agent;
33890
+ }
33891
+ const wrapped = async function(...args) {
33892
+ return cloudflareAIChatChannels.runExclusiveChatTurn.tracePromise(
33893
+ () => Reflect.apply(original, this, args),
33894
+ {
33895
+ arguments: args,
33896
+ self: this
33897
+ }
33898
+ );
33899
+ };
33900
+ wrappedTurnRunners.add(wrapped);
33901
+ defineWrappedMethod(agent, "_runExclusiveChatTurn", original, wrapped);
33902
+ } catch (error) {
33903
+ debugLogger.debug("Failed to wrap @cloudflare/ai-chat turn runner:", error);
33904
+ }
33905
+ return agent;
33906
+ }
33907
+ function instrumentCloudflareAIChatResponseHook(agent) {
33908
+ try {
33909
+ const original = Reflect.get(agent, "onChatResponse");
33910
+ if (typeof original !== "function" || wrappedResponseHooks.has(original)) {
33911
+ return;
33912
+ }
33913
+ const wrapped = function(result) {
33914
+ const args = [result];
33915
+ return cloudflareAIChatChannels.onChatResponse.traceSync(
33916
+ () => Reflect.apply(original, this, args),
33917
+ {
33918
+ arguments: args,
33919
+ self: this
33920
+ }
33921
+ );
33922
+ };
33923
+ wrappedResponseHooks.add(wrapped);
33924
+ defineWrappedMethod(agent, "onChatResponse", original, wrapped);
33925
+ } catch (error) {
33926
+ debugLogger.debug(
33927
+ "Failed to wrap @cloudflare/ai-chat response hook:",
33928
+ error
33929
+ );
33930
+ }
33931
+ }
33932
+ function defineWrappedMethod(target, property, original, wrapped) {
33933
+ const ownDescriptor = Object.getOwnPropertyDescriptor(target, property);
33934
+ Object.defineProperty(target, property, {
33935
+ configurable: ownDescriptor?.configurable ?? true,
33936
+ enumerable: ownDescriptor?.enumerable ?? false,
33937
+ value: wrapped,
33938
+ writable: ownDescriptor && "writable" in ownDescriptor ? ownDescriptor.writable : true
33939
+ });
33940
+ try {
33941
+ Object.defineProperty(wrapped, "name", {
33942
+ configurable: true,
33943
+ value: original.name
33944
+ });
33945
+ } catch {
33946
+ }
33947
+ }
33948
+
33949
+ // src/instrumentation/plugins/cloudflare-ai-chat-plugin.ts
33950
+ var BLOCKED_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
33951
+ var RESPONSE_STATE_RETENTION_MS = 6e4;
33952
+ var CloudflareAIChatPlugin = class extends BasePlugin {
33953
+ activeStates = /* @__PURE__ */ new Set();
33954
+ activeTurns = /* @__PURE__ */ new WeakMap();
33955
+ eventStates = /* @__PURE__ */ new WeakMap();
33956
+ onEnable() {
33957
+ this.subscribeToResponseHook();
33958
+ this.subscribeToTurnRunner();
33959
+ }
33960
+ onDisable() {
33961
+ for (const unsubscribe of this.unsubscribers) {
33962
+ unsubscribe();
33963
+ }
33964
+ this.unsubscribers = [];
33965
+ for (const state of this.activeStates) {
33966
+ this.cleanupState(state);
33967
+ }
33968
+ this.activeStates.clear();
33969
+ }
33970
+ subscribeToTurnRunner() {
33971
+ const tracingChannel = cloudflareAIChatChannels.runExclusiveChatTurn.tracingChannel();
33972
+ const unbindCurrentSpanStore = this.bindCurrentSpanStore(tracingChannel);
33973
+ const handlers = {
33974
+ start: (event) => {
33975
+ this.ensureEventState(event);
33976
+ },
33977
+ asyncEnd: (event) => {
33978
+ this.finishEvent(event);
33979
+ },
33980
+ error: (event) => {
33981
+ this.finishEvent(event, event.error);
33982
+ }
33983
+ };
33984
+ tracingChannel.subscribe(handlers);
33985
+ this.unsubscribers.push(() => {
33986
+ unbindCurrentSpanStore?.();
33987
+ tracingChannel.unsubscribe(handlers);
33988
+ });
33989
+ }
33990
+ subscribeToResponseHook() {
33991
+ const tracingChannel = cloudflareAIChatChannels.onChatResponse.tracingChannel();
33992
+ const handlers = {
33993
+ start: (event) => {
33994
+ let state;
33995
+ try {
33996
+ const agent = asObject(event.self);
33997
+ const result = event.arguments[0];
33998
+ state = agent ? this.findResponseState(
33999
+ agent,
34000
+ stringValue3(ownValue2(result, "requestId"))
34001
+ ) : void 0;
34002
+ if (!state) {
34003
+ return;
34004
+ }
34005
+ state.responseObserved = true;
34006
+ const output = serializeMessage(ownValue2(result, "message"));
34007
+ const status = stringValue3(ownValue2(result, "status"));
34008
+ const error = ownValue2(result, "error");
34009
+ const input = ownValue2(result, "continuation") === true ? state.input : serializeMessages(readProperty(agent, "messages"))?.filter(
34010
+ (message) => typeof output?.id !== "string" || message.id !== output.id
34011
+ );
34012
+ state.span.log({
34013
+ ...input !== void 0 ? { input } : {},
34014
+ ...output !== void 0 ? { output } : {},
34015
+ ...status === "error" && error !== void 0 ? { error } : {}
34016
+ });
34017
+ } catch (error) {
34018
+ debugLogger.debug(
34019
+ "Failed to process @cloudflare/ai-chat response hook:",
34020
+ error
34021
+ );
34022
+ } finally {
34023
+ if (state?.settled) {
34024
+ this.cleanupState(state);
34025
+ }
34026
+ }
34027
+ }
34028
+ };
34029
+ tracingChannel.subscribe(handlers);
34030
+ this.unsubscribers.push(() => tracingChannel.unsubscribe(handlers));
34031
+ }
34032
+ bindCurrentSpanStore(tracingChannel) {
34033
+ const globalState = _internalGetGlobalState();
34034
+ const contextManager = globalState?.contextManager;
34035
+ const startChannel = tracingChannel.start;
34036
+ const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
34037
+ if (!startChannel || !currentSpanStore || !contextManager) {
34038
+ return void 0;
34039
+ }
34040
+ startChannel.bindStore(currentSpanStore, (event) => {
34041
+ const state = this.ensureEventState(event);
34042
+ return state ? contextManager.wrapSpanForStore(state.span) : currentSpanStore.getStore();
34043
+ });
34044
+ return () => startChannel.unbindStore(currentSpanStore);
34045
+ }
34046
+ ensureEventState(event) {
34047
+ const eventKey = event;
34048
+ const known = this.eventStates.get(eventKey);
34049
+ if (known) {
34050
+ return known;
34051
+ }
34052
+ try {
34053
+ const agent = asObject(event.self);
34054
+ const requestId = stringValue3(event.arguments[0]);
34055
+ const key = requestId ?? /* @__PURE__ */ Symbol("cloudflare-ai-chat-turn");
34056
+ const activeForAgent = agent ? this.getActiveTurns(agent) : void 0;
34057
+ const existing = activeForAgent?.get(key);
34058
+ const state = existing && !existing.settled ? existing : this.createTurnState(agent, key);
34059
+ if (existing && !existing.settled) {
34060
+ state.depth += 1;
34061
+ }
34062
+ this.eventStates.set(eventKey, state);
34063
+ this.bindTurnCallback(event, agent, state);
34064
+ if (agent) {
34065
+ instrumentCloudflareAIChatResponseHook(agent);
34066
+ }
34067
+ return state;
34068
+ } catch (error) {
34069
+ debugLogger.debug(
34070
+ "Failed to start @cloudflare/ai-chat instrumentation:",
34071
+ error
34072
+ );
34073
+ return void 0;
34074
+ }
34075
+ }
34076
+ createTurnState(agent, key) {
34077
+ const span = startSpan(
34078
+ withSpanInstrumentationName(
34079
+ {
34080
+ name: "AIChatAgent.onChatMessage",
34081
+ spanAttributes: { type: "task" /* TASK */ }
34082
+ },
34083
+ INSTRUMENTATION_NAMES.CLOUDFLARE_AI_CHAT
34084
+ )
34085
+ );
34086
+ const state = {
34087
+ agent,
34088
+ depth: 1,
34089
+ ended: false,
34090
+ key,
34091
+ responseObserved: false,
34092
+ settled: false,
34093
+ span
34094
+ };
34095
+ this.activeStates.add(state);
34096
+ if (agent) {
34097
+ this.getActiveTurns(agent).set(key, state);
34098
+ }
34099
+ return state;
34100
+ }
34101
+ bindTurnCallback(event, agent, state) {
34102
+ const callback = event.arguments[1];
34103
+ if (typeof callback !== "function") {
34104
+ return;
34105
+ }
34106
+ try {
34107
+ event.arguments[1] = function(...args) {
34108
+ return withCurrent(state.span, () => {
34109
+ try {
34110
+ const input = serializeMessages(readProperty(agent, "messages"));
34111
+ if (input !== void 0 && state.input === void 0) {
34112
+ state.input = input;
34113
+ state.span.log({ input });
34114
+ }
34115
+ } catch (error) {
34116
+ debugLogger.debug(
34117
+ "Failed to capture @cloudflare/ai-chat messages:",
34118
+ error
34119
+ );
34120
+ }
34121
+ return Reflect.apply(callback, this, args);
34122
+ });
34123
+ };
34124
+ } catch (error) {
34125
+ debugLogger.debug(
34126
+ "Failed to bind @cloudflare/ai-chat turn callback context:",
34127
+ error
34128
+ );
34129
+ }
34130
+ }
34131
+ finishEvent(event, error) {
34132
+ const eventKey = event;
34133
+ const state = this.eventStates.get(eventKey);
34134
+ if (!state || state.ended) {
34135
+ return;
34136
+ }
34137
+ this.eventStates.delete(eventKey);
34138
+ if (error !== void 0 && state.pendingError === void 0) {
34139
+ state.pendingError = error;
34140
+ }
34141
+ state.depth -= 1;
34142
+ if (state.depth === 0) {
34143
+ state.settled = true;
34144
+ this.endState(state);
34145
+ if (state.responseObserved || error !== void 0) {
34146
+ this.cleanupState(state);
34147
+ } else {
34148
+ state.cleanupTimer = setTimeout(
34149
+ () => this.cleanupState(state),
34150
+ RESPONSE_STATE_RETENTION_MS
34151
+ );
34152
+ if (typeof state.cleanupTimer === "object" && state.cleanupTimer !== null && "unref" in state.cleanupTimer && typeof state.cleanupTimer.unref === "function") {
34153
+ state.cleanupTimer.unref();
34154
+ }
34155
+ }
34156
+ }
34157
+ }
34158
+ endState(state) {
34159
+ if (state.ended) {
34160
+ return;
34161
+ }
34162
+ state.ended = true;
34163
+ try {
34164
+ if (state.pendingError !== void 0) {
34165
+ state.span.log({ error: state.pendingError });
34166
+ }
34167
+ } finally {
34168
+ state.span.end();
34169
+ }
34170
+ }
34171
+ cleanupState(state) {
34172
+ if (state.cleanupTimer !== void 0) {
34173
+ clearTimeout(state.cleanupTimer);
34174
+ state.cleanupTimer = void 0;
34175
+ }
34176
+ try {
34177
+ this.endState(state);
34178
+ } finally {
34179
+ this.activeStates.delete(state);
34180
+ if (state.agent) {
34181
+ const activeForAgent = this.activeTurns.get(state.agent);
34182
+ if (activeForAgent?.get(state.key) === state) {
34183
+ activeForAgent.delete(state.key);
34184
+ }
34185
+ }
34186
+ }
34187
+ }
34188
+ getActiveTurns(agent) {
34189
+ let turns = this.activeTurns.get(agent);
34190
+ if (!turns) {
34191
+ turns = /* @__PURE__ */ new Map();
34192
+ this.activeTurns.set(agent, turns);
34193
+ }
34194
+ return turns;
34195
+ }
34196
+ findResponseState(agent, requestId) {
34197
+ const turns = this.activeTurns.get(agent);
34198
+ if (!turns) {
34199
+ return void 0;
34200
+ }
34201
+ if (requestId !== void 0) {
34202
+ return turns.get(requestId);
34203
+ }
34204
+ const active = [...turns.values()];
34205
+ return active.length === 1 ? active[0] : void 0;
34206
+ }
34207
+ };
34208
+ function asObject(value) {
34209
+ return value !== null && (typeof value === "object" || typeof value === "function") ? value : void 0;
34210
+ }
34211
+ function readProperty(value, key) {
34212
+ const object = asObject(value);
34213
+ return object ? Reflect.get(object, key) : void 0;
34214
+ }
34215
+ function ownValue2(value, key) {
34216
+ const object = asObject(value);
34217
+ if (!object) {
34218
+ return void 0;
34219
+ }
34220
+ const descriptor = Object.getOwnPropertyDescriptor(object, key);
34221
+ return descriptor && "value" in descriptor ? descriptor.value : void 0;
34222
+ }
34223
+ function stringValue3(value) {
34224
+ return typeof value === "string" ? value : void 0;
34225
+ }
34226
+ function serializeMessages(value) {
34227
+ if (!Array.isArray(value)) {
34228
+ return void 0;
34229
+ }
34230
+ return value.flatMap((message) => {
34231
+ const serialized = serializeMessage(message);
34232
+ return serialized === void 0 ? [] : [serialized];
34233
+ });
34234
+ }
34235
+ function serializeMessage(value) {
34236
+ const message = asObject(value);
34237
+ if (!message) {
34238
+ return void 0;
34239
+ }
34240
+ const serialized = [];
34241
+ const id = ownValue2(message, "id");
34242
+ const role = ownValue2(message, "role");
34243
+ const parts = ownValue2(message, "parts");
34244
+ if (typeof id === "string") {
34245
+ serialized.push(["id", id]);
34246
+ }
34247
+ if (typeof role === "string") {
34248
+ serialized.push(["role", role]);
34249
+ }
34250
+ const sanitizedParts = sanitizeLoggedValue2(parts);
34251
+ if (sanitizedParts !== void 0) {
34252
+ serialized.push(["parts", sanitizedParts]);
34253
+ }
34254
+ return serialized.length > 0 ? Object.fromEntries(serialized) : void 0;
34255
+ }
34256
+ function sanitizeLoggedValue2(value, seen = /* @__PURE__ */ new WeakSet(), depth = 0) {
34257
+ if (value === null || typeof value === "string" || typeof value === "boolean") {
34258
+ return value;
34259
+ }
34260
+ if (typeof value === "number") {
34261
+ return Number.isFinite(value) ? value : void 0;
34262
+ }
34263
+ const object = asObject(value);
34264
+ if (!object || depth >= 20 || typeof value === "function") {
34265
+ return void 0;
34266
+ }
34267
+ if (seen.has(object)) {
34268
+ return "[Circular]";
34269
+ }
34270
+ seen.add(object);
34271
+ if (Array.isArray(value)) {
34272
+ return value.map((entry) => sanitizeLoggedValue2(entry, seen, depth + 1));
34273
+ }
34274
+ const entries = [];
34275
+ for (const [key, descriptor] of Object.entries(
34276
+ Object.getOwnPropertyDescriptors(object)
34277
+ )) {
34278
+ if (BLOCKED_KEYS.has(key) || !descriptor.enumerable || !("value" in descriptor)) {
34279
+ continue;
34280
+ }
34281
+ const sanitized = sanitizeLoggedValue2(descriptor.value, seen, depth + 1);
34282
+ if (sanitized !== void 0) {
34283
+ entries.push([key, sanitized]);
34284
+ }
34285
+ }
34286
+ return Object.fromEntries(entries);
34287
+ }
34288
+
34289
+ // src/instrumentation/plugins/cloudflare-agents-channels.ts
34290
+ var cloudflareAgentsChannels = defineChannels(
34291
+ "agents",
34292
+ {
34293
+ runAgentTool: channel({
34294
+ channelName: "Agent.runAgentTool",
34295
+ kind: "async"
34296
+ })
34297
+ },
34298
+ { instrumentationName: INSTRUMENTATION_NAMES.CLOUDFLARE_AGENTS }
34299
+ );
34300
+
34301
+ // src/instrumentation/plugins/cloudflare-agents-plugin.ts
34302
+ var CLOUDFLARE_WORKERS_CONTEXT = {
34303
+ span_origin: {
34304
+ environment: { type: "server", name: "cloudflare_workers" }
34305
+ }
34306
+ };
34307
+ var CloudflareAgentsPlugin = class extends BasePlugin {
34308
+ onEnable() {
34309
+ const channel2 = cloudflareAgentsChannels.runAgentTool.tracingChannel();
34310
+ const spans = /* @__PURE__ */ new WeakMap();
34311
+ const handlers = {
34312
+ start: (event) => {
34313
+ try {
34314
+ const agentClass = event.arguments[0];
34315
+ const options = event.arguments[1];
34316
+ if (ownValue3(options, "detached")) {
34317
+ return;
34318
+ }
34319
+ const name = ownValue3(agentClass, "name");
34320
+ if (typeof name !== "string" || name.length === 0) {
34321
+ debugLogger.warn(
34322
+ "Skipping Cloudflare Agents runAgentTool span because the child agent class has no name."
34323
+ );
34324
+ return;
34325
+ }
34326
+ const span = _internalStartSpanWithContext(
34327
+ withSpanInstrumentationName(
34328
+ {
34329
+ name,
34330
+ spanAttributes: { type: "tool" /* TOOL */ },
34331
+ event: {
34332
+ input: ownValue3(options, "input")
34333
+ }
34334
+ },
34335
+ INSTRUMENTATION_NAMES.CLOUDFLARE_AGENTS
34336
+ ),
34337
+ CLOUDFLARE_WORKERS_CONTEXT
34338
+ );
34339
+ spans.set(event, span);
34340
+ } catch (error) {
34341
+ logInstrumentationError6("start", error);
34342
+ }
34343
+ },
34344
+ asyncEnd: (event) => {
34345
+ const span = spans.get(event);
34346
+ if (!span) {
34347
+ return;
34348
+ }
34349
+ spans.delete(event);
34350
+ try {
34351
+ const status = ownValue3(event.result, "status");
34352
+ if (status === "completed") {
34353
+ span.log({ output: ownValue3(event.result, "output") });
34354
+ } else {
34355
+ const error = ownValue3(event.result, "error");
34356
+ if (typeof error === "string") {
34357
+ span.log({ error });
34358
+ }
34359
+ }
34360
+ } catch (error) {
34361
+ logInstrumentationError6("completion", error);
34362
+ } finally {
34363
+ safelyEndSpan(span);
34364
+ }
34365
+ },
34366
+ error: (event) => {
34367
+ const span = spans.get(event);
34368
+ if (!span) {
34369
+ return;
34370
+ }
34371
+ spans.delete(event);
34372
+ try {
34373
+ span.log({ error: event.error });
34374
+ } catch (error) {
34375
+ logInstrumentationError6("rejection", error);
34376
+ } finally {
34377
+ safelyEndSpan(span);
34378
+ }
34379
+ }
34380
+ };
34381
+ channel2.subscribe(handlers);
34382
+ this.unsubscribers.push(() => channel2.unsubscribe(handlers));
34383
+ }
34384
+ onDisable() {
34385
+ for (const unsubscribe of this.unsubscribers) {
34386
+ unsubscribe();
34387
+ }
34388
+ this.unsubscribers = [];
34389
+ }
34390
+ };
34391
+ function ownValue3(value, key) {
34392
+ if (!isObjectLike2(value)) {
34393
+ return void 0;
34394
+ }
34395
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
34396
+ return descriptor && "value" in descriptor ? descriptor.value : void 0;
34397
+ }
34398
+ function isObjectLike2(value) {
34399
+ return typeof value === "object" && value !== null || typeof value === "function";
34400
+ }
34401
+ function safelyEndSpan(span) {
34402
+ try {
34403
+ span.end();
34404
+ } catch (error) {
34405
+ logInstrumentationError6("span end", error);
34406
+ }
34407
+ }
34408
+ function logInstrumentationError6(operation, error) {
34409
+ debugLogger.error(
34410
+ `Failed to process Cloudflare Agents ${operation} instrumentation:`,
34411
+ error
34412
+ );
34413
+ }
34414
+
33085
34415
  // src/instrumentation/braintrust-plugin.ts
33086
34416
  var BraintrustPlugin = class extends BasePlugin {
33087
34417
  config;
@@ -33094,6 +34424,7 @@ var BraintrustPlugin = class extends BasePlugin {
33094
34424
  openAIAgentsPlugin = null;
33095
34425
  googleGenAIPlugin = null;
33096
34426
  huggingFacePlugin = null;
34427
+ huggingFaceTransformersPlugin = null;
33097
34428
  openRouterPlugin = null;
33098
34429
  openRouterAgentPlugin = null;
33099
34430
  mistralPlugin = null;
@@ -33108,6 +34439,8 @@ var BraintrustPlugin = class extends BasePlugin {
33108
34439
  langSmithPlugin = null;
33109
34440
  piCodingAgentPlugin = null;
33110
34441
  strandsAgentSDKPlugin = null;
34442
+ cloudflareAIChatPlugin = null;
34443
+ cloudflareAgentsPlugin = null;
33111
34444
  constructor(config = {}) {
33112
34445
  super();
33113
34446
  this.config = config;
@@ -33149,6 +34482,8 @@ var BraintrustPlugin = class extends BasePlugin {
33149
34482
  if (integrations.huggingface !== false) {
33150
34483
  this.huggingFacePlugin = new HuggingFacePlugin();
33151
34484
  this.huggingFacePlugin.enable();
34485
+ this.huggingFaceTransformersPlugin = new HuggingFaceTransformersPlugin();
34486
+ this.huggingFaceTransformersPlugin.enable();
33152
34487
  }
33153
34488
  if (integrations.openrouter !== false) {
33154
34489
  this.openRouterPlugin = new OpenRouterPlugin();
@@ -33194,6 +34529,14 @@ var BraintrustPlugin = class extends BasePlugin {
33194
34529
  this.strandsAgentSDKPlugin = new StrandsAgentSDKPlugin();
33195
34530
  this.strandsAgentSDKPlugin.enable();
33196
34531
  }
34532
+ if (integrations.cloudflareAIChat !== false) {
34533
+ this.cloudflareAIChatPlugin = new CloudflareAIChatPlugin();
34534
+ this.cloudflareAIChatPlugin.enable();
34535
+ }
34536
+ if (integrations.cloudflareAgents !== false) {
34537
+ this.cloudflareAgentsPlugin = new CloudflareAgentsPlugin();
34538
+ this.cloudflareAgentsPlugin.enable();
34539
+ }
33197
34540
  if (integrations.flue !== false) {
33198
34541
  this.fluePlugin = new FluePlugin();
33199
34542
  this.fluePlugin.enable();
@@ -33246,6 +34589,10 @@ var BraintrustPlugin = class extends BasePlugin {
33246
34589
  this.huggingFacePlugin.disable();
33247
34590
  this.huggingFacePlugin = null;
33248
34591
  }
34592
+ if (this.huggingFaceTransformersPlugin) {
34593
+ this.huggingFaceTransformersPlugin.disable();
34594
+ this.huggingFaceTransformersPlugin = null;
34595
+ }
33249
34596
  if (this.openRouterPlugin) {
33250
34597
  this.openRouterPlugin.disable();
33251
34598
  this.openRouterPlugin = null;
@@ -33290,6 +34637,14 @@ var BraintrustPlugin = class extends BasePlugin {
33290
34637
  this.strandsAgentSDKPlugin.disable();
33291
34638
  this.strandsAgentSDKPlugin = null;
33292
34639
  }
34640
+ if (this.cloudflareAIChatPlugin) {
34641
+ this.cloudflareAIChatPlugin.disable();
34642
+ this.cloudflareAIChatPlugin = null;
34643
+ }
34644
+ if (this.cloudflareAgentsPlugin) {
34645
+ this.cloudflareAgentsPlugin.disable();
34646
+ this.cloudflareAgentsPlugin = null;
34647
+ }
33293
34648
  if (this.fluePlugin) {
33294
34649
  this.fluePlugin.disable();
33295
34650
  this.fluePlugin = null;
@@ -33322,6 +34677,9 @@ var envIntegrationAliases = {
33322
34677
  strandsagentsdk: "strandsAgentSDK",
33323
34678
  "strands-agent-sdk": "strandsAgentSDK",
33324
34679
  "@strands-agents/sdk": "strandsAgentSDK",
34680
+ agents: "cloudflareAgents",
34681
+ "cloudflare-agents": "cloudflareAgents",
34682
+ cloudflareagents: "cloudflareAgents",
33325
34683
  anthropic: "anthropic",
33326
34684
  aisdk: "aisdk",
33327
34685
  "ai-sdk": "aisdk",
@@ -33329,6 +34687,9 @@ var envIntegrationAliases = {
33329
34687
  vercel: "vercel",
33330
34688
  claudeagentsdk: "claudeAgentSDK",
33331
34689
  "claude-agent-sdk": "claudeAgentSDK",
34690
+ cloudflareaichat: "cloudflareAIChat",
34691
+ "cloudflare-ai-chat": "cloudflareAIChat",
34692
+ "@cloudflare/ai-chat": "cloudflareAIChat",
33332
34693
  cursor: "cursor",
33333
34694
  "cursor-sdk": "cursorSDK",
33334
34695
  cursorsdk: "cursorSDK",
@@ -33343,6 +34704,8 @@ var envIntegrationAliases = {
33343
34704
  "google-genai": "googleGenAI",
33344
34705
  googlegenai: "googleGenAI",
33345
34706
  huggingface: "huggingface",
34707
+ "@huggingface/transformers": "huggingface",
34708
+ transformers: "huggingface",
33346
34709
  openrouter: "openrouter",
33347
34710
  openrouteragent: "openrouterAgent",
33348
34711
  "openrouter-agent": "openrouterAgent",
@@ -33381,6 +34744,7 @@ function getDefaultInstrumentationIntegrations() {
33381
34744
  googleADK: true,
33382
34745
  huggingface: true,
33383
34746
  claudeAgentSDK: true,
34747
+ cloudflareAIChat: true,
33384
34748
  cursor: true,
33385
34749
  cursorSDK: true,
33386
34750
  flue: true,
@@ -33400,7 +34764,8 @@ function getDefaultInstrumentationIntegrations() {
33400
34764
  langgraph: true,
33401
34765
  langsmith: true,
33402
34766
  piCodingAgent: true,
33403
- strandsAgentSDK: true
34767
+ strandsAgentSDK: true,
34768
+ cloudflareAgents: true
33404
34769
  };
33405
34770
  }
33406
34771
  function readDisabledInstrumentationEnvConfig(disabledList) {
@@ -33418,7 +34783,9 @@ function readDisabledInstrumentationEnvConfig(disabledList) {
33418
34783
  }
33419
34784
 
33420
34785
  // src/instrumentation/registry.ts
33421
- var REGISTRY_STATE_KEY = /* @__PURE__ */ Symbol.for("braintrust.registry");
34786
+ var REGISTRY_STATE_KEY = /* @__PURE__ */ Symbol.for(
34787
+ `braintrust.registry.global-hooks.v${GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION}`
34788
+ );
33422
34789
  function getSharedState() {
33423
34790
  const state = globalThis[/* @__PURE__ */ Symbol.for("braintrust-state")];
33424
34791
  return state && typeof state === "object" ? state : void 0;
@@ -33523,11 +34890,6 @@ function configureEdgeLight() {
33523
34890
  if (runtimeAsyncLocalStorage) {
33524
34891
  isomorph_default.newAsyncLocalStorage = () => new runtimeAsyncLocalStorage();
33525
34892
  }
33526
- isomorph_default.newTracingChannel = (nameOrChannels) => (
33527
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
33528
- (0, import_dc_browser.tracingChannel)(nameOrChannels)
33529
- );
33530
- patchTracingChannel(import_dc_browser.tracingChannel);
33531
34893
  isomorph_default.getEnv = (name) => {
33532
34894
  if (typeof process === "undefined" || typeof process.env === "undefined") {
33533
34895
  return void 0;
@@ -33702,6 +35064,8 @@ __export(exports_exports, {
33702
35064
  wrapAnthropic: () => wrapAnthropic,
33703
35065
  wrapBedrockRuntime: () => wrapBedrockRuntime,
33704
35066
  wrapClaudeAgentSDK: () => wrapClaudeAgentSDK,
35067
+ wrapCloudflareAIChat: () => wrapCloudflareAIChat,
35068
+ wrapCloudflareAgent: () => wrapCloudflareAgent,
33705
35069
  wrapCohere: () => wrapCohere,
33706
35070
  wrapCopilotClient: () => wrapCopilotClient,
33707
35071
  wrapCursorSDK: () => wrapCursorSDK,
@@ -33710,6 +35074,7 @@ __export(exports_exports, {
33710
35074
  wrapGoogleGenAI: () => wrapGoogleGenAI,
33711
35075
  wrapGroq: () => wrapGroq,
33712
35076
  wrapHuggingFace: () => wrapHuggingFace,
35077
+ wrapHuggingFaceTransformers: () => wrapHuggingFaceTransformers,
33713
35078
  wrapLangSmithClient: () => wrapLangSmithClient,
33714
35079
  wrapLangSmithRunTrees: () => wrapLangSmithRunTrees,
33715
35080
  wrapLangSmithTraceable: () => wrapLangSmithTraceable,
@@ -35033,7 +36398,7 @@ function extractToolCallsFromBlocks(blocks) {
35033
36398
  if (!Array.isArray(blocks)) return [];
35034
36399
  return extractToolCallsFromSteps([{ content: blocks }]);
35035
36400
  }
35036
- function extractInput(params) {
36401
+ function extractInput2(params) {
35037
36402
  return params?.prompt ?? params?.messages ?? params?.system;
35038
36403
  }
35039
36404
  var V2_EXCLUDE_KEYS = /* @__PURE__ */ new Set([
@@ -35055,7 +36420,7 @@ function BraintrustMiddleware(config = {}) {
35055
36420
  params,
35056
36421
  model: modelFromWrapGenerate
35057
36422
  }) => {
35058
- const rawInput = extractInput(params);
36423
+ const rawInput = extractInput2(params);
35059
36424
  const processedInput = processInputAttachments(rawInput);
35060
36425
  const spanArgs = {
35061
36426
  name: config.spanInfo?.name || "ai-sdk.doGenerate",
@@ -35119,7 +36484,7 @@ function BraintrustMiddleware(config = {}) {
35119
36484
  }
35120
36485
  },
35121
36486
  wrapStream: async ({ doStream, params }) => {
35122
- const rawInput = extractInput(params);
36487
+ const rawInput = extractInput2(params);
35123
36488
  const processedInput = processInputAttachments(rawInput);
35124
36489
  const spanArgs = {
35125
36490
  name: config.spanInfo?.name || "ai-sdk.doStream",
@@ -37641,6 +39006,67 @@ function patchAgentSessionClass(AgentSession) {
37641
39006
  });
37642
39007
  }
37643
39008
 
39009
+ // src/wrappers/cloudflare-agent.ts
39010
+ var WRAPPED_RUN_AGENT_TOOL = /* @__PURE__ */ Symbol.for(
39011
+ "braintrust.cloudflare-agents.wrapped-run-agent-tool"
39012
+ );
39013
+ function wrapCloudflareAgent(Agent2) {
39014
+ if (typeof Agent2 !== "function") {
39015
+ warnUnsupportedAgent();
39016
+ return Agent2;
39017
+ }
39018
+ const prototypeDescriptor = Object.getOwnPropertyDescriptor(
39019
+ Agent2,
39020
+ "prototype"
39021
+ );
39022
+ const prototype = prototypeDescriptor && "value" in prototypeDescriptor ? prototypeDescriptor.value : void 0;
39023
+ if (!isObjectLike3(prototype)) {
39024
+ warnUnsupportedAgent();
39025
+ return Agent2;
39026
+ }
39027
+ if (ownValue4(prototype, WRAPPED_RUN_AGENT_TOOL) === true) {
39028
+ return Agent2;
39029
+ }
39030
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, "runAgentTool");
39031
+ if (!descriptor || typeof descriptor.value !== "function") {
39032
+ warnUnsupportedAgent();
39033
+ return Agent2;
39034
+ }
39035
+ const originalRunAgentTool = descriptor.value;
39036
+ Object.defineProperty(prototype, "runAgentTool", {
39037
+ ...descriptor,
39038
+ value: function wrappedRunAgentTool(...args) {
39039
+ const options = args[1];
39040
+ if (ownValue4(options, "detached")) {
39041
+ return Reflect.apply(originalRunAgentTool, this, args);
39042
+ }
39043
+ return cloudflareAgentsChannels.runAgentTool.tracePromise(
39044
+ () => Reflect.apply(originalRunAgentTool, this, args),
39045
+ { arguments: args, self: this }
39046
+ );
39047
+ }
39048
+ });
39049
+ Object.defineProperty(prototype, WRAPPED_RUN_AGENT_TOOL, {
39050
+ configurable: false,
39051
+ enumerable: false,
39052
+ value: true
39053
+ });
39054
+ return Agent2;
39055
+ }
39056
+ function ownValue4(value, key) {
39057
+ if (!isObjectLike3(value)) {
39058
+ return void 0;
39059
+ }
39060
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
39061
+ return descriptor && "value" in descriptor ? descriptor.value : void 0;
39062
+ }
39063
+ function isObjectLike3(value) {
39064
+ return typeof value === "object" && value !== null || typeof value === "function";
39065
+ }
39066
+ function warnUnsupportedAgent() {
39067
+ debugLogger.warn("Unsupported Cloudflare Agents Agent class. Not wrapping.");
39068
+ }
39069
+
37644
39070
  // src/wrappers/strands-agent-sdk.ts
37645
39071
  var WRAPPED_CLASS = /* @__PURE__ */ Symbol.for("braintrust.strands-agent-sdk.wrapped-class");
37646
39072
  var WRAPPED_INSTANCE = /* @__PURE__ */ Symbol.for(
@@ -37809,6 +39235,81 @@ async function consumeAsyncGenerator(generator) {
37809
39235
  return result.value;
37810
39236
  }
37811
39237
 
39238
+ // src/wrappers/cloudflare-ai-chat.ts
39239
+ var wrappedClasses = /* @__PURE__ */ new WeakMap();
39240
+ function wrapCloudflareAIChat(module2) {
39241
+ if (!module2 || typeof module2 !== "object") {
39242
+ return module2;
39243
+ }
39244
+ const candidate = module2;
39245
+ let AIChatAgent;
39246
+ try {
39247
+ AIChatAgent = Reflect.get(candidate, "AIChatAgent");
39248
+ } catch (error) {
39249
+ debugLogger.debug("Failed to inspect @cloudflare/ai-chat module:", error);
39250
+ return module2;
39251
+ }
39252
+ if (typeof AIChatAgent !== "function") {
39253
+ debugLogger.warn(
39254
+ "Unsupported @cloudflare/ai-chat module. AIChatAgent was not found; not wrapping."
39255
+ );
39256
+ return module2;
39257
+ }
39258
+ const target = isModuleNamespace5(module2) ? Object.setPrototypeOf({}, module2) : candidate;
39259
+ return new Proxy(target, {
39260
+ get(target2, property, receiver) {
39261
+ const value = Reflect.get(target2, property, receiver);
39262
+ if (property === "AIChatAgent" && typeof value === "function") {
39263
+ return wrapAIChatAgentClass(
39264
+ value
39265
+ );
39266
+ }
39267
+ return value;
39268
+ }
39269
+ });
39270
+ }
39271
+ function wrapAIChatAgentClass(AgentClass) {
39272
+ const cached = wrappedClasses.get(AgentClass);
39273
+ if (cached) {
39274
+ return cached;
39275
+ }
39276
+ const wrapped = new Proxy(AgentClass, {
39277
+ get(target, property) {
39278
+ const value = Reflect.get(target, property, target);
39279
+ return typeof value === "function" ? value.bind(target) : value;
39280
+ },
39281
+ construct(target, args, newTarget) {
39282
+ const instance = Reflect.construct(
39283
+ target,
39284
+ args,
39285
+ newTarget
39286
+ );
39287
+ return instrumentCloudflareAIChatAgent(instance);
39288
+ }
39289
+ });
39290
+ wrappedClasses.set(AgentClass, wrapped);
39291
+ wrappedClasses.set(wrapped, wrapped);
39292
+ return wrapped;
39293
+ }
39294
+ function isModuleNamespace5(value) {
39295
+ if (!value || typeof value !== "object") {
39296
+ return false;
39297
+ }
39298
+ try {
39299
+ if (Reflect.get(value, Symbol.toStringTag) === "Module") {
39300
+ return true;
39301
+ }
39302
+ const keys = Object.keys(value);
39303
+ if (keys.length === 0) {
39304
+ return false;
39305
+ }
39306
+ const descriptor = Object.getOwnPropertyDescriptor(value, keys[0]);
39307
+ return descriptor ? !descriptor.configurable && !descriptor.writable : false;
39308
+ } catch {
39309
+ return false;
39310
+ }
39311
+ }
39312
+
37812
39313
  // src/wrappers/google-genai.ts
37813
39314
  function wrapGoogleGenAI(googleGenAI) {
37814
39315
  if (!googleGenAI || typeof googleGenAI !== "object") {
@@ -38461,6 +39962,120 @@ function wrapFeatureExtraction(original, endpointUrl) {
38461
39962
  };
38462
39963
  }
38463
39964
 
39965
+ // src/wrappers/huggingface-transformers.ts
39966
+ var PIPELINE_CONSTRUCTOR_KEYS = /* @__PURE__ */ new Set([
39967
+ "TextGenerationPipeline",
39968
+ "Text2TextGenerationPipeline",
39969
+ "SummarizationPipeline",
39970
+ "FeatureExtractionPipeline",
39971
+ "QuestionAnsweringPipeline"
39972
+ ]);
39973
+ var wrappedValues = /* @__PURE__ */ new WeakMap();
39974
+ function wrapHuggingFaceTransformers(transformers) {
39975
+ const pipelineTask = transformers?.task;
39976
+ if (typeof transformers === "function" && isSupportedHuggingFaceTransformersTask(pipelineTask)) {
39977
+ return wrapPipeline(transformers);
39978
+ }
39979
+ if (!isSupportedModule(transformers)) {
39980
+ return transformers;
39981
+ }
39982
+ const existing = wrappedValues.get(transformers);
39983
+ if (existing) {
39984
+ return existing;
39985
+ }
39986
+ const proxy = new Proxy(Object.create(transformers), {
39987
+ get(_target, property, receiver) {
39988
+ const value = Reflect.get(transformers, property, receiver);
39989
+ if (property === "pipeline" && typeof value === "function") {
39990
+ return wrapPipelineFactory(value);
39991
+ }
39992
+ if (typeof property === "string" && PIPELINE_CONSTRUCTOR_KEYS.has(property) && typeof value === "function") {
39993
+ return wrapPipelineConstructor(
39994
+ value
39995
+ );
39996
+ }
39997
+ return value;
39998
+ }
39999
+ });
40000
+ wrappedValues.set(transformers, proxy);
40001
+ wrappedValues.set(proxy, proxy);
40002
+ return proxy;
40003
+ }
40004
+ function isSupportedModule(value) {
40005
+ if (value === null || typeof value !== "object" && typeof value !== "function") {
40006
+ return false;
40007
+ }
40008
+ if (typeof Reflect.get(value, "pipeline") === "function") {
40009
+ return true;
40010
+ }
40011
+ for (const key of PIPELINE_CONSTRUCTOR_KEYS) {
40012
+ if (typeof Reflect.get(value, key) === "function") {
40013
+ return true;
40014
+ }
40015
+ }
40016
+ return false;
40017
+ }
40018
+ function wrapPipelineFactory(factory) {
40019
+ const existing = wrappedValues.get(factory);
40020
+ if (existing) {
40021
+ return existing;
40022
+ }
40023
+ const wrapped = function(...args) {
40024
+ const [task] = args;
40025
+ const context = {
40026
+ arguments: args
40027
+ };
40028
+ return huggingFaceTransformersChannels.pipeline.tracePromise(() => Reflect.apply(factory, this, args), context).then((pipeline) => {
40029
+ if (isSupportedHuggingFaceTransformersTask(pipeline.task ?? task)) {
40030
+ return wrapPipeline(pipeline);
40031
+ }
40032
+ return pipeline;
40033
+ });
40034
+ };
40035
+ wrappedValues.set(factory, wrapped);
40036
+ wrappedValues.set(wrapped, wrapped);
40037
+ return wrapped;
40038
+ }
40039
+ function wrapPipelineConstructor(constructor) {
40040
+ const existing = wrappedValues.get(constructor);
40041
+ if (existing) {
40042
+ return existing;
40043
+ }
40044
+ const proxy = new Proxy(constructor, {
40045
+ construct(target, args, newTarget) {
40046
+ const pipeline = Reflect.construct(target, args, newTarget);
40047
+ if (isSupportedHuggingFaceTransformersTask(pipeline.task)) {
40048
+ return wrapPipeline(pipeline);
40049
+ }
40050
+ return pipeline;
40051
+ }
40052
+ });
40053
+ wrappedValues.set(constructor, proxy);
40054
+ wrappedValues.set(proxy, proxy);
40055
+ return proxy;
40056
+ }
40057
+ function wrapPipeline(pipeline) {
40058
+ const existing = wrappedValues.get(pipeline);
40059
+ if (existing) {
40060
+ return existing;
40061
+ }
40062
+ const proxy = new Proxy(pipeline, {
40063
+ apply(target, thisArg, args) {
40064
+ const context = {
40065
+ arguments: args,
40066
+ self: target
40067
+ };
40068
+ return huggingFaceTransformersChannels.pipelineCall.tracePromise(
40069
+ () => Reflect.apply(target, thisArg, args),
40070
+ context
40071
+ );
40072
+ }
40073
+ });
40074
+ wrappedValues.set(pipeline, proxy);
40075
+ wrappedValues.set(proxy, proxy);
40076
+ return proxy;
40077
+ }
40078
+
38464
40079
  // src/wrappers/openrouter-agent.ts
38465
40080
  function wrapOpenRouterAgent(agent) {
38466
40081
  const candidate = agent;
@@ -39177,7 +40792,7 @@ function wrapNamespaceExport(namespace, exportName, marker, wrap2) {
39177
40792
  );
39178
40793
  return namespace;
39179
40794
  }
39180
- const target = isModuleNamespace5(namespace) ? Object.setPrototypeOf({}, namespace) : candidate;
40795
+ const target = isModuleNamespace6(namespace) ? Object.setPrototypeOf({}, namespace) : candidate;
39181
40796
  const moduleNamespace = target !== candidate;
39182
40797
  let wrappedExport;
39183
40798
  return new Proxy(target, {
@@ -39211,7 +40826,7 @@ function wrapNamespaceExport(namespace, exportName, marker, wrap2) {
39211
40826
  }
39212
40827
  });
39213
40828
  }
39214
- function isModuleNamespace5(value) {
40829
+ function isModuleNamespace6(value) {
39215
40830
  if (!value || typeof value !== "object") {
39216
40831
  return false;
39217
40832
  }