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
@@ -44,84 +44,528 @@ __export(index_exports, {
44
44
  });
45
45
  module.exports = __toCommonJS(index_exports);
46
46
 
47
- // src/isomorph.ts
48
- var DefaultAsyncLocalStorage = class {
49
- constructor() {
50
- }
51
- enterWith(_) {
52
- }
53
- run(_, callback) {
54
- return callback();
47
+ // src/global-instrumentation-hooks.ts
48
+ var GLOBAL_INSTRUMENTATION_HOOKS_KEY = "__braintrust_instrumentation_hooks";
49
+ var GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION = 1;
50
+ var GLOBAL_INSTRUMENTATION_HOOKS_REGISTRY_BRAND = "braintrust.global-instrumentation-hooks.registry";
51
+ var GLOBAL_INSTRUMENTATION_HOOK_BRAND = "braintrust.global-instrumentation-hooks.hook";
52
+ var registryBrand = Symbol.for(GLOBAL_INSTRUMENTATION_HOOKS_REGISTRY_BRAND);
53
+ var hookBrand = Symbol.for(GLOBAL_INSTRUMENTATION_HOOK_BRAND);
54
+ var errorReporter;
55
+ function setGlobalHookErrorReporter(reporter) {
56
+ const previousReporter = errorReporter;
57
+ errorReporter = reporter;
58
+ return () => {
59
+ if (errorReporter === reporter) {
60
+ errorReporter = previousReporter;
61
+ }
62
+ };
63
+ }
64
+ function reportError(error) {
65
+ try {
66
+ errorReporter?.(error);
67
+ } catch {
55
68
  }
56
- getStore() {
57
- return void 0;
69
+ }
70
+ function setContextValue(context, key, value) {
71
+ try {
72
+ context[key] = value;
73
+ } catch (error) {
74
+ reportError(error);
58
75
  }
59
- };
60
- var DefaultChannel = class {
76
+ }
77
+ function wrapStoreRun(store, message, next, transform) {
78
+ return () => {
79
+ let context;
80
+ try {
81
+ context = transform ? transform(message) : message;
82
+ } catch (error) {
83
+ reportError(error);
84
+ return next();
85
+ }
86
+ let called = false;
87
+ let result;
88
+ let providerError;
89
+ let providerThrew = false;
90
+ const runNext = () => {
91
+ if (called) {
92
+ reportError(
93
+ new Error(
94
+ "Instrumentation store invoked its callback more than once"
95
+ )
96
+ );
97
+ if (providerThrew) {
98
+ throw providerError;
99
+ }
100
+ return result;
101
+ }
102
+ called = true;
103
+ try {
104
+ result = next();
105
+ return result;
106
+ } catch (error) {
107
+ providerThrew = true;
108
+ providerError = error;
109
+ throw error;
110
+ }
111
+ };
112
+ try {
113
+ store.run(context, runNext);
114
+ } catch (error) {
115
+ if (!providerThrew || error !== providerError) {
116
+ reportError(error);
117
+ }
118
+ }
119
+ if (!called) {
120
+ reportError(
121
+ new Error("Instrumentation store did not invoke its callback")
122
+ );
123
+ return runNext();
124
+ }
125
+ if (providerThrew) {
126
+ throw providerError;
127
+ }
128
+ return result;
129
+ };
130
+ }
131
+ var HookChannel = class {
61
132
  constructor(name) {
62
133
  this.name = name;
63
134
  }
64
135
  name;
65
- hasSubscribers = false;
66
- subscribe(_subscription) {
136
+ subscribers = [];
137
+ stores = /* @__PURE__ */ new Map();
138
+ get hasSubscribers() {
139
+ return this.subscribers.length > 0 || this.stores.size > 0;
67
140
  }
68
- unsubscribe(_subscription) {
69
- return false;
141
+ subscribe(subscription) {
142
+ if (typeof subscription !== "function") {
143
+ throw new TypeError("subscription must be a function");
144
+ }
145
+ this.subscribers = [...this.subscribers, subscription];
146
+ }
147
+ unsubscribe(subscription) {
148
+ const index = this.subscribers.indexOf(subscription);
149
+ if (index === -1) {
150
+ return false;
151
+ }
152
+ this.subscribers = [
153
+ ...this.subscribers.slice(0, index),
154
+ ...this.subscribers.slice(index + 1)
155
+ ];
156
+ return true;
70
157
  }
71
- bindStore(_store, _transform) {
158
+ bindStore(store, transform) {
159
+ if (!store || typeof store.run !== "function") {
160
+ throw new TypeError("store must have a run method");
161
+ }
162
+ this.stores.set(
163
+ store,
164
+ transform
165
+ );
72
166
  }
73
- unbindStore(_store) {
74
- return false;
167
+ unbindStore(store) {
168
+ return this.stores.delete(store);
75
169
  }
76
- publish(_message) {
170
+ publish(message) {
171
+ const subscribers = this.subscribers;
172
+ for (const subscriber of subscribers) {
173
+ try {
174
+ subscriber(message, this.name);
175
+ } catch (error) {
176
+ reportError(error);
177
+ }
178
+ }
77
179
  }
78
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
79
- runStores(_message, fn, thisArg, ...args) {
80
- return fn.apply(thisArg, args);
180
+ runStores(message, fn, thisArg, ...args) {
181
+ let run = () => {
182
+ this.publish(message);
183
+ return Reflect.apply(fn, thisArg, args);
184
+ };
185
+ for (const [store, transform] of this.stores.entries()) {
186
+ run = wrapStoreRun(store, message, run, transform);
187
+ }
188
+ return run();
81
189
  }
82
190
  };
83
- var DefaultTracingChannel = class {
191
+ var traceEvents = [
192
+ "start",
193
+ "end",
194
+ "asyncStart",
195
+ "asyncEnd",
196
+ "error"
197
+ ];
198
+ var TracingHook = class {
84
199
  start;
85
200
  end;
86
201
  asyncStart;
87
202
  asyncEnd;
88
203
  error;
89
204
  constructor(nameOrChannels) {
205
+ Object.defineProperty(this, hookBrand, {
206
+ configurable: false,
207
+ enumerable: false,
208
+ value: GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION,
209
+ writable: false
210
+ });
90
211
  if (typeof nameOrChannels === "string") {
91
- this.start = new DefaultChannel(`tracing:${nameOrChannels}:start`);
92
- this.end = new DefaultChannel(`tracing:${nameOrChannels}:end`);
93
- this.asyncStart = new DefaultChannel(
94
- `tracing:${nameOrChannels}:asyncStart`
95
- );
96
- this.asyncEnd = new DefaultChannel(`tracing:${nameOrChannels}:asyncEnd`);
97
- this.error = new DefaultChannel(`tracing:${nameOrChannels}:error`);
212
+ this.start = new HookChannel(`tracing:${nameOrChannels}:start`);
213
+ this.end = new HookChannel(`tracing:${nameOrChannels}:end`);
214
+ this.asyncStart = new HookChannel(`tracing:${nameOrChannels}:asyncStart`);
215
+ this.asyncEnd = new HookChannel(`tracing:${nameOrChannels}:asyncEnd`);
216
+ this.error = new HookChannel(`tracing:${nameOrChannels}:error`);
98
217
  return;
99
218
  }
100
- this.start = nameOrChannels.start ?? new DefaultChannel("tracing:start");
101
- this.end = nameOrChannels.end ?? new DefaultChannel("tracing:end");
102
- this.asyncStart = nameOrChannels.asyncStart ?? new DefaultChannel("tracing:asyncStart");
103
- this.asyncEnd = nameOrChannels.asyncEnd ?? new DefaultChannel("tracing:asyncEnd");
104
- this.error = nameOrChannels.error ?? new DefaultChannel("tracing:error");
219
+ this.start = nameOrChannels.start ?? new HookChannel("tracing:start");
220
+ this.end = nameOrChannels.end ?? new HookChannel("tracing:end");
221
+ this.asyncStart = nameOrChannels.asyncStart ?? new HookChannel("tracing:asyncStart");
222
+ this.asyncEnd = nameOrChannels.asyncEnd ?? new HookChannel("tracing:asyncEnd");
223
+ this.error = nameOrChannels.error ?? new HookChannel("tracing:error");
105
224
  }
106
225
  get hasSubscribers() {
107
226
  return this.start.hasSubscribers || this.end.hasSubscribers || this.asyncStart.hasSubscribers || this.asyncEnd.hasSubscribers || this.error.hasSubscribers;
108
227
  }
109
- subscribe(_handlers) {
228
+ subscribe(handlers) {
229
+ for (const eventName of traceEvents) {
230
+ const handler = handlers[eventName];
231
+ if (handler) {
232
+ this[eventName].subscribe(handler);
233
+ }
234
+ }
235
+ }
236
+ unsubscribe(handlers) {
237
+ let done = true;
238
+ for (const eventName of traceEvents) {
239
+ const handler = handlers[eventName];
240
+ if (handler && !this[eventName].unsubscribe(handler)) {
241
+ done = false;
242
+ }
243
+ }
244
+ return done;
245
+ }
246
+ traceSync(fn, message = {}, thisArg, ...args) {
247
+ if (!this.hasSubscribers) {
248
+ return Reflect.apply(fn, thisArg, args);
249
+ }
250
+ const context = message;
251
+ return this.start.runStores(message, () => {
252
+ try {
253
+ const result = Reflect.apply(fn, thisArg, args);
254
+ setContextValue(context, "result", result);
255
+ return result;
256
+ } catch (error) {
257
+ setContextValue(context, "error", error);
258
+ this.error.publish(message);
259
+ throw error;
260
+ } finally {
261
+ this.end.publish(message);
262
+ }
263
+ });
264
+ }
265
+ tracePromise(fn, message = {}, thisArg, ...args) {
266
+ if (!this.hasSubscribers) {
267
+ return Reflect.apply(fn, thisArg, args);
268
+ }
269
+ const context = message;
270
+ return this.start.runStores(message, () => {
271
+ let result;
272
+ try {
273
+ result = Reflect.apply(fn, thisArg, args);
274
+ } catch (error) {
275
+ setContextValue(context, "error", error);
276
+ this.error.publish(message);
277
+ this.end.publish(message);
278
+ throw error;
279
+ }
280
+ this.end.publish(message);
281
+ if (!result || typeof result !== "object" && typeof result !== "function") {
282
+ setContextValue(context, "result", result);
283
+ this.asyncStart.publish(message);
284
+ this.asyncEnd.publish(message);
285
+ return result;
286
+ }
287
+ let terminalPublished = false;
288
+ const finishUnobservedResult = (error) => {
289
+ reportError(error);
290
+ if (!terminalPublished) {
291
+ terminalPublished = true;
292
+ setContextValue(context, "result", result);
293
+ this.asyncStart.publish(message);
294
+ this.asyncEnd.publish(message);
295
+ }
296
+ return result;
297
+ };
298
+ let then;
299
+ try {
300
+ then = result.then;
301
+ } catch (error) {
302
+ return finishUnobservedResult(error);
303
+ }
304
+ if (typeof then !== "function") {
305
+ setContextValue(context, "result", result);
306
+ this.asyncStart.publish(message);
307
+ this.asyncEnd.publish(message);
308
+ return result;
309
+ }
310
+ const resolve = (resolved) => {
311
+ if (!terminalPublished) {
312
+ terminalPublished = true;
313
+ setContextValue(context, "result", resolved);
314
+ this.asyncStart.publish(message);
315
+ this.asyncEnd.publish(message);
316
+ }
317
+ return resolved;
318
+ };
319
+ let rejectionThrown = false;
320
+ let rejectionError;
321
+ const reject = (error) => {
322
+ if (!terminalPublished) {
323
+ terminalPublished = true;
324
+ setContextValue(context, "error", error);
325
+ this.error.publish(message);
326
+ this.asyncStart.publish(message);
327
+ this.asyncEnd.publish(message);
328
+ }
329
+ rejectionThrown = true;
330
+ rejectionError = error;
331
+ throw error;
332
+ };
333
+ let isPlainPromise;
334
+ try {
335
+ isPlainPromise = result instanceof Promise && result.constructor === Promise;
336
+ } catch (error) {
337
+ return finishUnobservedResult(error);
338
+ }
339
+ try {
340
+ if (isPlainPromise) {
341
+ return Reflect.apply(then, result, [resolve, reject]);
342
+ }
343
+ Reflect.apply(then, result, [
344
+ resolve,
345
+ (error) => {
346
+ try {
347
+ reject(error);
348
+ } catch {
349
+ }
350
+ }
351
+ ]);
352
+ } catch (error) {
353
+ if (rejectionThrown && error === rejectionError) {
354
+ return result;
355
+ }
356
+ return finishUnobservedResult(error);
357
+ }
358
+ return result;
359
+ });
110
360
  }
111
- unsubscribe(_handlers) {
361
+ traceCallback(fn, position = -1, message = {}, thisArg, ...args) {
362
+ if (!this.hasSubscribers) {
363
+ return Reflect.apply(fn, thisArg, args);
364
+ }
365
+ const context = message;
366
+ const callArgs = args.length > 0 ? args : context.arguments ?? args;
367
+ const callback = Array.prototype.at.call(callArgs, position);
368
+ if (typeof callback !== "function") {
369
+ return Reflect.apply(fn, thisArg, args);
370
+ }
371
+ const { asyncStart, asyncEnd, error: errorChannel } = this;
372
+ function wrappedCallback(error, result) {
373
+ if (error) {
374
+ setContextValue(context, "error", error);
375
+ errorChannel.publish(message);
376
+ } else {
377
+ setContextValue(context, "result", result);
378
+ }
379
+ return asyncStart.runStores(message, () => {
380
+ try {
381
+ return Reflect.apply(callback, this, arguments);
382
+ } finally {
383
+ asyncEnd.publish(message);
384
+ }
385
+ });
386
+ }
387
+ Array.prototype.splice.call(callArgs, position, 1, wrappedCallback);
388
+ return this.start.runStores(message, () => {
389
+ try {
390
+ return Reflect.apply(fn, thisArg, args);
391
+ } catch (error) {
392
+ setContextValue(context, "error", error);
393
+ this.error.publish(message);
394
+ throw error;
395
+ } finally {
396
+ this.end.publish(message);
397
+ }
398
+ });
399
+ }
400
+ };
401
+ var inertChannel = Object.freeze({
402
+ name: "braintrust:inert",
403
+ hasSubscribers: false,
404
+ subscribe() {
405
+ },
406
+ unsubscribe() {
407
+ return false;
408
+ },
409
+ bindStore() {
410
+ },
411
+ unbindStore() {
112
412
  return false;
413
+ },
414
+ publish() {
415
+ },
416
+ runStores(_message, fn, thisArg, ...args) {
417
+ return Reflect.apply(fn, thisArg, args);
113
418
  }
114
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
115
- traceSync(fn, _message, thisArg, ...args) {
116
- return fn.apply(thisArg, args);
419
+ });
420
+ var inertTracingHook = new TracingHook({
421
+ start: inertChannel,
422
+ end: inertChannel,
423
+ asyncStart: inertChannel,
424
+ asyncEnd: inertChannel,
425
+ error: inertChannel
426
+ });
427
+ function isHookChannel(value) {
428
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
429
+ return false;
117
430
  }
118
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
119
- tracePromise(fn, _message, thisArg, ...args) {
120
- return fn.apply(thisArg, args);
431
+ try {
432
+ const channel2 = value;
433
+ 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";
434
+ } catch {
435
+ return false;
121
436
  }
122
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
123
- traceCallback(fn, _position, _message, thisArg, ...args) {
124
- return fn.apply(thisArg, args);
437
+ }
438
+ function hasTracingHookShape(value) {
439
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
440
+ return false;
441
+ }
442
+ try {
443
+ const hook = value;
444
+ 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);
445
+ } catch {
446
+ return false;
447
+ }
448
+ }
449
+ function isCompatibleTracingHook(value) {
450
+ try {
451
+ return value[hookBrand] === GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION && hasTracingHookShape(value);
452
+ } catch {
453
+ return false;
454
+ }
455
+ }
456
+ function isCompatibleHookRegistry(value) {
457
+ try {
458
+ return value instanceof Map && value[registryBrand] === GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION;
459
+ } catch {
460
+ return false;
461
+ }
462
+ }
463
+ function getHookRegistry() {
464
+ let descriptor;
465
+ try {
466
+ descriptor = Object.getOwnPropertyDescriptor(
467
+ globalThis,
468
+ GLOBAL_INSTRUMENTATION_HOOKS_KEY
469
+ );
470
+ } catch (error) {
471
+ reportError(error);
472
+ return void 0;
473
+ }
474
+ if (descriptor && "value" in descriptor && isCompatibleHookRegistry(descriptor.value) && (descriptor.configurable || descriptor.enumerable === false)) {
475
+ if (descriptor.configurable || descriptor.writable) {
476
+ try {
477
+ Object.defineProperty(globalThis, GLOBAL_INSTRUMENTATION_HOOKS_KEY, {
478
+ configurable: false,
479
+ enumerable: false,
480
+ value: descriptor.value,
481
+ writable: false
482
+ });
483
+ } catch (error) {
484
+ reportError(error);
485
+ return void 0;
486
+ }
487
+ }
488
+ return descriptor.value;
489
+ }
490
+ if (descriptor && !descriptor.configurable) {
491
+ reportError(new Error("Incompatible global instrumentation hook registry"));
492
+ return void 0;
493
+ }
494
+ const registry2 = /* @__PURE__ */ new Map();
495
+ try {
496
+ Object.defineProperty(registry2, registryBrand, {
497
+ configurable: false,
498
+ enumerable: false,
499
+ value: GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION,
500
+ writable: false
501
+ });
502
+ } catch (error) {
503
+ reportError(error);
504
+ return void 0;
505
+ }
506
+ try {
507
+ Object.defineProperty(globalThis, GLOBAL_INSTRUMENTATION_HOOKS_KEY, {
508
+ configurable: false,
509
+ enumerable: false,
510
+ value: registry2,
511
+ writable: false
512
+ });
513
+ return registry2;
514
+ } catch (error) {
515
+ reportError(error);
516
+ return void 0;
517
+ }
518
+ }
519
+ function newGlobalTracingChannel(nameOrChannels) {
520
+ if (typeof nameOrChannels !== "string") {
521
+ return new TracingHook(nameOrChannels);
522
+ }
523
+ const registry2 = getHookRegistry();
524
+ if (!registry2) {
525
+ return inertTracingHook;
526
+ }
527
+ let existing;
528
+ try {
529
+ existing = Map.prototype.get.call(registry2, nameOrChannels);
530
+ } catch (error) {
531
+ reportError(error);
532
+ return inertTracingHook;
533
+ }
534
+ if (isCompatibleTracingHook(existing)) {
535
+ return existing;
536
+ }
537
+ if (existing !== void 0) {
538
+ reportError(
539
+ new Error(`Invalid global instrumentation hook: ${nameOrChannels}`)
540
+ );
541
+ try {
542
+ Map.prototype.delete.call(registry2, nameOrChannels);
543
+ } catch (error) {
544
+ reportError(error);
545
+ return inertTracingHook;
546
+ }
547
+ }
548
+ const hook = new TracingHook(nameOrChannels);
549
+ try {
550
+ Map.prototype.set.call(registry2, nameOrChannels, hook);
551
+ } catch (error) {
552
+ reportError(error);
553
+ return inertTracingHook;
554
+ }
555
+ return hook;
556
+ }
557
+
558
+ // src/isomorph.ts
559
+ var DefaultAsyncLocalStorage = class {
560
+ constructor() {
561
+ }
562
+ enterWith(_) {
563
+ }
564
+ run(_, callback) {
565
+ return callback();
566
+ }
567
+ getStore() {
568
+ return void 0;
125
569
  }
126
570
  };
127
571
  var iso = {
@@ -134,7 +578,7 @@ var iso = {
134
578
  getCallerLocation: () => void 0,
135
579
  newAsyncLocalStorage: () => new DefaultAsyncLocalStorage(),
136
580
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
137
- newTracingChannel: (nameOrChannels) => new DefaultTracingChannel(nameOrChannels),
581
+ newTracingChannel: (nameOrChannels) => newGlobalTracingChannel(nameOrChannels),
138
582
  processOn: (_0, _1) => {
139
583
  },
140
584
  basename: (filepath) => filepath.split(/[\\/]/).pop() || filepath,
@@ -474,6 +918,9 @@ var debugLogger = {
474
918
  return createDebugLogger(state);
475
919
  }
476
920
  };
921
+ setGlobalHookErrorReporter((error) => {
922
+ debugLogger.error("Global instrumentation hook error:", error);
923
+ });
477
924
 
478
925
  // src/queue.ts
479
926
  var DEFAULT_QUEUE_SIZE = 15e3;
@@ -2125,7 +2572,8 @@ var ApiKey = import_v36.z.object({
2125
2572
  user_email: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
2126
2573
  user_given_name: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
2127
2574
  user_family_name: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
2128
- org_id: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional()
2575
+ org_id: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
2576
+ expires_at: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional()
2129
2577
  });
2130
2578
  var TriggeredFunctionState = import_v36.z.object({
2131
2579
  triggered_xact_id: import_v36.z.string(),
@@ -2245,6 +2693,7 @@ var TopicMapData = import_v36.z.object({
2245
2693
  topic_names: import_v36.z.record(import_v36.z.string()).optional(),
2246
2694
  generation_settings: TopicMapGenerationSettings.optional(),
2247
2695
  disable_reconciliation: import_v36.z.boolean().optional(),
2696
+ reconcile_mode: import_v36.z.enum(["evolve", "names_only"]).optional(),
2248
2697
  distance_threshold: import_v36.z.number().optional(),
2249
2698
  btql_filter: import_v36.z.string().optional(),
2250
2699
  automation_btql_filter: import_v36.z.string().optional()
@@ -2825,7 +3274,12 @@ var ModelParams = import_v36.z.union([
2825
3274
  }).partial().passthrough()
2826
3275
  ]);
2827
3276
  var PromptOptionsNullish = import_v36.z.union([
2828
- import_v36.z.object({ model: import_v36.z.string(), params: ModelParams, position: import_v36.z.string() }).partial(),
3277
+ import_v36.z.object({
3278
+ model: import_v36.z.string(),
3279
+ params: ModelParams,
3280
+ position: import_v36.z.string(),
3281
+ endpoint_name: import_v36.z.union([import_v36.z.string(), import_v36.z.null()])
3282
+ }).partial(),
2829
3283
  import_v36.z.null()
2830
3284
  ]);
2831
3285
  var PromptParserNullish = import_v36.z.union([
@@ -2839,11 +3293,25 @@ var PromptParserNullish = import_v36.z.union([
2839
3293
  }),
2840
3294
  import_v36.z.null()
2841
3295
  ]);
3296
+ var PreprocessorSavedFunctionId = import_v36.z.union([
3297
+ import_v36.z.object({
3298
+ type: import_v36.z.literal("function"),
3299
+ id: import_v36.z.string(),
3300
+ version: import_v36.z.string().optional()
3301
+ }),
3302
+ import_v36.z.object({
3303
+ type: import_v36.z.literal("global"),
3304
+ name: import_v36.z.string(),
3305
+ function_type: import_v36.z.literal("preprocessor").optional().default("preprocessor")
3306
+ }),
3307
+ import_v36.z.null()
3308
+ ]);
2842
3309
  var PromptDataNullish = import_v36.z.union([
2843
3310
  import_v36.z.object({
2844
3311
  prompt: PromptBlockDataNullish,
2845
3312
  options: PromptOptionsNullish,
2846
3313
  parser: PromptParserNullish,
3314
+ preprocessor: PreprocessorSavedFunctionId,
2847
3315
  tool_functions: import_v36.z.union([import_v36.z.array(SavedFunctionId), import_v36.z.null()]),
2848
3316
  template_format: import_v36.z.union([
2849
3317
  import_v36.z.enum(["mustache", "nunjucks", "none"]),
@@ -3045,6 +3513,7 @@ var PromptData = import_v36.z.object({
3045
3513
  prompt: PromptBlockDataNullish,
3046
3514
  options: PromptOptionsNullish,
3047
3515
  parser: PromptParserNullish,
3516
+ preprocessor: PreprocessorSavedFunctionId,
3048
3517
  tool_functions: import_v36.z.union([import_v36.z.array(SavedFunctionId), import_v36.z.null()]),
3049
3518
  template_format: import_v36.z.union([
3050
3519
  import_v36.z.enum(["mustache", "nunjucks", "none"]),
@@ -3207,7 +3676,8 @@ var InvokeFunction = FunctionId.and(
3207
3676
  mode: StreamingMode,
3208
3677
  strict: import_v36.z.union([import_v36.z.boolean(), import_v36.z.null()]),
3209
3678
  mcp_auth: import_v36.z.record(import_v36.z.object({ oauth_token: import_v36.z.string() }).partial()),
3210
- overrides: import_v36.z.union([import_v36.z.object({}).partial().passthrough(), import_v36.z.null()])
3679
+ overrides: import_v36.z.union([import_v36.z.object({}).partial().passthrough(), import_v36.z.null()]),
3680
+ endpoint_name: import_v36.z.union([import_v36.z.string(), import_v36.z.null()])
3211
3681
  }).partial()
3212
3682
  );
3213
3683
  var MCPServer = import_v36.z.object({
@@ -3271,6 +3741,24 @@ var Organization = import_v36.z.object({
3271
3741
  created: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
3272
3742
  image_rendering_mode: ImageRenderingMode.optional()
3273
3743
  });
3744
+ var RetentionObjectType = import_v36.z.enum([
3745
+ "project_logs",
3746
+ "experiment",
3747
+ "dataset"
3748
+ ]);
3749
+ var OrgAutomation = import_v36.z.object({
3750
+ id: import_v36.z.string().uuid(),
3751
+ org_id: import_v36.z.string().uuid(),
3752
+ user_id: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
3753
+ created: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
3754
+ name: import_v36.z.string(),
3755
+ description: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
3756
+ config: import_v36.z.object({
3757
+ event_type: import_v36.z.literal("retention"),
3758
+ object_type: RetentionObjectType,
3759
+ retention_days: import_v36.z.number().int().gte(0)
3760
+ })
3761
+ });
3274
3762
  var ProjectSettings = import_v36.z.union([
3275
3763
  import_v36.z.object({
3276
3764
  comparison_key: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]),
@@ -3297,6 +3785,7 @@ var ProjectSettings = import_v36.z.union([
3297
3785
  import_v36.z.null()
3298
3786
  ]),
3299
3787
  disable_realtime_queries: import_v36.z.union([import_v36.z.boolean(), import_v36.z.null()]),
3788
+ monitor_charts_use_metrics_start: import_v36.z.union([import_v36.z.boolean(), import_v36.z.null()]),
3300
3789
  default_preprocessor: NullableSavedFunctionId
3301
3790
  }).partial(),
3302
3791
  import_v36.z.null()
@@ -3311,11 +3800,6 @@ var Project = import_v36.z.object({
3311
3800
  user_id: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
3312
3801
  settings: ProjectSettings.optional()
3313
3802
  });
3314
- var RetentionObjectType = import_v36.z.enum([
3315
- "project_logs",
3316
- "experiment",
3317
- "dataset"
3318
- ]);
3319
3803
  var TopicAutomationFacetModel = import_v36.z.union([
3320
3804
  import_v36.z.enum(["brain-facet-latest", "brain-facet-1", "brain-facet-2"]),
3321
3805
  import_v36.z.null()
@@ -3426,7 +3910,7 @@ var ProjectAutomation = import_v36.z.object({
3426
3910
  import_v36.z.object({
3427
3911
  event_type: import_v36.z.literal("retention"),
3428
3912
  object_type: RetentionObjectType,
3429
- retention_days: import_v36.z.number().gte(0)
3913
+ retention_days: import_v36.z.number().int().gte(0)
3430
3914
  }),
3431
3915
  import_v36.z.object({
3432
3916
  event_type: import_v36.z.literal("environment_update"),
@@ -3598,7 +4082,12 @@ var Prompt = import_v36.z.object({
3598
4082
  metadata: import_v36.z.union([import_v36.z.object({}).partial().passthrough(), import_v36.z.null()]).optional(),
3599
4083
  function_type: FunctionTypeEnumNullish.optional()
3600
4084
  });
3601
- var PromptOptions = import_v36.z.object({ model: import_v36.z.string(), params: ModelParams, position: import_v36.z.string() }).partial();
4085
+ var PromptOptions = import_v36.z.object({
4086
+ model: import_v36.z.string(),
4087
+ params: ModelParams,
4088
+ position: import_v36.z.string(),
4089
+ endpoint_name: import_v36.z.union([import_v36.z.string(), import_v36.z.null()])
4090
+ }).partial();
3602
4091
  var PromptSessionEvent = import_v36.z.object({
3603
4092
  id: import_v36.z.string(),
3604
4093
  _xact_id: import_v36.z.string(),
@@ -3681,7 +4170,8 @@ var RunEval = import_v36.z.object({
3681
4170
  stop_token: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
3682
4171
  extra_messages: import_v36.z.string().optional(),
3683
4172
  tags: import_v36.z.array(import_v36.z.string()).optional(),
3684
- mcp_auth: import_v36.z.record(import_v36.z.object({ oauth_token: import_v36.z.string() }).partial()).optional()
4173
+ mcp_auth: import_v36.z.record(import_v36.z.object({ oauth_token: import_v36.z.string() }).partial()).optional(),
4174
+ endpoint_name: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional()
3685
4175
  });
3686
4176
  var ServiceToken = import_v36.z.object({
3687
4177
  id: import_v36.z.string().uuid(),
@@ -3691,7 +4181,8 @@ var ServiceToken = import_v36.z.object({
3691
4181
  service_account_id: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
3692
4182
  service_account_email: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
3693
4183
  service_account_name: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
3694
- org_id: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional()
4184
+ org_id: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional(),
4185
+ expires_at: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]).optional()
3695
4186
  });
3696
4187
  var SpanIFrame = import_v36.z.object({
3697
4188
  id: import_v36.z.string().uuid(),
@@ -3813,6 +4304,13 @@ var ViewOptions = import_v36.z.union([
3813
4304
  }),
3814
4305
  import_v36.z.null()
3815
4306
  ]),
4307
+ pointSizeMetric: import_v36.z.union([
4308
+ import_v36.z.object({
4309
+ type: import_v36.z.enum(["none", "score", "metric", "metadata"]),
4310
+ value: import_v36.z.string()
4311
+ }),
4312
+ import_v36.z.null()
4313
+ ]),
3816
4314
  xAxisAggregation: import_v36.z.union([import_v36.z.string(), import_v36.z.null()]),
3817
4315
  chartAnnotations: import_v36.z.union([
3818
4316
  import_v36.z.array(import_v36.z.object({ id: import_v36.z.string(), text: import_v36.z.string() })),
@@ -4926,6 +5424,8 @@ var INSTRUMENTATION_NAMES = {
4926
5424
  BEDROCK_RUNTIME: "bedrock-runtime",
4927
5425
  BRAINTRUST_JS_LOGGER: "braintrust-js-logger",
4928
5426
  CLAUDE_AGENT_SDK: "claude-agent-sdk",
5427
+ CLOUDFLARE_AI_CHAT: "cloudflare-ai-chat",
5428
+ CLOUDFLARE_AGENTS: "cloudflare-agents",
4929
5429
  COHERE: "cohere",
4930
5430
  CURSOR_SDK: "cursor-sdk",
4931
5431
  EVE: "eve",
@@ -4951,7 +5451,7 @@ var INSTRUMENTATION_NAMES = {
4951
5451
  var INTERNAL_SPAN_INSTRUMENTATION_NAME = /* @__PURE__ */ Symbol.for(
4952
5452
  "braintrust.spanInstrumentationName"
4953
5453
  );
4954
- var SDK_VERSION = true ? "3.25.0" : "0.0.0";
5454
+ var SDK_VERSION = true ? "3.26.0" : "0.0.0";
4955
5455
  function withSpanInstrumentationName(args, instrumentationName) {
4956
5456
  return {
4957
5457
  ...args,
@@ -5146,12 +5646,13 @@ function applyMaskingToField(maskingFunction, data, fieldName) {
5146
5646
  var INITIAL_SPAN_WRITE_AS_MERGE = /* @__PURE__ */ Symbol(
5147
5647
  "braintrust.initial-span-write-as-merge"
5148
5648
  );
5649
+ var INTERNAL_SPAN_CONTEXT = /* @__PURE__ */ Symbol("braintrust.internal-span-context");
5149
5650
  var BRAINTRUST_CURRENT_SPAN_STORE = /* @__PURE__ */ Symbol.for(
5150
5651
  "braintrust.currentSpanStore"
5151
5652
  );
5152
5653
  var ContextManager = class {
5153
5654
  /**
5154
- * Returns the value to store in the ALS bound to a TracingChannel's start event.
5655
+ * Returns the value to store in the ALS bound to a global hook's start event.
5155
5656
  * In default mode this is the Span itself; in OTEL mode it is the OTEL Context
5156
5657
  * containing the span so that OTEL's own ALS stores a proper Context object.
5157
5658
  */
@@ -7695,6 +8196,12 @@ function _internalStartSpanWithInitialMerge(args) {
7695
8196
  [INITIAL_SPAN_WRITE_AS_MERGE]: true
7696
8197
  }).span;
7697
8198
  }
8199
+ function _internalStartSpanWithContext(args, context) {
8200
+ return startSpanAndIsLogger({
8201
+ ...args,
8202
+ [INTERNAL_SPAN_CONTEXT]: context
8203
+ }).span;
8204
+ }
7698
8205
  async function flush(options) {
7699
8206
  const state = options?.state ?? _globalState;
7700
8207
  return await state.bgLogger().flush();
@@ -8488,7 +8995,7 @@ var SpanImpl = class _SpanImpl {
8488
8995
  start: args.startTime ?? getCurrentUnixTimestamp()
8489
8996
  },
8490
8997
  context: mergeSpanOriginContext(
8491
- { ...callerLocation },
8998
+ { ...callerLocation, ...args[INTERNAL_SPAN_CONTEXT] },
8492
8999
  instrumentationName,
8493
9000
  this._state.spanOriginEnvironment
8494
9001
  ),
@@ -20347,11 +20854,11 @@ function summarizeEmbedContentOutput(response) {
20347
20854
  };
20348
20855
  }
20349
20856
  function populateUsageMetrics(metrics, usage) {
20350
- if (usage.promptTokenCount !== void 0) {
20351
- metrics.prompt_tokens = usage.promptTokenCount;
20857
+ if (usage.promptTokenCount !== void 0 || usage.toolUsePromptTokenCount !== void 0) {
20858
+ metrics.prompt_tokens = (usage.promptTokenCount ?? 0) + (usage.toolUsePromptTokenCount ?? 0);
20352
20859
  }
20353
- if (usage.candidatesTokenCount !== void 0) {
20354
- metrics.completion_tokens = usage.candidatesTokenCount;
20860
+ if (usage.candidatesTokenCount !== void 0 || usage.thoughtsTokenCount !== void 0) {
20861
+ metrics.completion_tokens = (usage.candidatesTokenCount ?? 0) + (usage.thoughtsTokenCount ?? 0);
20355
20862
  }
20356
20863
  if (usage.totalTokenCount !== void 0) {
20357
20864
  metrics.tokens = usage.totalTokenCount;
@@ -20362,13 +20869,26 @@ function populateUsageMetrics(metrics, usage) {
20362
20869
  if (usage.thoughtsTokenCount !== void 0) {
20363
20870
  metrics.completion_reasoning_tokens = usage.thoughtsTokenCount;
20364
20871
  }
20872
+ for (const detail of usage.promptTokensDetails ?? []) {
20873
+ if (detail.modality === "AUDIO" && detail.tokenCount !== void 0) {
20874
+ metrics.prompt_audio_tokens = (metrics.prompt_audio_tokens ?? 0) + detail.tokenCount;
20875
+ }
20876
+ }
20877
+ for (const detail of usage.candidatesTokensDetails ?? []) {
20878
+ if (detail.modality === "AUDIO" && detail.tokenCount !== void 0) {
20879
+ metrics.completion_audio_tokens = (metrics.completion_audio_tokens ?? 0) + detail.tokenCount;
20880
+ }
20881
+ if (detail.modality === "IMAGE" && detail.tokenCount !== void 0) {
20882
+ metrics.completion_image_tokens = (metrics.completion_image_tokens ?? 0) + detail.tokenCount;
20883
+ }
20884
+ }
20365
20885
  }
20366
20886
  function populateInteractionUsageMetrics(metrics, usage) {
20367
20887
  if (typeof usage.total_input_tokens === "number") {
20368
20888
  metrics.prompt_tokens = usage.total_input_tokens;
20369
20889
  }
20370
20890
  if (typeof usage.total_output_tokens === "number") {
20371
- metrics.completion_tokens = usage.total_output_tokens;
20891
+ metrics.completion_tokens = usage.total_output_tokens + (typeof usage.total_thought_tokens === "number" ? usage.total_thought_tokens : 0);
20372
20892
  }
20373
20893
  if (typeof usage.total_tokens === "number") {
20374
20894
  metrics.tokens = usage.total_tokens;
@@ -20379,6 +20899,24 @@ function populateInteractionUsageMetrics(metrics, usage) {
20379
20899
  if (typeof usage.total_thought_tokens === "number") {
20380
20900
  metrics.completion_reasoning_tokens = usage.total_thought_tokens;
20381
20901
  }
20902
+ for (const detail of Array.isArray(usage.input_tokens_by_modality) ? usage.input_tokens_by_modality : []) {
20903
+ if (typeof detail?.modality === "string" && detail.modality.toLowerCase() === "audio" && typeof detail.tokens === "number") {
20904
+ metrics.prompt_audio_tokens = (metrics.prompt_audio_tokens ?? 0) + detail.tokens;
20905
+ }
20906
+ }
20907
+ for (const detail of Array.isArray(usage.output_tokens_by_modality) ? usage.output_tokens_by_modality : []) {
20908
+ if (typeof detail?.modality !== "string" || typeof detail.tokens !== "number") {
20909
+ continue;
20910
+ }
20911
+ switch (detail.modality.toLowerCase()) {
20912
+ case "audio":
20913
+ metrics.completion_audio_tokens = (metrics.completion_audio_tokens ?? 0) + detail.tokens;
20914
+ break;
20915
+ case "image":
20916
+ metrics.completion_image_tokens = (metrics.completion_image_tokens ?? 0) + detail.tokens;
20917
+ break;
20918
+ }
20919
+ }
20382
20920
  }
20383
20921
  function aggregateGenerateContentChunks(chunks, startTime, firstTokenTime) {
20384
20922
  const end = getCurrentUnixTimestamp();
@@ -21117,6 +21655,299 @@ function extractTextGenerationStreamMetadata(chunks) {
21117
21655
  return void 0;
21118
21656
  }
21119
21657
 
21658
+ // src/instrumentation/plugins/huggingface-transformers-channels.ts
21659
+ var SUPPORTED_TASKS = /* @__PURE__ */ new Set([
21660
+ "text-generation",
21661
+ "text2text-generation",
21662
+ "summarization",
21663
+ "feature-extraction",
21664
+ "question-answering"
21665
+ ]);
21666
+ var pipelineInfo = /* @__PURE__ */ new WeakMap();
21667
+ function isSupportedHuggingFaceTransformersTask(task) {
21668
+ return typeof task === "string" && SUPPORTED_TASKS.has(task);
21669
+ }
21670
+ function registerHuggingFaceTransformersPipeline(pipeline, task, model) {
21671
+ if (typeof task !== "string") {
21672
+ return;
21673
+ }
21674
+ const info = { task };
21675
+ if (typeof model === "string") {
21676
+ info.model = model;
21677
+ }
21678
+ pipelineInfo.set(pipeline, info);
21679
+ }
21680
+ function getHuggingFaceTransformersPipelineInfo(pipeline) {
21681
+ return pipeline ? pipelineInfo.get(pipeline) : void 0;
21682
+ }
21683
+ var huggingFaceTransformersChannels = defineChannels(
21684
+ "@huggingface/transformers",
21685
+ {
21686
+ pipeline: channel({
21687
+ channelName: "pipeline",
21688
+ kind: "async"
21689
+ }),
21690
+ pipelineCall: channel({
21691
+ channelName: "pipeline.call",
21692
+ kind: "async"
21693
+ })
21694
+ },
21695
+ { instrumentationName: INSTRUMENTATION_NAMES.HUGGINGFACE }
21696
+ );
21697
+
21698
+ // src/instrumentation/plugins/huggingface-transformers-plugin.ts
21699
+ var REQUEST_METADATA_KEYS = [
21700
+ "temperature",
21701
+ "top_p",
21702
+ "max_tokens",
21703
+ "stop"
21704
+ ];
21705
+ var HuggingFaceTransformersPlugin = class extends BasePlugin {
21706
+ onEnable() {
21707
+ this.subscribeToPipelineFactory();
21708
+ this.unsubscribers.push(
21709
+ traceAsyncChannel(huggingFaceTransformersChannels.pipelineCall, {
21710
+ name: (_args, event) => {
21711
+ const task = getTask(event);
21712
+ const operation = task?.replaceAll("-", "_") ?? "unknown";
21713
+ return `huggingface.transformers.${operation}`;
21714
+ },
21715
+ type: "llm" /* LLM */,
21716
+ shouldTrace: (_args, event) => isSupportedHuggingFaceTransformersTask(
21717
+ getTask(event)
21718
+ ),
21719
+ extractInput: (args, event) => ({
21720
+ input: extractInput(
21721
+ getTask(event),
21722
+ args
21723
+ ),
21724
+ metadata: extractMetadata(
21725
+ event,
21726
+ args
21727
+ )
21728
+ }),
21729
+ extractOutput: (result, event) => extractOutput(
21730
+ getTask(event),
21731
+ result
21732
+ ),
21733
+ extractMetrics: () => ({})
21734
+ })
21735
+ );
21736
+ }
21737
+ onDisable() {
21738
+ this.unsubscribers = unsubscribeAll(this.unsubscribers);
21739
+ }
21740
+ subscribeToPipelineFactory() {
21741
+ const channel2 = huggingFaceTransformersChannels.pipeline.tracingChannel();
21742
+ const handlers = {
21743
+ asyncEnd: (event) => {
21744
+ if (typeof event.result !== "function") {
21745
+ return;
21746
+ }
21747
+ registerHuggingFaceTransformersPipeline(
21748
+ event.result,
21749
+ event.arguments?.[0],
21750
+ event.arguments?.[1]
21751
+ );
21752
+ }
21753
+ };
21754
+ channel2.subscribe(handlers);
21755
+ this.unsubscribers.push(() => channel2.unsubscribe(handlers));
21756
+ }
21757
+ };
21758
+ function getTask(event) {
21759
+ const self = event.self;
21760
+ const registeredTask = getHuggingFaceTransformersPipelineInfo(self)?.task;
21761
+ if (registeredTask !== void 0) {
21762
+ return registeredTask;
21763
+ }
21764
+ if (typeof self?.task === "string") {
21765
+ return self.task;
21766
+ }
21767
+ return void 0;
21768
+ }
21769
+ function extractMetadata(event, args) {
21770
+ const metadata = {
21771
+ provider: "huggingface"
21772
+ };
21773
+ const registeredModel = getHuggingFaceTransformersPipelineInfo(
21774
+ event.self
21775
+ )?.model;
21776
+ const model = registeredModel ?? modelIdentifier(event.self);
21777
+ if (model) {
21778
+ metadata.model = model;
21779
+ }
21780
+ const task = getTask(event);
21781
+ const options = task === "question-answering" ? args[2] : args[1];
21782
+ if (isObject(options)) {
21783
+ for (const key of REQUEST_METADATA_KEYS) {
21784
+ if (options[key] !== void 0) {
21785
+ metadata[key] = options[key];
21786
+ }
21787
+ }
21788
+ }
21789
+ return metadata;
21790
+ }
21791
+ function modelIdentifier(pipeline) {
21792
+ const model = pipeline?.model;
21793
+ if (!isObject(model)) {
21794
+ return void 0;
21795
+ }
21796
+ const config = isObject(model.config) ? model.config : void 0;
21797
+ for (const value of [
21798
+ config?._name_or_path,
21799
+ config?.name_or_path,
21800
+ config?.model_id,
21801
+ config?.modelId,
21802
+ model.name
21803
+ ]) {
21804
+ if (typeof value === "string" && value.length > 0) {
21805
+ return value;
21806
+ }
21807
+ }
21808
+ return void 0;
21809
+ }
21810
+ function extractInput(task, args) {
21811
+ switch (task) {
21812
+ case "feature-extraction":
21813
+ return args[0];
21814
+ case "question-answering": {
21815
+ const question = args[0];
21816
+ const context = args[1];
21817
+ if (Array.isArray(question) && Array.isArray(context) && question.every((value) => typeof value === "string") && context.every((value) => typeof value === "string")) {
21818
+ return question.map((value, index) => [
21819
+ {
21820
+ role: "user",
21821
+ content: `Context:
21822
+ ${context[index] ?? ""}
21823
+
21824
+ Question:
21825
+ ${value}`
21826
+ }
21827
+ ]);
21828
+ }
21829
+ if (typeof question === "string" && typeof context === "string") {
21830
+ return [
21831
+ {
21832
+ role: "user",
21833
+ content: `Context:
21834
+ ${context}
21835
+
21836
+ Question:
21837
+ ${question}`
21838
+ }
21839
+ ];
21840
+ }
21841
+ return { context, question };
21842
+ }
21843
+ }
21844
+ const input = args[0];
21845
+ if (task === "text-generation" && isChat(input)) {
21846
+ return input;
21847
+ }
21848
+ if (task === "text-generation" && Array.isArray(input) && input.every(isChat)) {
21849
+ return input;
21850
+ }
21851
+ if (typeof input === "string") {
21852
+ return [{ role: "user", content: input }];
21853
+ }
21854
+ if (Array.isArray(input) && input.every((value) => typeof value === "string")) {
21855
+ return input.map((value) => [
21856
+ {
21857
+ role: "user",
21858
+ content: value
21859
+ }
21860
+ ]);
21861
+ }
21862
+ return input;
21863
+ }
21864
+ function isChat(value) {
21865
+ return Array.isArray(value) && value.length > 0 && value.every(
21866
+ (message) => isObject(message) && typeof message.role === "string" && "content" in message
21867
+ );
21868
+ }
21869
+ function extractOutput(task, result) {
21870
+ switch (task) {
21871
+ case "feature-extraction":
21872
+ return summarizeEmbedding(result);
21873
+ case "question-answering":
21874
+ return choicesFromAnswers(result);
21875
+ default:
21876
+ return choicesFromGenerations(result);
21877
+ }
21878
+ }
21879
+ function summarizeEmbedding(result) {
21880
+ if (!isObject(result) || !Array.isArray(result.dims)) {
21881
+ return void 0;
21882
+ }
21883
+ const { dims } = result;
21884
+ if (dims.length === 0 || !dims.every((dimension) => typeof dimension === "number")) {
21885
+ return void 0;
21886
+ }
21887
+ if (dims.length === 1) {
21888
+ return { embedding_length: dims[0] };
21889
+ }
21890
+ if (dims.length === 2) {
21891
+ return {
21892
+ embedding_count: dims[0],
21893
+ embedding_length: dims[1]
21894
+ };
21895
+ }
21896
+ return {
21897
+ embedding_batch_count: dims[0],
21898
+ embedding_count: dims[1],
21899
+ embedding_length: dims.at(-1) ?? 0
21900
+ };
21901
+ }
21902
+ function choicesFromAnswers(result) {
21903
+ const answers = Array.isArray(result) ? result.flat() : [result];
21904
+ const choices = answers.flatMap((answer, index) => {
21905
+ if (!isObject(answer) || typeof answer.answer !== "string") {
21906
+ return [];
21907
+ }
21908
+ return [
21909
+ {
21910
+ index,
21911
+ finish_reason: "stop",
21912
+ message: {
21913
+ role: "assistant",
21914
+ content: answer.answer
21915
+ }
21916
+ }
21917
+ ];
21918
+ });
21919
+ return choices.length > 0 ? choices : void 0;
21920
+ }
21921
+ function choicesFromGenerations(result) {
21922
+ const generations = Array.isArray(result) ? result.flat() : [result];
21923
+ const choices = generations.flatMap((generation, index) => {
21924
+ if (!isObject(generation)) {
21925
+ return [];
21926
+ }
21927
+ const generated = generation.generated_text ?? generation.summary_text;
21928
+ let content;
21929
+ if (typeof generated === "string") {
21930
+ content = generated;
21931
+ } else if (isChat(generated)) {
21932
+ content = generated.at(-1)?.content;
21933
+ }
21934
+ if (typeof content !== "string") {
21935
+ return [];
21936
+ }
21937
+ return [
21938
+ {
21939
+ index,
21940
+ finish_reason: "stop",
21941
+ message: {
21942
+ role: "assistant",
21943
+ content
21944
+ }
21945
+ }
21946
+ ];
21947
+ });
21948
+ return choices.length > 0 ? choices : void 0;
21949
+ }
21950
+
21120
21951
  // src/instrumentation/plugins/openrouter-agent-channels.ts
21121
21952
  var openRouterAgentChannels = defineChannels(
21122
21953
  "@openrouter/agent",
@@ -24282,15 +25113,32 @@ function aggregateUsageFromEvents(events) {
24282
25113
  if (usage.thoughtsTokenCount !== void 0) {
24283
25114
  aggregated.thoughtsTokenCount = (aggregated.thoughtsTokenCount ?? 0) + usage.thoughtsTokenCount;
24284
25115
  }
25116
+ if (usage.toolUsePromptTokenCount !== void 0) {
25117
+ aggregated.toolUsePromptTokenCount = (aggregated.toolUsePromptTokenCount ?? 0) + usage.toolUsePromptTokenCount;
25118
+ }
25119
+ for (const detailsField of [
25120
+ "promptTokensDetails",
25121
+ "cacheTokensDetails",
25122
+ "candidatesTokensDetails",
25123
+ "toolUsePromptTokensDetails"
25124
+ ]) {
25125
+ const details = usage[detailsField];
25126
+ if (details !== void 0) {
25127
+ aggregated[detailsField] = [
25128
+ ...aggregated[detailsField] ?? [],
25129
+ ...details
25130
+ ];
25131
+ }
25132
+ }
24285
25133
  }
24286
25134
  return hasUsage ? aggregated : void 0;
24287
25135
  }
24288
25136
  function populateUsageMetrics2(metrics, usage) {
24289
- if (usage.promptTokenCount !== void 0) {
24290
- metrics.prompt_tokens = usage.promptTokenCount;
25137
+ if (usage.promptTokenCount !== void 0 || usage.toolUsePromptTokenCount !== void 0) {
25138
+ metrics.prompt_tokens = (usage.promptTokenCount ?? 0) + (usage.toolUsePromptTokenCount ?? 0);
24291
25139
  }
24292
- if (usage.candidatesTokenCount !== void 0) {
24293
- metrics.completion_tokens = usage.candidatesTokenCount;
25140
+ if (usage.candidatesTokenCount !== void 0 || usage.thoughtsTokenCount !== void 0) {
25141
+ metrics.completion_tokens = (usage.candidatesTokenCount ?? 0) + (usage.thoughtsTokenCount ?? 0);
24294
25142
  }
24295
25143
  if (usage.totalTokenCount !== void 0) {
24296
25144
  metrics.tokens = usage.totalTokenCount;
@@ -24301,6 +25149,19 @@ function populateUsageMetrics2(metrics, usage) {
24301
25149
  if (usage.thoughtsTokenCount !== void 0) {
24302
25150
  metrics.completion_reasoning_tokens = usage.thoughtsTokenCount;
24303
25151
  }
25152
+ for (const detail of usage.promptTokensDetails ?? []) {
25153
+ if (detail.modality === "AUDIO" && detail.tokenCount !== void 0) {
25154
+ metrics.prompt_audio_tokens = (metrics.prompt_audio_tokens ?? 0) + detail.tokenCount;
25155
+ }
25156
+ }
25157
+ for (const detail of usage.candidatesTokensDetails ?? []) {
25158
+ if (detail.modality === "AUDIO" && detail.tokenCount !== void 0) {
25159
+ metrics.completion_audio_tokens = (metrics.completion_audio_tokens ?? 0) + detail.tokenCount;
25160
+ }
25161
+ if (detail.modality === "IMAGE" && detail.tokenCount !== void 0) {
25162
+ metrics.completion_image_tokens = (metrics.completion_image_tokens ?? 0) + detail.tokenCount;
25163
+ }
25164
+ }
24304
25165
  }
24305
25166
  function cleanMetrics4(metrics) {
24306
25167
  const cleaned = {};
@@ -28666,7 +29527,7 @@ var LangSmithPlugin = class extends BasePlugin {
28666
29527
  const inputs = preferOwnValue(run, previous, "inputs");
28667
29528
  const outputs = preferOwnValue(run, previous, "outputs");
28668
29529
  const error = errorMessage(preferOwnValue(run, previous, "error"));
28669
- const metadata = extractMetadata(run, previous);
29530
+ const metadata = extractMetadata2(run, previous);
28670
29531
  const tags = extractTags(preferOwnValue(run, previous, "tags"));
28671
29532
  const metrics = extractMetrics(run, previous);
28672
29533
  span.log({
@@ -28771,7 +29632,7 @@ function mapRunType(runType) {
28771
29632
  return "task" /* TASK */;
28772
29633
  }
28773
29634
  }
28774
- function extractMetadata(run, previous) {
29635
+ function extractMetadata2(run, previous) {
28775
29636
  const extra = preferOwnValue(run, previous, "extra");
28776
29637
  const rawMetadata = ownValue(extra, "metadata");
28777
29638
  if (!isRecord2(rawMetadata)) {
@@ -30144,6 +31005,15 @@ function handleMultiAgentStreamEvent(state, event, activeChildParents) {
30144
31005
  logInstrumentationError5("Strands Agent SDK multi-agent event", error);
30145
31006
  }
30146
31007
  }
31008
+ function buildModelSpanInput(event, attachmentCache) {
31009
+ const systemPrompt = typeof event.agent?.systemPrompt === "string" && event.agent.systemPrompt.length > 0 ? event.agent.systemPrompt : void 0;
31010
+ const processedMessages = Array.isArray(event.agent?.messages) ? processStrandsInputAttachments(event.agent.messages, attachmentCache) : void 0;
31011
+ if (!systemPrompt) {
31012
+ return processedMessages;
31013
+ }
31014
+ const systemMessage = { role: "system", content: systemPrompt };
31015
+ return Array.isArray(processedMessages) ? [systemMessage, ...processedMessages] : [systemMessage];
31016
+ }
30147
31017
  function startModelSpan(state, event) {
30148
31018
  if (state.activeModel) {
30149
31019
  finalizeModelSpan(state);
@@ -30161,10 +31031,7 @@ function startModelSpan(state, event) {
30161
31031
  withSpanInstrumentationName(
30162
31032
  {
30163
31033
  event: {
30164
- input: Array.isArray(event.agent?.messages) ? processStrandsInputAttachments(
30165
- event.agent.messages,
30166
- state.attachmentCache
30167
- ) : void 0,
31034
+ input: buildModelSpanInput(event, state.attachmentCache),
30168
31035
  metadata
30169
31036
  },
30170
31037
  name: formatModelSpanName(model),
@@ -30804,6 +31671,532 @@ function logInstrumentationError5(context, error) {
30804
31671
  debugLogger.debug(`${context}:`, error);
30805
31672
  }
30806
31673
 
31674
+ // src/instrumentation/plugins/cloudflare-ai-chat-channels.ts
31675
+ var cloudflareAIChatChannels = defineChannels(
31676
+ "@cloudflare/ai-chat",
31677
+ {
31678
+ runExclusiveChatTurn: channel({
31679
+ channelName: "AIChatAgent._runExclusiveChatTurn",
31680
+ kind: "async"
31681
+ }),
31682
+ onChatResponse: channel({
31683
+ channelName: "AIChatAgent.onChatResponse",
31684
+ kind: "sync-stream"
31685
+ })
31686
+ },
31687
+ { instrumentationName: INSTRUMENTATION_NAMES.CLOUDFLARE_AI_CHAT }
31688
+ );
31689
+
31690
+ // src/instrumentation/plugins/cloudflare-ai-chat-instrumentation.ts
31691
+ var wrappedResponseHooks = /* @__PURE__ */ new WeakSet();
31692
+ function instrumentCloudflareAIChatResponseHook(agent) {
31693
+ try {
31694
+ const original = Reflect.get(agent, "onChatResponse");
31695
+ if (typeof original !== "function" || wrappedResponseHooks.has(original)) {
31696
+ return;
31697
+ }
31698
+ const wrapped = function(result) {
31699
+ const args = [result];
31700
+ return cloudflareAIChatChannels.onChatResponse.traceSync(
31701
+ () => Reflect.apply(original, this, args),
31702
+ {
31703
+ arguments: args,
31704
+ self: this
31705
+ }
31706
+ );
31707
+ };
31708
+ wrappedResponseHooks.add(wrapped);
31709
+ defineWrappedMethod(agent, "onChatResponse", original, wrapped);
31710
+ } catch (error) {
31711
+ debugLogger.debug(
31712
+ "Failed to wrap @cloudflare/ai-chat response hook:",
31713
+ error
31714
+ );
31715
+ }
31716
+ }
31717
+ function defineWrappedMethod(target, property, original, wrapped) {
31718
+ const ownDescriptor = Object.getOwnPropertyDescriptor(target, property);
31719
+ Object.defineProperty(target, property, {
31720
+ configurable: ownDescriptor?.configurable ?? true,
31721
+ enumerable: ownDescriptor?.enumerable ?? false,
31722
+ value: wrapped,
31723
+ writable: ownDescriptor && "writable" in ownDescriptor ? ownDescriptor.writable : true
31724
+ });
31725
+ try {
31726
+ Object.defineProperty(wrapped, "name", {
31727
+ configurable: true,
31728
+ value: original.name
31729
+ });
31730
+ } catch {
31731
+ }
31732
+ }
31733
+
31734
+ // src/instrumentation/plugins/cloudflare-ai-chat-plugin.ts
31735
+ var BLOCKED_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
31736
+ var RESPONSE_STATE_RETENTION_MS = 6e4;
31737
+ var CloudflareAIChatPlugin = class extends BasePlugin {
31738
+ activeStates = /* @__PURE__ */ new Set();
31739
+ activeTurns = /* @__PURE__ */ new WeakMap();
31740
+ eventStates = /* @__PURE__ */ new WeakMap();
31741
+ onEnable() {
31742
+ this.subscribeToResponseHook();
31743
+ this.subscribeToTurnRunner();
31744
+ }
31745
+ onDisable() {
31746
+ for (const unsubscribe of this.unsubscribers) {
31747
+ unsubscribe();
31748
+ }
31749
+ this.unsubscribers = [];
31750
+ for (const state of this.activeStates) {
31751
+ this.cleanupState(state);
31752
+ }
31753
+ this.activeStates.clear();
31754
+ }
31755
+ subscribeToTurnRunner() {
31756
+ const tracingChannel = cloudflareAIChatChannels.runExclusiveChatTurn.tracingChannel();
31757
+ const unbindCurrentSpanStore = this.bindCurrentSpanStore(tracingChannel);
31758
+ const handlers = {
31759
+ start: (event) => {
31760
+ this.ensureEventState(event);
31761
+ },
31762
+ asyncEnd: (event) => {
31763
+ this.finishEvent(event);
31764
+ },
31765
+ error: (event) => {
31766
+ this.finishEvent(event, event.error);
31767
+ }
31768
+ };
31769
+ tracingChannel.subscribe(handlers);
31770
+ this.unsubscribers.push(() => {
31771
+ unbindCurrentSpanStore?.();
31772
+ tracingChannel.unsubscribe(handlers);
31773
+ });
31774
+ }
31775
+ subscribeToResponseHook() {
31776
+ const tracingChannel = cloudflareAIChatChannels.onChatResponse.tracingChannel();
31777
+ const handlers = {
31778
+ start: (event) => {
31779
+ let state;
31780
+ try {
31781
+ const agent = asObject(event.self);
31782
+ const result = event.arguments[0];
31783
+ state = agent ? this.findResponseState(
31784
+ agent,
31785
+ stringValue3(ownValue2(result, "requestId"))
31786
+ ) : void 0;
31787
+ if (!state) {
31788
+ return;
31789
+ }
31790
+ state.responseObserved = true;
31791
+ const output = serializeMessage(ownValue2(result, "message"));
31792
+ const status = stringValue3(ownValue2(result, "status"));
31793
+ const error = ownValue2(result, "error");
31794
+ const input = ownValue2(result, "continuation") === true ? state.input : serializeMessages(readProperty(agent, "messages"))?.filter(
31795
+ (message) => typeof output?.id !== "string" || message.id !== output.id
31796
+ );
31797
+ state.span.log({
31798
+ ...input !== void 0 ? { input } : {},
31799
+ ...output !== void 0 ? { output } : {},
31800
+ ...status === "error" && error !== void 0 ? { error } : {}
31801
+ });
31802
+ } catch (error) {
31803
+ debugLogger.debug(
31804
+ "Failed to process @cloudflare/ai-chat response hook:",
31805
+ error
31806
+ );
31807
+ } finally {
31808
+ if (state?.settled) {
31809
+ this.cleanupState(state);
31810
+ }
31811
+ }
31812
+ }
31813
+ };
31814
+ tracingChannel.subscribe(handlers);
31815
+ this.unsubscribers.push(() => tracingChannel.unsubscribe(handlers));
31816
+ }
31817
+ bindCurrentSpanStore(tracingChannel) {
31818
+ const globalState = _internalGetGlobalState();
31819
+ const contextManager = globalState?.contextManager;
31820
+ const startChannel = tracingChannel.start;
31821
+ const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
31822
+ if (!startChannel || !currentSpanStore || !contextManager) {
31823
+ return void 0;
31824
+ }
31825
+ startChannel.bindStore(currentSpanStore, (event) => {
31826
+ const state = this.ensureEventState(event);
31827
+ return state ? contextManager.wrapSpanForStore(state.span) : currentSpanStore.getStore();
31828
+ });
31829
+ return () => startChannel.unbindStore(currentSpanStore);
31830
+ }
31831
+ ensureEventState(event) {
31832
+ const eventKey = event;
31833
+ const known = this.eventStates.get(eventKey);
31834
+ if (known) {
31835
+ return known;
31836
+ }
31837
+ try {
31838
+ const agent = asObject(event.self);
31839
+ const requestId = stringValue3(event.arguments[0]);
31840
+ const key = requestId ?? /* @__PURE__ */ Symbol("cloudflare-ai-chat-turn");
31841
+ const activeForAgent = agent ? this.getActiveTurns(agent) : void 0;
31842
+ const existing = activeForAgent?.get(key);
31843
+ const state = existing && !existing.settled ? existing : this.createTurnState(agent, key);
31844
+ if (existing && !existing.settled) {
31845
+ state.depth += 1;
31846
+ }
31847
+ this.eventStates.set(eventKey, state);
31848
+ this.bindTurnCallback(event, agent, state);
31849
+ if (agent) {
31850
+ instrumentCloudflareAIChatResponseHook(agent);
31851
+ }
31852
+ return state;
31853
+ } catch (error) {
31854
+ debugLogger.debug(
31855
+ "Failed to start @cloudflare/ai-chat instrumentation:",
31856
+ error
31857
+ );
31858
+ return void 0;
31859
+ }
31860
+ }
31861
+ createTurnState(agent, key) {
31862
+ const span = startSpan(
31863
+ withSpanInstrumentationName(
31864
+ {
31865
+ name: "AIChatAgent.onChatMessage",
31866
+ spanAttributes: { type: "task" /* TASK */ }
31867
+ },
31868
+ INSTRUMENTATION_NAMES.CLOUDFLARE_AI_CHAT
31869
+ )
31870
+ );
31871
+ const state = {
31872
+ agent,
31873
+ depth: 1,
31874
+ ended: false,
31875
+ key,
31876
+ responseObserved: false,
31877
+ settled: false,
31878
+ span
31879
+ };
31880
+ this.activeStates.add(state);
31881
+ if (agent) {
31882
+ this.getActiveTurns(agent).set(key, state);
31883
+ }
31884
+ return state;
31885
+ }
31886
+ bindTurnCallback(event, agent, state) {
31887
+ const callback = event.arguments[1];
31888
+ if (typeof callback !== "function") {
31889
+ return;
31890
+ }
31891
+ try {
31892
+ event.arguments[1] = function(...args) {
31893
+ return withCurrent(state.span, () => {
31894
+ try {
31895
+ const input = serializeMessages(readProperty(agent, "messages"));
31896
+ if (input !== void 0 && state.input === void 0) {
31897
+ state.input = input;
31898
+ state.span.log({ input });
31899
+ }
31900
+ } catch (error) {
31901
+ debugLogger.debug(
31902
+ "Failed to capture @cloudflare/ai-chat messages:",
31903
+ error
31904
+ );
31905
+ }
31906
+ return Reflect.apply(callback, this, args);
31907
+ });
31908
+ };
31909
+ } catch (error) {
31910
+ debugLogger.debug(
31911
+ "Failed to bind @cloudflare/ai-chat turn callback context:",
31912
+ error
31913
+ );
31914
+ }
31915
+ }
31916
+ finishEvent(event, error) {
31917
+ const eventKey = event;
31918
+ const state = this.eventStates.get(eventKey);
31919
+ if (!state || state.ended) {
31920
+ return;
31921
+ }
31922
+ this.eventStates.delete(eventKey);
31923
+ if (error !== void 0 && state.pendingError === void 0) {
31924
+ state.pendingError = error;
31925
+ }
31926
+ state.depth -= 1;
31927
+ if (state.depth === 0) {
31928
+ state.settled = true;
31929
+ this.endState(state);
31930
+ if (state.responseObserved || error !== void 0) {
31931
+ this.cleanupState(state);
31932
+ } else {
31933
+ state.cleanupTimer = setTimeout(
31934
+ () => this.cleanupState(state),
31935
+ RESPONSE_STATE_RETENTION_MS
31936
+ );
31937
+ if (typeof state.cleanupTimer === "object" && state.cleanupTimer !== null && "unref" in state.cleanupTimer && typeof state.cleanupTimer.unref === "function") {
31938
+ state.cleanupTimer.unref();
31939
+ }
31940
+ }
31941
+ }
31942
+ }
31943
+ endState(state) {
31944
+ if (state.ended) {
31945
+ return;
31946
+ }
31947
+ state.ended = true;
31948
+ try {
31949
+ if (state.pendingError !== void 0) {
31950
+ state.span.log({ error: state.pendingError });
31951
+ }
31952
+ } finally {
31953
+ state.span.end();
31954
+ }
31955
+ }
31956
+ cleanupState(state) {
31957
+ if (state.cleanupTimer !== void 0) {
31958
+ clearTimeout(state.cleanupTimer);
31959
+ state.cleanupTimer = void 0;
31960
+ }
31961
+ try {
31962
+ this.endState(state);
31963
+ } finally {
31964
+ this.activeStates.delete(state);
31965
+ if (state.agent) {
31966
+ const activeForAgent = this.activeTurns.get(state.agent);
31967
+ if (activeForAgent?.get(state.key) === state) {
31968
+ activeForAgent.delete(state.key);
31969
+ }
31970
+ }
31971
+ }
31972
+ }
31973
+ getActiveTurns(agent) {
31974
+ let turns = this.activeTurns.get(agent);
31975
+ if (!turns) {
31976
+ turns = /* @__PURE__ */ new Map();
31977
+ this.activeTurns.set(agent, turns);
31978
+ }
31979
+ return turns;
31980
+ }
31981
+ findResponseState(agent, requestId) {
31982
+ const turns = this.activeTurns.get(agent);
31983
+ if (!turns) {
31984
+ return void 0;
31985
+ }
31986
+ if (requestId !== void 0) {
31987
+ return turns.get(requestId);
31988
+ }
31989
+ const active = [...turns.values()];
31990
+ return active.length === 1 ? active[0] : void 0;
31991
+ }
31992
+ };
31993
+ function asObject(value) {
31994
+ return value !== null && (typeof value === "object" || typeof value === "function") ? value : void 0;
31995
+ }
31996
+ function readProperty(value, key) {
31997
+ const object = asObject(value);
31998
+ return object ? Reflect.get(object, key) : void 0;
31999
+ }
32000
+ function ownValue2(value, key) {
32001
+ const object = asObject(value);
32002
+ if (!object) {
32003
+ return void 0;
32004
+ }
32005
+ const descriptor = Object.getOwnPropertyDescriptor(object, key);
32006
+ return descriptor && "value" in descriptor ? descriptor.value : void 0;
32007
+ }
32008
+ function stringValue3(value) {
32009
+ return typeof value === "string" ? value : void 0;
32010
+ }
32011
+ function serializeMessages(value) {
32012
+ if (!Array.isArray(value)) {
32013
+ return void 0;
32014
+ }
32015
+ return value.flatMap((message) => {
32016
+ const serialized = serializeMessage(message);
32017
+ return serialized === void 0 ? [] : [serialized];
32018
+ });
32019
+ }
32020
+ function serializeMessage(value) {
32021
+ const message = asObject(value);
32022
+ if (!message) {
32023
+ return void 0;
32024
+ }
32025
+ const serialized = [];
32026
+ const id = ownValue2(message, "id");
32027
+ const role = ownValue2(message, "role");
32028
+ const parts = ownValue2(message, "parts");
32029
+ if (typeof id === "string") {
32030
+ serialized.push(["id", id]);
32031
+ }
32032
+ if (typeof role === "string") {
32033
+ serialized.push(["role", role]);
32034
+ }
32035
+ const sanitizedParts = sanitizeLoggedValue2(parts);
32036
+ if (sanitizedParts !== void 0) {
32037
+ serialized.push(["parts", sanitizedParts]);
32038
+ }
32039
+ return serialized.length > 0 ? Object.fromEntries(serialized) : void 0;
32040
+ }
32041
+ function sanitizeLoggedValue2(value, seen = /* @__PURE__ */ new WeakSet(), depth = 0) {
32042
+ if (value === null || typeof value === "string" || typeof value === "boolean") {
32043
+ return value;
32044
+ }
32045
+ if (typeof value === "number") {
32046
+ return Number.isFinite(value) ? value : void 0;
32047
+ }
32048
+ const object = asObject(value);
32049
+ if (!object || depth >= 20 || typeof value === "function") {
32050
+ return void 0;
32051
+ }
32052
+ if (seen.has(object)) {
32053
+ return "[Circular]";
32054
+ }
32055
+ seen.add(object);
32056
+ if (Array.isArray(value)) {
32057
+ return value.map((entry) => sanitizeLoggedValue2(entry, seen, depth + 1));
32058
+ }
32059
+ const entries = [];
32060
+ for (const [key, descriptor] of Object.entries(
32061
+ Object.getOwnPropertyDescriptors(object)
32062
+ )) {
32063
+ if (BLOCKED_KEYS.has(key) || !descriptor.enumerable || !("value" in descriptor)) {
32064
+ continue;
32065
+ }
32066
+ const sanitized = sanitizeLoggedValue2(descriptor.value, seen, depth + 1);
32067
+ if (sanitized !== void 0) {
32068
+ entries.push([key, sanitized]);
32069
+ }
32070
+ }
32071
+ return Object.fromEntries(entries);
32072
+ }
32073
+
32074
+ // src/instrumentation/plugins/cloudflare-agents-channels.ts
32075
+ var cloudflareAgentsChannels = defineChannels(
32076
+ "agents",
32077
+ {
32078
+ runAgentTool: channel({
32079
+ channelName: "Agent.runAgentTool",
32080
+ kind: "async"
32081
+ })
32082
+ },
32083
+ { instrumentationName: INSTRUMENTATION_NAMES.CLOUDFLARE_AGENTS }
32084
+ );
32085
+
32086
+ // src/instrumentation/plugins/cloudflare-agents-plugin.ts
32087
+ var CLOUDFLARE_WORKERS_CONTEXT = {
32088
+ span_origin: {
32089
+ environment: { type: "server", name: "cloudflare_workers" }
32090
+ }
32091
+ };
32092
+ var CloudflareAgentsPlugin = class extends BasePlugin {
32093
+ onEnable() {
32094
+ const channel2 = cloudflareAgentsChannels.runAgentTool.tracingChannel();
32095
+ const spans = /* @__PURE__ */ new WeakMap();
32096
+ const handlers = {
32097
+ start: (event) => {
32098
+ try {
32099
+ const agentClass = event.arguments[0];
32100
+ const options = event.arguments[1];
32101
+ if (ownValue3(options, "detached")) {
32102
+ return;
32103
+ }
32104
+ const name = ownValue3(agentClass, "name");
32105
+ if (typeof name !== "string" || name.length === 0) {
32106
+ debugLogger.warn(
32107
+ "Skipping Cloudflare Agents runAgentTool span because the child agent class has no name."
32108
+ );
32109
+ return;
32110
+ }
32111
+ const span = _internalStartSpanWithContext(
32112
+ withSpanInstrumentationName(
32113
+ {
32114
+ name,
32115
+ spanAttributes: { type: "tool" /* TOOL */ },
32116
+ event: {
32117
+ input: ownValue3(options, "input")
32118
+ }
32119
+ },
32120
+ INSTRUMENTATION_NAMES.CLOUDFLARE_AGENTS
32121
+ ),
32122
+ CLOUDFLARE_WORKERS_CONTEXT
32123
+ );
32124
+ spans.set(event, span);
32125
+ } catch (error) {
32126
+ logInstrumentationError6("start", error);
32127
+ }
32128
+ },
32129
+ asyncEnd: (event) => {
32130
+ const span = spans.get(event);
32131
+ if (!span) {
32132
+ return;
32133
+ }
32134
+ spans.delete(event);
32135
+ try {
32136
+ const status = ownValue3(event.result, "status");
32137
+ if (status === "completed") {
32138
+ span.log({ output: ownValue3(event.result, "output") });
32139
+ } else {
32140
+ const error = ownValue3(event.result, "error");
32141
+ if (typeof error === "string") {
32142
+ span.log({ error });
32143
+ }
32144
+ }
32145
+ } catch (error) {
32146
+ logInstrumentationError6("completion", error);
32147
+ } finally {
32148
+ safelyEndSpan(span);
32149
+ }
32150
+ },
32151
+ error: (event) => {
32152
+ const span = spans.get(event);
32153
+ if (!span) {
32154
+ return;
32155
+ }
32156
+ spans.delete(event);
32157
+ try {
32158
+ span.log({ error: event.error });
32159
+ } catch (error) {
32160
+ logInstrumentationError6("rejection", error);
32161
+ } finally {
32162
+ safelyEndSpan(span);
32163
+ }
32164
+ }
32165
+ };
32166
+ channel2.subscribe(handlers);
32167
+ this.unsubscribers.push(() => channel2.unsubscribe(handlers));
32168
+ }
32169
+ onDisable() {
32170
+ for (const unsubscribe of this.unsubscribers) {
32171
+ unsubscribe();
32172
+ }
32173
+ this.unsubscribers = [];
32174
+ }
32175
+ };
32176
+ function ownValue3(value, key) {
32177
+ if (!isObjectLike2(value)) {
32178
+ return void 0;
32179
+ }
32180
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
32181
+ return descriptor && "value" in descriptor ? descriptor.value : void 0;
32182
+ }
32183
+ function isObjectLike2(value) {
32184
+ return typeof value === "object" && value !== null || typeof value === "function";
32185
+ }
32186
+ function safelyEndSpan(span) {
32187
+ try {
32188
+ span.end();
32189
+ } catch (error) {
32190
+ logInstrumentationError6("span end", error);
32191
+ }
32192
+ }
32193
+ function logInstrumentationError6(operation, error) {
32194
+ debugLogger.error(
32195
+ `Failed to process Cloudflare Agents ${operation} instrumentation:`,
32196
+ error
32197
+ );
32198
+ }
32199
+
30807
32200
  // src/instrumentation/braintrust-plugin.ts
30808
32201
  var BraintrustPlugin = class extends BasePlugin {
30809
32202
  config;
@@ -30816,6 +32209,7 @@ var BraintrustPlugin = class extends BasePlugin {
30816
32209
  openAIAgentsPlugin = null;
30817
32210
  googleGenAIPlugin = null;
30818
32211
  huggingFacePlugin = null;
32212
+ huggingFaceTransformersPlugin = null;
30819
32213
  openRouterPlugin = null;
30820
32214
  openRouterAgentPlugin = null;
30821
32215
  mistralPlugin = null;
@@ -30830,6 +32224,8 @@ var BraintrustPlugin = class extends BasePlugin {
30830
32224
  langSmithPlugin = null;
30831
32225
  piCodingAgentPlugin = null;
30832
32226
  strandsAgentSDKPlugin = null;
32227
+ cloudflareAIChatPlugin = null;
32228
+ cloudflareAgentsPlugin = null;
30833
32229
  constructor(config = {}) {
30834
32230
  super();
30835
32231
  this.config = config;
@@ -30871,6 +32267,8 @@ var BraintrustPlugin = class extends BasePlugin {
30871
32267
  if (integrations.huggingface !== false) {
30872
32268
  this.huggingFacePlugin = new HuggingFacePlugin();
30873
32269
  this.huggingFacePlugin.enable();
32270
+ this.huggingFaceTransformersPlugin = new HuggingFaceTransformersPlugin();
32271
+ this.huggingFaceTransformersPlugin.enable();
30874
32272
  }
30875
32273
  if (integrations.openrouter !== false) {
30876
32274
  this.openRouterPlugin = new OpenRouterPlugin();
@@ -30916,6 +32314,14 @@ var BraintrustPlugin = class extends BasePlugin {
30916
32314
  this.strandsAgentSDKPlugin = new StrandsAgentSDKPlugin();
30917
32315
  this.strandsAgentSDKPlugin.enable();
30918
32316
  }
32317
+ if (integrations.cloudflareAIChat !== false) {
32318
+ this.cloudflareAIChatPlugin = new CloudflareAIChatPlugin();
32319
+ this.cloudflareAIChatPlugin.enable();
32320
+ }
32321
+ if (integrations.cloudflareAgents !== false) {
32322
+ this.cloudflareAgentsPlugin = new CloudflareAgentsPlugin();
32323
+ this.cloudflareAgentsPlugin.enable();
32324
+ }
30919
32325
  if (integrations.flue !== false) {
30920
32326
  this.fluePlugin = new FluePlugin();
30921
32327
  this.fluePlugin.enable();
@@ -30968,6 +32374,10 @@ var BraintrustPlugin = class extends BasePlugin {
30968
32374
  this.huggingFacePlugin.disable();
30969
32375
  this.huggingFacePlugin = null;
30970
32376
  }
32377
+ if (this.huggingFaceTransformersPlugin) {
32378
+ this.huggingFaceTransformersPlugin.disable();
32379
+ this.huggingFaceTransformersPlugin = null;
32380
+ }
30971
32381
  if (this.openRouterPlugin) {
30972
32382
  this.openRouterPlugin.disable();
30973
32383
  this.openRouterPlugin = null;
@@ -31012,6 +32422,14 @@ var BraintrustPlugin = class extends BasePlugin {
31012
32422
  this.strandsAgentSDKPlugin.disable();
31013
32423
  this.strandsAgentSDKPlugin = null;
31014
32424
  }
32425
+ if (this.cloudflareAIChatPlugin) {
32426
+ this.cloudflareAIChatPlugin.disable();
32427
+ this.cloudflareAIChatPlugin = null;
32428
+ }
32429
+ if (this.cloudflareAgentsPlugin) {
32430
+ this.cloudflareAgentsPlugin.disable();
32431
+ this.cloudflareAgentsPlugin = null;
32432
+ }
31015
32433
  if (this.fluePlugin) {
31016
32434
  this.fluePlugin.disable();
31017
32435
  this.fluePlugin = null;
@@ -32695,6 +34113,9 @@ var envIntegrationAliases = {
32695
34113
  strandsagentsdk: "strandsAgentSDK",
32696
34114
  "strands-agent-sdk": "strandsAgentSDK",
32697
34115
  "@strands-agents/sdk": "strandsAgentSDK",
34116
+ agents: "cloudflareAgents",
34117
+ "cloudflare-agents": "cloudflareAgents",
34118
+ cloudflareagents: "cloudflareAgents",
32698
34119
  anthropic: "anthropic",
32699
34120
  aisdk: "aisdk",
32700
34121
  "ai-sdk": "aisdk",
@@ -32702,6 +34123,9 @@ var envIntegrationAliases = {
32702
34123
  vercel: "vercel",
32703
34124
  claudeagentsdk: "claudeAgentSDK",
32704
34125
  "claude-agent-sdk": "claudeAgentSDK",
34126
+ cloudflareaichat: "cloudflareAIChat",
34127
+ "cloudflare-ai-chat": "cloudflareAIChat",
34128
+ "@cloudflare/ai-chat": "cloudflareAIChat",
32705
34129
  cursor: "cursor",
32706
34130
  "cursor-sdk": "cursorSDK",
32707
34131
  cursorsdk: "cursorSDK",
@@ -32716,6 +34140,8 @@ var envIntegrationAliases = {
32716
34140
  "google-genai": "googleGenAI",
32717
34141
  googlegenai: "googleGenAI",
32718
34142
  huggingface: "huggingface",
34143
+ "@huggingface/transformers": "huggingface",
34144
+ transformers: "huggingface",
32719
34145
  openrouter: "openrouter",
32720
34146
  openrouteragent: "openrouterAgent",
32721
34147
  "openrouter-agent": "openrouterAgent",
@@ -32754,6 +34180,7 @@ function getDefaultInstrumentationIntegrations() {
32754
34180
  googleADK: true,
32755
34181
  huggingface: true,
32756
34182
  claudeAgentSDK: true,
34183
+ cloudflareAIChat: true,
32757
34184
  cursor: true,
32758
34185
  cursorSDK: true,
32759
34186
  flue: true,
@@ -32773,7 +34200,8 @@ function getDefaultInstrumentationIntegrations() {
32773
34200
  langgraph: true,
32774
34201
  langsmith: true,
32775
34202
  piCodingAgent: true,
32776
- strandsAgentSDK: true
34203
+ strandsAgentSDK: true,
34204
+ cloudflareAgents: true
32777
34205
  };
32778
34206
  }
32779
34207
  function readDisabledInstrumentationEnvConfig(disabledList) {
@@ -32791,7 +34219,9 @@ function readDisabledInstrumentationEnvConfig(disabledList) {
32791
34219
  }
32792
34220
 
32793
34221
  // src/instrumentation/registry.ts
32794
- var REGISTRY_STATE_KEY = /* @__PURE__ */ Symbol.for("braintrust.registry");
34222
+ var REGISTRY_STATE_KEY = /* @__PURE__ */ Symbol.for(
34223
+ `braintrust.registry.global-hooks.v${GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION}`
34224
+ );
32795
34225
  function getSharedState() {
32796
34226
  const state = globalThis[/* @__PURE__ */ Symbol.for("braintrust-state")];
32797
34227
  return state && typeof state === "object" ? state : void 0;