braintrust 3.25.0 → 3.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/NOTICE +6 -0
  2. package/dev/dist/index.d.mts +130 -2
  3. package/dev/dist/index.d.ts +130 -2
  4. package/dev/dist/index.js +2455 -1116
  5. package/dev/dist/index.mjs +1599 -260
  6. package/dist/apply-auto-instrumentation.js +439 -398
  7. package/dist/apply-auto-instrumentation.mjs +242 -201
  8. package/dist/auto-instrumentations/bundler/esbuild.cjs +853 -337
  9. package/dist/auto-instrumentations/bundler/esbuild.d.mts +4 -4
  10. package/dist/auto-instrumentations/bundler/esbuild.d.ts +4 -4
  11. package/dist/auto-instrumentations/bundler/esbuild.mjs +5 -8
  12. package/dist/auto-instrumentations/bundler/next.cjs +852 -356
  13. package/dist/auto-instrumentations/bundler/next.mjs +6 -29
  14. package/dist/auto-instrumentations/bundler/rollup.cjs +853 -337
  15. package/dist/auto-instrumentations/bundler/rollup.d.mts +4 -4
  16. package/dist/auto-instrumentations/bundler/rollup.d.ts +4 -4
  17. package/dist/auto-instrumentations/bundler/rollup.mjs +5 -8
  18. package/dist/auto-instrumentations/bundler/vite.cjs +853 -337
  19. package/dist/auto-instrumentations/bundler/vite.d.mts +4 -4
  20. package/dist/auto-instrumentations/bundler/vite.d.ts +4 -4
  21. package/dist/auto-instrumentations/bundler/vite.mjs +5 -8
  22. package/dist/auto-instrumentations/bundler/webpack-loader.cjs +1006 -266
  23. package/dist/auto-instrumentations/bundler/webpack-loader.d.ts +20 -12
  24. package/dist/auto-instrumentations/bundler/webpack.cjs +853 -337
  25. package/dist/auto-instrumentations/bundler/webpack.d.mts +4 -4
  26. package/dist/auto-instrumentations/bundler/webpack.d.ts +4 -4
  27. package/dist/auto-instrumentations/bundler/webpack.mjs +5 -4
  28. package/dist/auto-instrumentations/{chunk-JPVCUKTY.mjs → chunk-6E22MYSW.mjs} +165 -73
  29. package/dist/auto-instrumentations/{chunk-VT6DDNKM.mjs → chunk-AKKPLXTP.mjs} +631 -194
  30. package/dist/auto-instrumentations/chunk-NRE4QUQR.mjs +509 -0
  31. package/dist/auto-instrumentations/{chunk-7P6563SW.mjs → chunk-V5LEODRX.mjs} +2 -6
  32. package/dist/auto-instrumentations/{chunk-M6DLIJ2Z.mjs → chunk-XYN63IG5.mjs} +124 -194
  33. package/dist/auto-instrumentations/{chunk-CZ24KNHT.mjs → chunk-XZHHE4Y3.mjs} +77 -68
  34. package/dist/auto-instrumentations/hook.mjs +247 -182
  35. package/dist/auto-instrumentations/index.cjs +557 -48
  36. package/dist/auto-instrumentations/index.d.mts +6 -2
  37. package/dist/auto-instrumentations/index.d.ts +6 -2
  38. package/dist/auto-instrumentations/index.mjs +6 -1
  39. package/dist/auto-instrumentations/loader/cjs-patch.cjs +492 -195
  40. package/dist/auto-instrumentations/loader/cjs-patch.d.mts +2 -2
  41. package/dist/auto-instrumentations/loader/cjs-patch.d.ts +2 -2
  42. package/dist/auto-instrumentations/loader/cjs-patch.mjs +3 -2
  43. package/dist/auto-instrumentations/loader/esm-hook.mjs +1 -1
  44. package/dist/auto-instrumentations/plugin-B-aZh7EP.d.ts +30 -0
  45. package/dist/auto-instrumentations/plugin-Bnj4E_6B.d.mts +30 -0
  46. package/dist/auto-instrumentations/{types-RNPaKi9o.d.mts → types-C1fVeiCp.d.mts} +1 -1
  47. package/dist/auto-instrumentations/{types-RNPaKi9o.d.ts → types-C1fVeiCp.d.ts} +1 -1
  48. package/dist/browser.d.mts +817 -197
  49. package/dist/browser.d.ts +817 -197
  50. package/dist/browser.js +1883 -265
  51. package/dist/browser.mjs +1883 -265
  52. package/dist/{chunk-ABR2QWDP.mjs → chunk-PN7EWK66.mjs} +581 -133
  53. package/dist/{chunk-GSIDVFE6.js → chunk-VRZZQPAA.js} +1670 -736
  54. package/dist/{chunk-P25IOOU4.js → chunk-VYNNEKSA.js} +586 -138
  55. package/dist/{chunk-2SANLSWX.mjs → chunk-XIZOM2HO.mjs} +1052 -118
  56. package/dist/cli.js +1601 -263
  57. package/dist/edge-light.d.mts +1 -1
  58. package/dist/edge-light.d.ts +1 -1
  59. package/dist/edge-light.js +1883 -268
  60. package/dist/edge-light.mjs +1883 -268
  61. package/dist/index.d.mts +817 -197
  62. package/dist/index.d.ts +817 -197
  63. package/dist/index.js +695 -435
  64. package/dist/index.mjs +264 -4
  65. package/dist/instrumentation/index.d.mts +130 -6
  66. package/dist/instrumentation/index.d.ts +130 -6
  67. package/dist/instrumentation/index.js +1510 -80
  68. package/dist/instrumentation/index.mjs +1510 -80
  69. package/dist/vitest-evals-reporter.js +16 -16
  70. package/dist/vitest-evals-reporter.mjs +2 -2
  71. package/dist/workerd.d.mts +1 -1
  72. package/dist/workerd.d.ts +1 -1
  73. package/dist/workerd.js +1883 -268
  74. package/dist/workerd.mjs +1883 -268
  75. package/licenses/node-diagnostics-channel/LICENSE +19 -0
  76. package/package.json +34 -35
  77. package/dist/auto-instrumentations/plugin-D0KHwSJv.d.mts +0 -44
  78. package/dist/auto-instrumentations/plugin-G6fgxk1b.d.ts +0 -44
package/dist/workerd.mjs CHANGED
@@ -4,84 +4,528 @@ var __export = (target, all) => {
4
4
  __defProp(target, name, { get: all[name], enumerable: true });
5
5
  };
6
6
 
7
- // src/isomorph.ts
8
- var DefaultAsyncLocalStorage = class {
9
- constructor() {
10
- }
11
- enterWith(_) {
12
- }
13
- run(_, callback) {
14
- return callback();
7
+ // src/global-instrumentation-hooks.ts
8
+ var GLOBAL_INSTRUMENTATION_HOOKS_KEY = "__braintrust_instrumentation_hooks";
9
+ var GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION = 1;
10
+ var GLOBAL_INSTRUMENTATION_HOOKS_REGISTRY_BRAND = "braintrust.global-instrumentation-hooks.registry";
11
+ var GLOBAL_INSTRUMENTATION_HOOK_BRAND = "braintrust.global-instrumentation-hooks.hook";
12
+ var registryBrand = Symbol.for(GLOBAL_INSTRUMENTATION_HOOKS_REGISTRY_BRAND);
13
+ var hookBrand = Symbol.for(GLOBAL_INSTRUMENTATION_HOOK_BRAND);
14
+ var errorReporter;
15
+ function setGlobalHookErrorReporter(reporter) {
16
+ const previousReporter = errorReporter;
17
+ errorReporter = reporter;
18
+ return () => {
19
+ if (errorReporter === reporter) {
20
+ errorReporter = previousReporter;
21
+ }
22
+ };
23
+ }
24
+ function reportError(error) {
25
+ try {
26
+ errorReporter?.(error);
27
+ } catch {
15
28
  }
16
- getStore() {
17
- return void 0;
29
+ }
30
+ function setContextValue(context, key, value) {
31
+ try {
32
+ context[key] = value;
33
+ } catch (error) {
34
+ reportError(error);
18
35
  }
19
- };
20
- var DefaultChannel = class {
36
+ }
37
+ function wrapStoreRun(store, message, next, transform) {
38
+ return () => {
39
+ let context;
40
+ try {
41
+ context = transform ? transform(message) : message;
42
+ } catch (error) {
43
+ reportError(error);
44
+ return next();
45
+ }
46
+ let called = false;
47
+ let result;
48
+ let providerError;
49
+ let providerThrew = false;
50
+ const runNext = () => {
51
+ if (called) {
52
+ reportError(
53
+ new Error(
54
+ "Instrumentation store invoked its callback more than once"
55
+ )
56
+ );
57
+ if (providerThrew) {
58
+ throw providerError;
59
+ }
60
+ return result;
61
+ }
62
+ called = true;
63
+ try {
64
+ result = next();
65
+ return result;
66
+ } catch (error) {
67
+ providerThrew = true;
68
+ providerError = error;
69
+ throw error;
70
+ }
71
+ };
72
+ try {
73
+ store.run(context, runNext);
74
+ } catch (error) {
75
+ if (!providerThrew || error !== providerError) {
76
+ reportError(error);
77
+ }
78
+ }
79
+ if (!called) {
80
+ reportError(
81
+ new Error("Instrumentation store did not invoke its callback")
82
+ );
83
+ return runNext();
84
+ }
85
+ if (providerThrew) {
86
+ throw providerError;
87
+ }
88
+ return result;
89
+ };
90
+ }
91
+ var HookChannel = class {
21
92
  constructor(name) {
22
93
  this.name = name;
23
94
  }
24
95
  name;
25
- hasSubscribers = false;
26
- subscribe(_subscription) {
96
+ subscribers = [];
97
+ stores = /* @__PURE__ */ new Map();
98
+ get hasSubscribers() {
99
+ return this.subscribers.length > 0 || this.stores.size > 0;
27
100
  }
28
- unsubscribe(_subscription) {
29
- return false;
101
+ subscribe(subscription) {
102
+ if (typeof subscription !== "function") {
103
+ throw new TypeError("subscription must be a function");
104
+ }
105
+ this.subscribers = [...this.subscribers, subscription];
30
106
  }
31
- bindStore(_store, _transform) {
107
+ unsubscribe(subscription) {
108
+ const index = this.subscribers.indexOf(subscription);
109
+ if (index === -1) {
110
+ return false;
111
+ }
112
+ this.subscribers = [
113
+ ...this.subscribers.slice(0, index),
114
+ ...this.subscribers.slice(index + 1)
115
+ ];
116
+ return true;
32
117
  }
33
- unbindStore(_store) {
34
- return false;
118
+ bindStore(store, transform) {
119
+ if (!store || typeof store.run !== "function") {
120
+ throw new TypeError("store must have a run method");
121
+ }
122
+ this.stores.set(
123
+ store,
124
+ transform
125
+ );
35
126
  }
36
- publish(_message) {
127
+ unbindStore(store) {
128
+ return this.stores.delete(store);
37
129
  }
38
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
39
- runStores(_message, fn, thisArg, ...args) {
40
- return fn.apply(thisArg, args);
130
+ publish(message) {
131
+ const subscribers = this.subscribers;
132
+ for (const subscriber of subscribers) {
133
+ try {
134
+ subscriber(message, this.name);
135
+ } catch (error) {
136
+ reportError(error);
137
+ }
138
+ }
139
+ }
140
+ runStores(message, fn, thisArg, ...args) {
141
+ let run = () => {
142
+ this.publish(message);
143
+ return Reflect.apply(fn, thisArg, args);
144
+ };
145
+ for (const [store, transform] of this.stores.entries()) {
146
+ run = wrapStoreRun(store, message, run, transform);
147
+ }
148
+ return run();
41
149
  }
42
150
  };
43
- var DefaultTracingChannel = class {
151
+ var traceEvents = [
152
+ "start",
153
+ "end",
154
+ "asyncStart",
155
+ "asyncEnd",
156
+ "error"
157
+ ];
158
+ var TracingHook = class {
44
159
  start;
45
160
  end;
46
161
  asyncStart;
47
162
  asyncEnd;
48
163
  error;
49
164
  constructor(nameOrChannels) {
165
+ Object.defineProperty(this, hookBrand, {
166
+ configurable: false,
167
+ enumerable: false,
168
+ value: GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION,
169
+ writable: false
170
+ });
50
171
  if (typeof nameOrChannels === "string") {
51
- this.start = new DefaultChannel(`tracing:${nameOrChannels}:start`);
52
- this.end = new DefaultChannel(`tracing:${nameOrChannels}:end`);
53
- this.asyncStart = new DefaultChannel(
54
- `tracing:${nameOrChannels}:asyncStart`
55
- );
56
- this.asyncEnd = new DefaultChannel(`tracing:${nameOrChannels}:asyncEnd`);
57
- this.error = new DefaultChannel(`tracing:${nameOrChannels}:error`);
172
+ this.start = new HookChannel(`tracing:${nameOrChannels}:start`);
173
+ this.end = new HookChannel(`tracing:${nameOrChannels}:end`);
174
+ this.asyncStart = new HookChannel(`tracing:${nameOrChannels}:asyncStart`);
175
+ this.asyncEnd = new HookChannel(`tracing:${nameOrChannels}:asyncEnd`);
176
+ this.error = new HookChannel(`tracing:${nameOrChannels}:error`);
58
177
  return;
59
178
  }
60
- this.start = nameOrChannels.start ?? new DefaultChannel("tracing:start");
61
- this.end = nameOrChannels.end ?? new DefaultChannel("tracing:end");
62
- this.asyncStart = nameOrChannels.asyncStart ?? new DefaultChannel("tracing:asyncStart");
63
- this.asyncEnd = nameOrChannels.asyncEnd ?? new DefaultChannel("tracing:asyncEnd");
64
- this.error = nameOrChannels.error ?? new DefaultChannel("tracing:error");
179
+ this.start = nameOrChannels.start ?? new HookChannel("tracing:start");
180
+ this.end = nameOrChannels.end ?? new HookChannel("tracing:end");
181
+ this.asyncStart = nameOrChannels.asyncStart ?? new HookChannel("tracing:asyncStart");
182
+ this.asyncEnd = nameOrChannels.asyncEnd ?? new HookChannel("tracing:asyncEnd");
183
+ this.error = nameOrChannels.error ?? new HookChannel("tracing:error");
65
184
  }
66
185
  get hasSubscribers() {
67
186
  return this.start.hasSubscribers || this.end.hasSubscribers || this.asyncStart.hasSubscribers || this.asyncEnd.hasSubscribers || this.error.hasSubscribers;
68
187
  }
69
- subscribe(_handlers) {
188
+ subscribe(handlers) {
189
+ for (const eventName of traceEvents) {
190
+ const handler = handlers[eventName];
191
+ if (handler) {
192
+ this[eventName].subscribe(handler);
193
+ }
194
+ }
195
+ }
196
+ unsubscribe(handlers) {
197
+ let done = true;
198
+ for (const eventName of traceEvents) {
199
+ const handler = handlers[eventName];
200
+ if (handler && !this[eventName].unsubscribe(handler)) {
201
+ done = false;
202
+ }
203
+ }
204
+ return done;
205
+ }
206
+ traceSync(fn, message = {}, thisArg, ...args) {
207
+ if (!this.hasSubscribers) {
208
+ return Reflect.apply(fn, thisArg, args);
209
+ }
210
+ const context = message;
211
+ return this.start.runStores(message, () => {
212
+ try {
213
+ const result = Reflect.apply(fn, thisArg, args);
214
+ setContextValue(context, "result", result);
215
+ return result;
216
+ } catch (error) {
217
+ setContextValue(context, "error", error);
218
+ this.error.publish(message);
219
+ throw error;
220
+ } finally {
221
+ this.end.publish(message);
222
+ }
223
+ });
224
+ }
225
+ tracePromise(fn, message = {}, thisArg, ...args) {
226
+ if (!this.hasSubscribers) {
227
+ return Reflect.apply(fn, thisArg, args);
228
+ }
229
+ const context = message;
230
+ return this.start.runStores(message, () => {
231
+ let result;
232
+ try {
233
+ result = Reflect.apply(fn, thisArg, args);
234
+ } catch (error) {
235
+ setContextValue(context, "error", error);
236
+ this.error.publish(message);
237
+ this.end.publish(message);
238
+ throw error;
239
+ }
240
+ this.end.publish(message);
241
+ if (!result || typeof result !== "object" && typeof result !== "function") {
242
+ setContextValue(context, "result", result);
243
+ this.asyncStart.publish(message);
244
+ this.asyncEnd.publish(message);
245
+ return result;
246
+ }
247
+ let terminalPublished = false;
248
+ const finishUnobservedResult = (error) => {
249
+ reportError(error);
250
+ if (!terminalPublished) {
251
+ terminalPublished = true;
252
+ setContextValue(context, "result", result);
253
+ this.asyncStart.publish(message);
254
+ this.asyncEnd.publish(message);
255
+ }
256
+ return result;
257
+ };
258
+ let then;
259
+ try {
260
+ then = result.then;
261
+ } catch (error) {
262
+ return finishUnobservedResult(error);
263
+ }
264
+ if (typeof then !== "function") {
265
+ setContextValue(context, "result", result);
266
+ this.asyncStart.publish(message);
267
+ this.asyncEnd.publish(message);
268
+ return result;
269
+ }
270
+ const resolve = (resolved) => {
271
+ if (!terminalPublished) {
272
+ terminalPublished = true;
273
+ setContextValue(context, "result", resolved);
274
+ this.asyncStart.publish(message);
275
+ this.asyncEnd.publish(message);
276
+ }
277
+ return resolved;
278
+ };
279
+ let rejectionThrown = false;
280
+ let rejectionError;
281
+ const reject2 = (error) => {
282
+ if (!terminalPublished) {
283
+ terminalPublished = true;
284
+ setContextValue(context, "error", error);
285
+ this.error.publish(message);
286
+ this.asyncStart.publish(message);
287
+ this.asyncEnd.publish(message);
288
+ }
289
+ rejectionThrown = true;
290
+ rejectionError = error;
291
+ throw error;
292
+ };
293
+ let isPlainPromise;
294
+ try {
295
+ isPlainPromise = result instanceof Promise && result.constructor === Promise;
296
+ } catch (error) {
297
+ return finishUnobservedResult(error);
298
+ }
299
+ try {
300
+ if (isPlainPromise) {
301
+ return Reflect.apply(then, result, [resolve, reject2]);
302
+ }
303
+ Reflect.apply(then, result, [
304
+ resolve,
305
+ (error) => {
306
+ try {
307
+ reject2(error);
308
+ } catch {
309
+ }
310
+ }
311
+ ]);
312
+ } catch (error) {
313
+ if (rejectionThrown && error === rejectionError) {
314
+ return result;
315
+ }
316
+ return finishUnobservedResult(error);
317
+ }
318
+ return result;
319
+ });
320
+ }
321
+ traceCallback(fn, position = -1, message = {}, thisArg, ...args) {
322
+ if (!this.hasSubscribers) {
323
+ return Reflect.apply(fn, thisArg, args);
324
+ }
325
+ const context = message;
326
+ const callArgs = args.length > 0 ? args : context.arguments ?? args;
327
+ const callback = Array.prototype.at.call(callArgs, position);
328
+ if (typeof callback !== "function") {
329
+ return Reflect.apply(fn, thisArg, args);
330
+ }
331
+ const { asyncStart, asyncEnd, error: errorChannel } = this;
332
+ function wrappedCallback(error, result) {
333
+ if (error) {
334
+ setContextValue(context, "error", error);
335
+ errorChannel.publish(message);
336
+ } else {
337
+ setContextValue(context, "result", result);
338
+ }
339
+ return asyncStart.runStores(message, () => {
340
+ try {
341
+ return Reflect.apply(callback, this, arguments);
342
+ } finally {
343
+ asyncEnd.publish(message);
344
+ }
345
+ });
346
+ }
347
+ Array.prototype.splice.call(callArgs, position, 1, wrappedCallback);
348
+ return this.start.runStores(message, () => {
349
+ try {
350
+ return Reflect.apply(fn, thisArg, args);
351
+ } catch (error) {
352
+ setContextValue(context, "error", error);
353
+ this.error.publish(message);
354
+ throw error;
355
+ } finally {
356
+ this.end.publish(message);
357
+ }
358
+ });
359
+ }
360
+ };
361
+ var inertChannel = Object.freeze({
362
+ name: "braintrust:inert",
363
+ hasSubscribers: false,
364
+ subscribe() {
365
+ },
366
+ unsubscribe() {
367
+ return false;
368
+ },
369
+ bindStore() {
370
+ },
371
+ unbindStore() {
372
+ return false;
373
+ },
374
+ publish() {
375
+ },
376
+ runStores(_message, fn, thisArg, ...args) {
377
+ return Reflect.apply(fn, thisArg, args);
70
378
  }
71
- unsubscribe(_handlers) {
379
+ });
380
+ var inertTracingHook = new TracingHook({
381
+ start: inertChannel,
382
+ end: inertChannel,
383
+ asyncStart: inertChannel,
384
+ asyncEnd: inertChannel,
385
+ error: inertChannel
386
+ });
387
+ function isHookChannel(value) {
388
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
72
389
  return false;
73
390
  }
74
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
75
- traceSync(fn, _message, thisArg, ...args) {
76
- return fn.apply(thisArg, args);
391
+ try {
392
+ const channel2 = value;
393
+ return typeof channel2.hasSubscribers === "boolean" && typeof channel2.subscribe === "function" && typeof channel2.unsubscribe === "function" && typeof channel2.bindStore === "function" && typeof channel2.unbindStore === "function" && typeof channel2.publish === "function" && typeof channel2.runStores === "function";
394
+ } catch {
395
+ return false;
77
396
  }
78
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
79
- tracePromise(fn, _message, thisArg, ...args) {
80
- return fn.apply(thisArg, args);
397
+ }
398
+ function hasTracingHookShape(value) {
399
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
400
+ return false;
81
401
  }
82
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
83
- traceCallback(fn, _position, _message, thisArg, ...args) {
84
- return fn.apply(thisArg, args);
402
+ try {
403
+ const hook = value;
404
+ return typeof hook.hasSubscribers === "boolean" && typeof hook.subscribe === "function" && typeof hook.unsubscribe === "function" && typeof hook.traceSync === "function" && typeof hook.tracePromise === "function" && typeof hook.traceCallback === "function" && isHookChannel(hook.start) && isHookChannel(hook.end) && isHookChannel(hook.asyncStart) && isHookChannel(hook.asyncEnd) && isHookChannel(hook.error);
405
+ } catch {
406
+ return false;
407
+ }
408
+ }
409
+ function isCompatibleTracingHook(value) {
410
+ try {
411
+ return value[hookBrand] === GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION && hasTracingHookShape(value);
412
+ } catch {
413
+ return false;
414
+ }
415
+ }
416
+ function isCompatibleHookRegistry(value) {
417
+ try {
418
+ return value instanceof Map && value[registryBrand] === GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION;
419
+ } catch {
420
+ return false;
421
+ }
422
+ }
423
+ function getHookRegistry() {
424
+ let descriptor;
425
+ try {
426
+ descriptor = Object.getOwnPropertyDescriptor(
427
+ globalThis,
428
+ GLOBAL_INSTRUMENTATION_HOOKS_KEY
429
+ );
430
+ } catch (error) {
431
+ reportError(error);
432
+ return void 0;
433
+ }
434
+ if (descriptor && "value" in descriptor && isCompatibleHookRegistry(descriptor.value) && (descriptor.configurable || descriptor.enumerable === false)) {
435
+ if (descriptor.configurable || descriptor.writable) {
436
+ try {
437
+ Object.defineProperty(globalThis, GLOBAL_INSTRUMENTATION_HOOKS_KEY, {
438
+ configurable: false,
439
+ enumerable: false,
440
+ value: descriptor.value,
441
+ writable: false
442
+ });
443
+ } catch (error) {
444
+ reportError(error);
445
+ return void 0;
446
+ }
447
+ }
448
+ return descriptor.value;
449
+ }
450
+ if (descriptor && !descriptor.configurable) {
451
+ reportError(new Error("Incompatible global instrumentation hook registry"));
452
+ return void 0;
453
+ }
454
+ const registry2 = /* @__PURE__ */ new Map();
455
+ try {
456
+ Object.defineProperty(registry2, registryBrand, {
457
+ configurable: false,
458
+ enumerable: false,
459
+ value: GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION,
460
+ writable: false
461
+ });
462
+ } catch (error) {
463
+ reportError(error);
464
+ return void 0;
465
+ }
466
+ try {
467
+ Object.defineProperty(globalThis, GLOBAL_INSTRUMENTATION_HOOKS_KEY, {
468
+ configurable: false,
469
+ enumerable: false,
470
+ value: registry2,
471
+ writable: false
472
+ });
473
+ return registry2;
474
+ } catch (error) {
475
+ reportError(error);
476
+ return void 0;
477
+ }
478
+ }
479
+ function newGlobalTracingChannel(nameOrChannels) {
480
+ if (typeof nameOrChannels !== "string") {
481
+ return new TracingHook(nameOrChannels);
482
+ }
483
+ const registry2 = getHookRegistry();
484
+ if (!registry2) {
485
+ return inertTracingHook;
486
+ }
487
+ let existing;
488
+ try {
489
+ existing = Map.prototype.get.call(registry2, nameOrChannels);
490
+ } catch (error) {
491
+ reportError(error);
492
+ return inertTracingHook;
493
+ }
494
+ if (isCompatibleTracingHook(existing)) {
495
+ return existing;
496
+ }
497
+ if (existing !== void 0) {
498
+ reportError(
499
+ new Error(`Invalid global instrumentation hook: ${nameOrChannels}`)
500
+ );
501
+ try {
502
+ Map.prototype.delete.call(registry2, nameOrChannels);
503
+ } catch (error) {
504
+ reportError(error);
505
+ return inertTracingHook;
506
+ }
507
+ }
508
+ const hook = new TracingHook(nameOrChannels);
509
+ try {
510
+ Map.prototype.set.call(registry2, nameOrChannels, hook);
511
+ } catch (error) {
512
+ reportError(error);
513
+ return inertTracingHook;
514
+ }
515
+ return hook;
516
+ }
517
+
518
+ // src/isomorph.ts
519
+ var DefaultAsyncLocalStorage = class {
520
+ constructor() {
521
+ }
522
+ enterWith(_) {
523
+ }
524
+ run(_, callback) {
525
+ return callback();
526
+ }
527
+ getStore() {
528
+ return void 0;
85
529
  }
86
530
  };
87
531
  var iso = {
@@ -94,7 +538,7 @@ var iso = {
94
538
  getCallerLocation: () => void 0,
95
539
  newAsyncLocalStorage: () => new DefaultAsyncLocalStorage(),
96
540
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
97
- newTracingChannel: (nameOrChannels) => new DefaultTracingChannel(nameOrChannels),
541
+ newTracingChannel: (nameOrChannels) => newGlobalTracingChannel(nameOrChannels),
98
542
  processOn: (_0, _1) => {
99
543
  },
100
544
  basename: (filepath) => filepath.split(/[\\/]/).pop() || filepath,
@@ -214,6 +658,9 @@ var debugLogger = {
214
658
  return createDebugLogger(state);
215
659
  }
216
660
  };
661
+ setGlobalHookErrorReporter((error) => {
662
+ debugLogger.error("Global instrumentation hook error:", error);
663
+ });
217
664
 
218
665
  // src/queue.ts
219
666
  var DEFAULT_QUEUE_SIZE = 15e3;
@@ -1998,7 +2445,8 @@ var ApiKey = z6.object({
1998
2445
  user_email: z6.union([z6.string(), z6.null()]).optional(),
1999
2446
  user_given_name: z6.union([z6.string(), z6.null()]).optional(),
2000
2447
  user_family_name: z6.union([z6.string(), z6.null()]).optional(),
2001
- org_id: z6.union([z6.string(), z6.null()]).optional()
2448
+ org_id: z6.union([z6.string(), z6.null()]).optional(),
2449
+ expires_at: z6.union([z6.string(), z6.null()]).optional()
2002
2450
  });
2003
2451
  var TriggeredFunctionState = z6.object({
2004
2452
  triggered_xact_id: z6.string(),
@@ -2118,6 +2566,7 @@ var TopicMapData = z6.object({
2118
2566
  topic_names: z6.record(z6.string()).optional(),
2119
2567
  generation_settings: TopicMapGenerationSettings.optional(),
2120
2568
  disable_reconciliation: z6.boolean().optional(),
2569
+ reconcile_mode: z6.enum(["evolve", "names_only"]).optional(),
2121
2570
  distance_threshold: z6.number().optional(),
2122
2571
  btql_filter: z6.string().optional(),
2123
2572
  automation_btql_filter: z6.string().optional()
@@ -2698,7 +3147,12 @@ var ModelParams = z6.union([
2698
3147
  }).partial().passthrough()
2699
3148
  ]);
2700
3149
  var PromptOptionsNullish = z6.union([
2701
- z6.object({ model: z6.string(), params: ModelParams, position: z6.string() }).partial(),
3150
+ z6.object({
3151
+ model: z6.string(),
3152
+ params: ModelParams,
3153
+ position: z6.string(),
3154
+ endpoint_name: z6.union([z6.string(), z6.null()])
3155
+ }).partial(),
2702
3156
  z6.null()
2703
3157
  ]);
2704
3158
  var PromptParserNullish = z6.union([
@@ -2712,11 +3166,25 @@ var PromptParserNullish = z6.union([
2712
3166
  }),
2713
3167
  z6.null()
2714
3168
  ]);
3169
+ var PreprocessorSavedFunctionId = z6.union([
3170
+ z6.object({
3171
+ type: z6.literal("function"),
3172
+ id: z6.string(),
3173
+ version: z6.string().optional()
3174
+ }),
3175
+ z6.object({
3176
+ type: z6.literal("global"),
3177
+ name: z6.string(),
3178
+ function_type: z6.literal("preprocessor").optional().default("preprocessor")
3179
+ }),
3180
+ z6.null()
3181
+ ]);
2715
3182
  var PromptDataNullish = z6.union([
2716
3183
  z6.object({
2717
3184
  prompt: PromptBlockDataNullish,
2718
3185
  options: PromptOptionsNullish,
2719
3186
  parser: PromptParserNullish,
3187
+ preprocessor: PreprocessorSavedFunctionId,
2720
3188
  tool_functions: z6.union([z6.array(SavedFunctionId), z6.null()]),
2721
3189
  template_format: z6.union([
2722
3190
  z6.enum(["mustache", "nunjucks", "none"]),
@@ -2918,6 +3386,7 @@ var PromptData = z6.object({
2918
3386
  prompt: PromptBlockDataNullish,
2919
3387
  options: PromptOptionsNullish,
2920
3388
  parser: PromptParserNullish,
3389
+ preprocessor: PreprocessorSavedFunctionId,
2921
3390
  tool_functions: z6.union([z6.array(SavedFunctionId), z6.null()]),
2922
3391
  template_format: z6.union([
2923
3392
  z6.enum(["mustache", "nunjucks", "none"]),
@@ -3080,7 +3549,8 @@ var InvokeFunction = FunctionId.and(
3080
3549
  mode: StreamingMode,
3081
3550
  strict: z6.union([z6.boolean(), z6.null()]),
3082
3551
  mcp_auth: z6.record(z6.object({ oauth_token: z6.string() }).partial()),
3083
- overrides: z6.union([z6.object({}).partial().passthrough(), z6.null()])
3552
+ overrides: z6.union([z6.object({}).partial().passthrough(), z6.null()]),
3553
+ endpoint_name: z6.union([z6.string(), z6.null()])
3084
3554
  }).partial()
3085
3555
  );
3086
3556
  var MCPServer = z6.object({
@@ -3144,6 +3614,24 @@ var Organization = z6.object({
3144
3614
  created: z6.union([z6.string(), z6.null()]).optional(),
3145
3615
  image_rendering_mode: ImageRenderingMode.optional()
3146
3616
  });
3617
+ var RetentionObjectType = z6.enum([
3618
+ "project_logs",
3619
+ "experiment",
3620
+ "dataset"
3621
+ ]);
3622
+ var OrgAutomation = z6.object({
3623
+ id: z6.string().uuid(),
3624
+ org_id: z6.string().uuid(),
3625
+ user_id: z6.union([z6.string(), z6.null()]).optional(),
3626
+ created: z6.union([z6.string(), z6.null()]).optional(),
3627
+ name: z6.string(),
3628
+ description: z6.union([z6.string(), z6.null()]).optional(),
3629
+ config: z6.object({
3630
+ event_type: z6.literal("retention"),
3631
+ object_type: RetentionObjectType,
3632
+ retention_days: z6.number().int().gte(0)
3633
+ })
3634
+ });
3147
3635
  var ProjectSettings = z6.union([
3148
3636
  z6.object({
3149
3637
  comparison_key: z6.union([z6.string(), z6.null()]),
@@ -3170,6 +3658,7 @@ var ProjectSettings = z6.union([
3170
3658
  z6.null()
3171
3659
  ]),
3172
3660
  disable_realtime_queries: z6.union([z6.boolean(), z6.null()]),
3661
+ monitor_charts_use_metrics_start: z6.union([z6.boolean(), z6.null()]),
3173
3662
  default_preprocessor: NullableSavedFunctionId
3174
3663
  }).partial(),
3175
3664
  z6.null()
@@ -3184,11 +3673,6 @@ var Project = z6.object({
3184
3673
  user_id: z6.union([z6.string(), z6.null()]).optional(),
3185
3674
  settings: ProjectSettings.optional()
3186
3675
  });
3187
- var RetentionObjectType = z6.enum([
3188
- "project_logs",
3189
- "experiment",
3190
- "dataset"
3191
- ]);
3192
3676
  var TopicAutomationFacetModel = z6.union([
3193
3677
  z6.enum(["brain-facet-latest", "brain-facet-1", "brain-facet-2"]),
3194
3678
  z6.null()
@@ -3299,7 +3783,7 @@ var ProjectAutomation = z6.object({
3299
3783
  z6.object({
3300
3784
  event_type: z6.literal("retention"),
3301
3785
  object_type: RetentionObjectType,
3302
- retention_days: z6.number().gte(0)
3786
+ retention_days: z6.number().int().gte(0)
3303
3787
  }),
3304
3788
  z6.object({
3305
3789
  event_type: z6.literal("environment_update"),
@@ -3471,7 +3955,12 @@ var Prompt = z6.object({
3471
3955
  metadata: z6.union([z6.object({}).partial().passthrough(), z6.null()]).optional(),
3472
3956
  function_type: FunctionTypeEnumNullish.optional()
3473
3957
  });
3474
- var PromptOptions = z6.object({ model: z6.string(), params: ModelParams, position: z6.string() }).partial();
3958
+ var PromptOptions = z6.object({
3959
+ model: z6.string(),
3960
+ params: ModelParams,
3961
+ position: z6.string(),
3962
+ endpoint_name: z6.union([z6.string(), z6.null()])
3963
+ }).partial();
3475
3964
  var PromptSessionEvent = z6.object({
3476
3965
  id: z6.string(),
3477
3966
  _xact_id: z6.string(),
@@ -3554,7 +4043,8 @@ var RunEval = z6.object({
3554
4043
  stop_token: z6.union([z6.string(), z6.null()]).optional(),
3555
4044
  extra_messages: z6.string().optional(),
3556
4045
  tags: z6.array(z6.string()).optional(),
3557
- mcp_auth: z6.record(z6.object({ oauth_token: z6.string() }).partial()).optional()
4046
+ mcp_auth: z6.record(z6.object({ oauth_token: z6.string() }).partial()).optional(),
4047
+ endpoint_name: z6.union([z6.string(), z6.null()]).optional()
3558
4048
  });
3559
4049
  var ServiceToken = z6.object({
3560
4050
  id: z6.string().uuid(),
@@ -3564,7 +4054,8 @@ var ServiceToken = z6.object({
3564
4054
  service_account_id: z6.union([z6.string(), z6.null()]).optional(),
3565
4055
  service_account_email: z6.union([z6.string(), z6.null()]).optional(),
3566
4056
  service_account_name: z6.union([z6.string(), z6.null()]).optional(),
3567
- org_id: z6.union([z6.string(), z6.null()]).optional()
4057
+ org_id: z6.union([z6.string(), z6.null()]).optional(),
4058
+ expires_at: z6.union([z6.string(), z6.null()]).optional()
3568
4059
  });
3569
4060
  var SpanIFrame = z6.object({
3570
4061
  id: z6.string().uuid(),
@@ -3686,6 +4177,13 @@ var ViewOptions = z6.union([
3686
4177
  }),
3687
4178
  z6.null()
3688
4179
  ]),
4180
+ pointSizeMetric: z6.union([
4181
+ z6.object({
4182
+ type: z6.enum(["none", "score", "metric", "metadata"]),
4183
+ value: z6.string()
4184
+ }),
4185
+ z6.null()
4186
+ ]),
3689
4187
  xAxisAggregation: z6.union([z6.string(), z6.null()]),
3690
4188
  chartAnnotations: z6.union([
3691
4189
  z6.array(z6.object({ id: z6.string(), text: z6.string() })),
@@ -4829,6 +5327,8 @@ var INSTRUMENTATION_NAMES = {
4829
5327
  BEDROCK_RUNTIME: "bedrock-runtime",
4830
5328
  BRAINTRUST_JS_LOGGER: "braintrust-js-logger",
4831
5329
  CLAUDE_AGENT_SDK: "claude-agent-sdk",
5330
+ CLOUDFLARE_AI_CHAT: "cloudflare-ai-chat",
5331
+ CLOUDFLARE_AGENTS: "cloudflare-agents",
4832
5332
  COHERE: "cohere",
4833
5333
  CURSOR_SDK: "cursor-sdk",
4834
5334
  EVE: "eve",
@@ -4854,7 +5354,7 @@ var INSTRUMENTATION_NAMES = {
4854
5354
  var INTERNAL_SPAN_INSTRUMENTATION_NAME = /* @__PURE__ */ Symbol.for(
4855
5355
  "braintrust.spanInstrumentationName"
4856
5356
  );
4857
- var SDK_VERSION = true ? "3.25.0" : "0.0.0";
5357
+ var SDK_VERSION = true ? "3.26.0" : "0.0.0";
4858
5358
  function withSpanInstrumentationName(args, instrumentationName) {
4859
5359
  return {
4860
5360
  ...args,
@@ -5049,12 +5549,13 @@ function applyMaskingToField(maskingFunction, data, fieldName) {
5049
5549
  var INITIAL_SPAN_WRITE_AS_MERGE = /* @__PURE__ */ Symbol(
5050
5550
  "braintrust.initial-span-write-as-merge"
5051
5551
  );
5552
+ var INTERNAL_SPAN_CONTEXT = /* @__PURE__ */ Symbol("braintrust.internal-span-context");
5052
5553
  var BRAINTRUST_CURRENT_SPAN_STORE = /* @__PURE__ */ Symbol.for(
5053
5554
  "braintrust.currentSpanStore"
5054
5555
  );
5055
5556
  var ContextManager = class {
5056
5557
  /**
5057
- * Returns the value to store in the ALS bound to a TracingChannel's start event.
5558
+ * Returns the value to store in the ALS bound to a global hook's start event.
5058
5559
  * In default mode this is the Span itself; in OTEL mode it is the OTEL Context
5059
5560
  * containing the span so that OTEL's own ALS stores a proper Context object.
5060
5561
  */
@@ -8787,6 +9288,12 @@ function _internalStartSpanWithInitialMerge(args) {
8787
9288
  [INITIAL_SPAN_WRITE_AS_MERGE]: true
8788
9289
  }).span;
8789
9290
  }
9291
+ function _internalStartSpanWithContext(args, context) {
9292
+ return startSpanAndIsLogger({
9293
+ ...args,
9294
+ [INTERNAL_SPAN_CONTEXT]: context
9295
+ }).span;
9296
+ }
8790
9297
  async function flush(options) {
8791
9298
  const state = options?.state ?? _globalState;
8792
9299
  return await state.bgLogger().flush();
@@ -9688,7 +10195,7 @@ var SpanImpl = class _SpanImpl {
9688
10195
  start: args.startTime ?? getCurrentUnixTimestamp()
9689
10196
  },
9690
10197
  context: mergeSpanOriginContext(
9691
- { ...callerLocation },
10198
+ { ...callerLocation, ...args[INTERNAL_SPAN_CONTEXT] },
9692
10199
  instrumentationName,
9693
10200
  this._state.spanOriginEnvironment
9694
10201
  ),
@@ -10996,95 +11503,6 @@ function resolveRuntimeAsyncLocalStorage() {
10996
11503
  }
10997
11504
  }
10998
11505
 
10999
- // src/workerd/config.ts
11000
- import { tracingChannel } from "dc-browser";
11001
-
11002
- // src/auto-instrumentations/patch-tracing-channel.ts
11003
- function patchTracingChannel(tracingChannelFn) {
11004
- const dummyChannel = tracingChannelFn("__braintrust_probe__");
11005
- const TracingChannel = dummyChannel?.constructor;
11006
- if (!TracingChannel?.prototype) {
11007
- return;
11008
- }
11009
- if (!Object.getOwnPropertyDescriptor(TracingChannel.prototype, "hasSubscribers")) {
11010
- Object.defineProperty(TracingChannel.prototype, "hasSubscribers", {
11011
- configurable: true,
11012
- enumerable: false,
11013
- get() {
11014
- return Boolean(
11015
- this.start?.hasSubscribers || this.end?.hasSubscribers || this.asyncStart?.hasSubscribers || this.asyncEnd?.hasSubscribers || this.error?.hasSubscribers
11016
- );
11017
- }
11018
- });
11019
- }
11020
- if (TracingChannel.prototype.tracePromise) {
11021
- TracingChannel.prototype.tracePromise = function(fn, context = {}, thisArg, ...args) {
11022
- const start = this.start;
11023
- const end = this.end;
11024
- const asyncStart = this.asyncStart;
11025
- const asyncEnd = this.asyncEnd;
11026
- const error = this.error;
11027
- function publishRejected(err) {
11028
- context.error = err;
11029
- error?.publish(context);
11030
- asyncStart?.publish(context);
11031
- asyncEnd?.publish(context);
11032
- }
11033
- function publishResolved(result) {
11034
- context.result = result;
11035
- asyncStart?.publish(context);
11036
- asyncEnd?.publish(context);
11037
- }
11038
- return start.runStores(context, () => {
11039
- try {
11040
- const result = Reflect.apply(fn, thisArg, args);
11041
- end?.publish(context);
11042
- if (result && (typeof result === "object" || typeof result === "function") && typeof result.then === "function") {
11043
- if (result.constructor === Promise) {
11044
- return result.then(
11045
- (res) => {
11046
- publishResolved(res);
11047
- return res;
11048
- },
11049
- (err) => {
11050
- publishRejected(err);
11051
- return Promise.reject(err);
11052
- }
11053
- );
11054
- }
11055
- void result.then(
11056
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
11057
- (resolved) => {
11058
- try {
11059
- publishResolved(resolved);
11060
- } catch {
11061
- }
11062
- },
11063
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
11064
- (err) => {
11065
- try {
11066
- publishRejected(err);
11067
- } catch {
11068
- }
11069
- }
11070
- );
11071
- return result;
11072
- }
11073
- context.result = result;
11074
- asyncStart?.publish(context);
11075
- asyncEnd?.publish(context);
11076
- return result;
11077
- } catch (err) {
11078
- context.error = err;
11079
- error?.publish(context);
11080
- end?.publish(context);
11081
- throw err;
11082
- }
11083
- });
11084
- };
11085
- }
11086
- }
11087
-
11088
11506
  // src/instrumentation/core/stream-patcher.ts
11089
11507
  function isAsyncIterable(value) {
11090
11508
  return value !== null && typeof value === "object" && Symbol.asyncIterator in value && typeof value[Symbol.asyncIterator] === "function";
@@ -11751,8 +12169,8 @@ function runWithAutoInstrumentationSuppressed(callback) {
11751
12169
  callback
11752
12170
  );
11753
12171
  }
11754
- function bindAutoInstrumentationSuppressionToStart(tracingChannel2) {
11755
- const startChannel = tracingChannel2.start;
12172
+ function bindAutoInstrumentationSuppressionToStart(tracingChannel) {
12173
+ const startChannel = tracingChannel.start;
11756
12174
  if (!startChannel) {
11757
12175
  return void 0;
11758
12176
  }
@@ -11863,9 +12281,9 @@ function ensureSpanStateForEvent(states, config, event, channelName, instrumenta
11863
12281
  states.set(key, created);
11864
12282
  return created;
11865
12283
  }
11866
- function bindCurrentSpanStoreToStart(tracingChannel2, states, config, channelName, instrumentationName) {
12284
+ function bindCurrentSpanStoreToStart(tracingChannel, states, config, channelName, instrumentationName) {
11867
12285
  const state = _internalGetGlobalState();
11868
- const startChannel = tracingChannel2.start;
12286
+ const startChannel = tracingChannel.start;
11869
12287
  const contextManager = state?.contextManager;
11870
12288
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
11871
12289
  if (!currentSpanStore || !startChannel) {
@@ -11948,11 +12366,11 @@ function runStreamingErrorHook(args) {
11948
12366
  }
11949
12367
  }
11950
12368
  function traceAsyncChannel(channel2, config) {
11951
- const tracingChannel2 = channel2.tracingChannel();
12369
+ const tracingChannel = channel2.tracingChannel();
11952
12370
  const states = /* @__PURE__ */ new WeakMap();
11953
12371
  const channelName = channel2.channelName;
11954
12372
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart(
11955
- tracingChannel2,
12373
+ tracingChannel,
11956
12374
  states,
11957
12375
  config,
11958
12376
  channelName,
@@ -12008,18 +12426,18 @@ function traceAsyncChannel(channel2, config) {
12008
12426
  logErrorAndEnd(states, event, channelName);
12009
12427
  }
12010
12428
  };
12011
- tracingChannel2.subscribe(handlers);
12429
+ tracingChannel.subscribe(handlers);
12012
12430
  return () => {
12013
12431
  unbindCurrentSpanStore?.();
12014
- tracingChannel2.unsubscribe(handlers);
12432
+ tracingChannel.unsubscribe(handlers);
12015
12433
  };
12016
12434
  }
12017
12435
  function traceStreamingChannel(channel2, config) {
12018
- const tracingChannel2 = channel2.tracingChannel();
12436
+ const tracingChannel = channel2.tracingChannel();
12019
12437
  const states = /* @__PURE__ */ new WeakMap();
12020
12438
  const channelName = channel2.channelName;
12021
12439
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart(
12022
- tracingChannel2,
12440
+ tracingChannel,
12023
12441
  states,
12024
12442
  config,
12025
12443
  channelName,
@@ -12230,18 +12648,18 @@ function traceStreamingChannel(channel2, config) {
12230
12648
  }
12231
12649
  }
12232
12650
  };
12233
- tracingChannel2.subscribe(handlers);
12651
+ tracingChannel.subscribe(handlers);
12234
12652
  return () => {
12235
12653
  unbindCurrentSpanStore?.();
12236
- tracingChannel2.unsubscribe(handlers);
12654
+ tracingChannel.unsubscribe(handlers);
12237
12655
  };
12238
12656
  }
12239
12657
  function traceSyncStreamChannel(channel2, config) {
12240
- const tracingChannel2 = channel2.tracingChannel();
12658
+ const tracingChannel = channel2.tracingChannel();
12241
12659
  const states = /* @__PURE__ */ new WeakMap();
12242
12660
  const channelName = channel2.channelName;
12243
12661
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart(
12244
- tracingChannel2,
12662
+ tracingChannel,
12245
12663
  states,
12246
12664
  config,
12247
12665
  channelName,
@@ -12354,10 +12772,10 @@ function traceSyncStreamChannel(channel2, config) {
12354
12772
  logErrorAndEnd(states, event, channelName);
12355
12773
  }
12356
12774
  };
12357
- tracingChannel2.subscribe(handlers);
12775
+ tracingChannel.subscribe(handlers);
12358
12776
  return () => {
12359
12777
  unbindCurrentSpanStore?.();
12360
- tracingChannel2.unsubscribe(handlers);
12778
+ tracingChannel.unsubscribe(handlers);
12361
12779
  };
12362
12780
  }
12363
12781
  function unsubscribeAll(unsubscribers) {
@@ -12537,7 +12955,7 @@ function defineChannels(pkg, channels, options) {
12537
12955
  const fullChannelName = `orchestrion:${pkg}:${spec.channelName}`;
12538
12956
  if (spec.kind === "async") {
12539
12957
  const asyncSpec = spec;
12540
- const tracingChannel3 = () => isomorph_default.newTracingChannel(
12958
+ const tracingChannel2 = () => isomorph_default.newTracingChannel(
12541
12959
  fullChannelName
12542
12960
  );
12543
12961
  return [
@@ -12545,8 +12963,8 @@ function defineChannels(pkg, channels, options) {
12545
12963
  {
12546
12964
  ...asyncSpec,
12547
12965
  instrumentationName,
12548
- tracingChannel: tracingChannel3,
12549
- tracePromise: (fn, context) => tracingChannel3().tracePromise(
12966
+ tracingChannel: tracingChannel2,
12967
+ tracePromise: (fn, context) => tracingChannel2().tracePromise(
12550
12968
  fn,
12551
12969
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
12552
12970
  context
@@ -12555,7 +12973,7 @@ function defineChannels(pkg, channels, options) {
12555
12973
  ];
12556
12974
  }
12557
12975
  const syncSpec = spec;
12558
- const tracingChannel2 = () => isomorph_default.newTracingChannel(
12976
+ const tracingChannel = () => isomorph_default.newTracingChannel(
12559
12977
  fullChannelName
12560
12978
  );
12561
12979
  return [
@@ -12563,8 +12981,8 @@ function defineChannels(pkg, channels, options) {
12563
12981
  {
12564
12982
  ...syncSpec,
12565
12983
  instrumentationName,
12566
- tracingChannel: tracingChannel2,
12567
- traceSync: (fn, context) => tracingChannel2().traceSync(
12984
+ tracingChannel,
12985
+ traceSync: (fn, context) => tracingChannel().traceSync(
12568
12986
  fn,
12569
12987
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
12570
12988
  context
@@ -13896,7 +14314,7 @@ var AnthropicPlugin = class extends BasePlugin {
13896
14314
  );
13897
14315
  }
13898
14316
  subscribeToAnthropicToolRunner() {
13899
- const tracingChannel2 = anthropicChannels.betaMessagesToolRunner.tracingChannel();
14317
+ const tracingChannel = anthropicChannels.betaMessagesToolRunner.tracingChannel();
13900
14318
  const states = /* @__PURE__ */ new WeakMap();
13901
14319
  const handlers = {
13902
14320
  start: (event) => {
@@ -13953,9 +14371,9 @@ var AnthropicPlugin = class extends BasePlugin {
13953
14371
  states.delete(event);
13954
14372
  }
13955
14373
  };
13956
- tracingChannel2.subscribe(handlers);
14374
+ tracingChannel.subscribe(handlers);
13957
14375
  this.unsubscribers.push(() => {
13958
- tracingChannel2.unsubscribe(handlers);
14376
+ tracingChannel.unsubscribe(handlers);
13959
14377
  });
13960
14378
  }
13961
14379
  };
@@ -14867,8 +15285,8 @@ function registerHarnessSessionParent(session, parent) {
14867
15285
  function currentHarnessTurnParent() {
14868
15286
  return harnessTurnParentStore?.getStore() ?? wrapperTurnParents.get(currentSpan());
14869
15287
  }
14870
- function bindHarnessTurnParentToStart(tracingChannel2, parentFromEvent) {
14871
- const startChannel = tracingChannel2.start;
15288
+ function bindHarnessTurnParentToStart(tracingChannel, parentFromEvent) {
15289
+ const startChannel = tracingChannel.start;
14872
15290
  if (!startChannel) {
14873
15291
  return () => {
14874
15292
  };
@@ -20334,7 +20752,7 @@ var CursorSDKPlugin = class extends BasePlugin {
20334
20752
  this.subscribeToAgentFactory(cursorSDKChannels.resume);
20335
20753
  }
20336
20754
  subscribeToAgentFactory(channel2) {
20337
- const tracingChannel2 = channel2.tracingChannel();
20755
+ const tracingChannel = channel2.tracingChannel();
20338
20756
  const handlers = {
20339
20757
  asyncEnd: (event) => {
20340
20758
  patchCursorAgentInPlace(event.result);
@@ -20342,9 +20760,9 @@ var CursorSDKPlugin = class extends BasePlugin {
20342
20760
  error: () => {
20343
20761
  }
20344
20762
  };
20345
- tracingChannel2.subscribe(handlers);
20763
+ tracingChannel.subscribe(handlers);
20346
20764
  this.unsubscribers.push(() => {
20347
- tracingChannel2.unsubscribe(handlers);
20765
+ tracingChannel.unsubscribe(handlers);
20348
20766
  });
20349
20767
  }
20350
20768
  subscribeToPrompt() {
@@ -21700,10 +22118,10 @@ var GoogleGenAIPlugin = class extends BasePlugin {
21700
22118
  this.subscribeToInteractionsCreateChannel();
21701
22119
  }
21702
22120
  subscribeToGenerateContentChannel() {
21703
- const tracingChannel2 = googleGenAIChannels.generateContent.tracingChannel();
22121
+ const tracingChannel = googleGenAIChannels.generateContent.tracingChannel();
21704
22122
  const states = /* @__PURE__ */ new WeakMap();
21705
22123
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart2(
21706
- tracingChannel2,
22124
+ tracingChannel,
21707
22125
  states,
21708
22126
  (event) => {
21709
22127
  const params = event.arguments[0];
@@ -21777,14 +22195,14 @@ var GoogleGenAIPlugin = class extends BasePlugin {
21777
22195
  logErrorAndEndSpan(states, event);
21778
22196
  }
21779
22197
  };
21780
- tracingChannel2.subscribe(handlers);
22198
+ tracingChannel.subscribe(handlers);
21781
22199
  this.unsubscribers.push(() => {
21782
22200
  unbindCurrentSpanStore?.();
21783
- tracingChannel2.unsubscribe(handlers);
22201
+ tracingChannel.unsubscribe(handlers);
21784
22202
  });
21785
22203
  }
21786
22204
  subscribeToGenerateContentStreamChannel() {
21787
- const tracingChannel2 = googleGenAIChannels.generateContentStream.tracingChannel();
22205
+ const tracingChannel = googleGenAIChannels.generateContentStream.tracingChannel();
21788
22206
  const handlers = {
21789
22207
  start: (event) => {
21790
22208
  const streamEvent = event;
@@ -21805,16 +22223,16 @@ var GoogleGenAIPlugin = class extends BasePlugin {
21805
22223
  error: () => {
21806
22224
  }
21807
22225
  };
21808
- tracingChannel2.subscribe(handlers);
22226
+ tracingChannel.subscribe(handlers);
21809
22227
  this.unsubscribers.push(() => {
21810
- tracingChannel2.unsubscribe(handlers);
22228
+ tracingChannel.unsubscribe(handlers);
21811
22229
  });
21812
22230
  }
21813
22231
  subscribeToEmbedContentChannel() {
21814
- const tracingChannel2 = googleGenAIChannels.embedContent.tracingChannel();
22232
+ const tracingChannel = googleGenAIChannels.embedContent.tracingChannel();
21815
22233
  const states = /* @__PURE__ */ new WeakMap();
21816
22234
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart2(
21817
- tracingChannel2,
22235
+ tracingChannel,
21818
22236
  states,
21819
22237
  (event) => {
21820
22238
  const params = event.arguments[0];
@@ -21884,10 +22302,10 @@ var GoogleGenAIPlugin = class extends BasePlugin {
21884
22302
  logErrorAndEndSpan(states, event);
21885
22303
  }
21886
22304
  };
21887
- tracingChannel2.subscribe(handlers);
22305
+ tracingChannel.subscribe(handlers);
21888
22306
  this.unsubscribers.push(() => {
21889
22307
  unbindCurrentSpanStore?.();
21890
- tracingChannel2.unsubscribe(handlers);
22308
+ tracingChannel.unsubscribe(handlers);
21891
22309
  });
21892
22310
  }
21893
22311
  subscribeToInteractionsCreateChannel() {
@@ -21923,10 +22341,10 @@ function ensureSpanState(states, event, create) {
21923
22341
  states.set(event, created);
21924
22342
  return created;
21925
22343
  }
21926
- function bindCurrentSpanStoreToStart2(tracingChannel2, states, create) {
22344
+ function bindCurrentSpanStoreToStart2(tracingChannel, states, create) {
21927
22345
  const state = _internalGetGlobalState();
21928
22346
  const contextManager = state?.contextManager;
21929
- const startChannel = tracingChannel2.start;
22347
+ const startChannel = tracingChannel.start;
21930
22348
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
21931
22349
  if (!startChannel?.bindStore || !currentSpanStore) {
21932
22350
  return void 0;
@@ -22429,11 +22847,11 @@ function summarizeEmbedContentOutput(response) {
22429
22847
  };
22430
22848
  }
22431
22849
  function populateUsageMetrics(metrics, usage) {
22432
- if (usage.promptTokenCount !== void 0) {
22433
- metrics.prompt_tokens = usage.promptTokenCount;
22850
+ if (usage.promptTokenCount !== void 0 || usage.toolUsePromptTokenCount !== void 0) {
22851
+ metrics.prompt_tokens = (usage.promptTokenCount ?? 0) + (usage.toolUsePromptTokenCount ?? 0);
22434
22852
  }
22435
- if (usage.candidatesTokenCount !== void 0) {
22436
- metrics.completion_tokens = usage.candidatesTokenCount;
22853
+ if (usage.candidatesTokenCount !== void 0 || usage.thoughtsTokenCount !== void 0) {
22854
+ metrics.completion_tokens = (usage.candidatesTokenCount ?? 0) + (usage.thoughtsTokenCount ?? 0);
22437
22855
  }
22438
22856
  if (usage.totalTokenCount !== void 0) {
22439
22857
  metrics.tokens = usage.totalTokenCount;
@@ -22444,13 +22862,26 @@ function populateUsageMetrics(metrics, usage) {
22444
22862
  if (usage.thoughtsTokenCount !== void 0) {
22445
22863
  metrics.completion_reasoning_tokens = usage.thoughtsTokenCount;
22446
22864
  }
22865
+ for (const detail of usage.promptTokensDetails ?? []) {
22866
+ if (detail.modality === "AUDIO" && detail.tokenCount !== void 0) {
22867
+ metrics.prompt_audio_tokens = (metrics.prompt_audio_tokens ?? 0) + detail.tokenCount;
22868
+ }
22869
+ }
22870
+ for (const detail of usage.candidatesTokensDetails ?? []) {
22871
+ if (detail.modality === "AUDIO" && detail.tokenCount !== void 0) {
22872
+ metrics.completion_audio_tokens = (metrics.completion_audio_tokens ?? 0) + detail.tokenCount;
22873
+ }
22874
+ if (detail.modality === "IMAGE" && detail.tokenCount !== void 0) {
22875
+ metrics.completion_image_tokens = (metrics.completion_image_tokens ?? 0) + detail.tokenCount;
22876
+ }
22877
+ }
22447
22878
  }
22448
22879
  function populateInteractionUsageMetrics(metrics, usage) {
22449
22880
  if (typeof usage.total_input_tokens === "number") {
22450
22881
  metrics.prompt_tokens = usage.total_input_tokens;
22451
22882
  }
22452
22883
  if (typeof usage.total_output_tokens === "number") {
22453
- metrics.completion_tokens = usage.total_output_tokens;
22884
+ metrics.completion_tokens = usage.total_output_tokens + (typeof usage.total_thought_tokens === "number" ? usage.total_thought_tokens : 0);
22454
22885
  }
22455
22886
  if (typeof usage.total_tokens === "number") {
22456
22887
  metrics.tokens = usage.total_tokens;
@@ -22461,6 +22892,24 @@ function populateInteractionUsageMetrics(metrics, usage) {
22461
22892
  if (typeof usage.total_thought_tokens === "number") {
22462
22893
  metrics.completion_reasoning_tokens = usage.total_thought_tokens;
22463
22894
  }
22895
+ for (const detail of Array.isArray(usage.input_tokens_by_modality) ? usage.input_tokens_by_modality : []) {
22896
+ if (typeof detail?.modality === "string" && detail.modality.toLowerCase() === "audio" && typeof detail.tokens === "number") {
22897
+ metrics.prompt_audio_tokens = (metrics.prompt_audio_tokens ?? 0) + detail.tokens;
22898
+ }
22899
+ }
22900
+ for (const detail of Array.isArray(usage.output_tokens_by_modality) ? usage.output_tokens_by_modality : []) {
22901
+ if (typeof detail?.modality !== "string" || typeof detail.tokens !== "number") {
22902
+ continue;
22903
+ }
22904
+ switch (detail.modality.toLowerCase()) {
22905
+ case "audio":
22906
+ metrics.completion_audio_tokens = (metrics.completion_audio_tokens ?? 0) + detail.tokens;
22907
+ break;
22908
+ case "image":
22909
+ metrics.completion_image_tokens = (metrics.completion_image_tokens ?? 0) + detail.tokens;
22910
+ break;
22911
+ }
22912
+ }
22464
22913
  }
22465
22914
  function aggregateGenerateContentChunks(chunks, startTime, firstTokenTime) {
22466
22915
  const end = getCurrentUnixTimestamp();
@@ -23199,6 +23648,299 @@ function extractTextGenerationStreamMetadata(chunks) {
23199
23648
  return void 0;
23200
23649
  }
23201
23650
 
23651
+ // src/instrumentation/plugins/huggingface-transformers-channels.ts
23652
+ var SUPPORTED_TASKS = /* @__PURE__ */ new Set([
23653
+ "text-generation",
23654
+ "text2text-generation",
23655
+ "summarization",
23656
+ "feature-extraction",
23657
+ "question-answering"
23658
+ ]);
23659
+ var pipelineInfo = /* @__PURE__ */ new WeakMap();
23660
+ function isSupportedHuggingFaceTransformersTask(task) {
23661
+ return typeof task === "string" && SUPPORTED_TASKS.has(task);
23662
+ }
23663
+ function registerHuggingFaceTransformersPipeline(pipeline, task, model) {
23664
+ if (typeof task !== "string") {
23665
+ return;
23666
+ }
23667
+ const info = { task };
23668
+ if (typeof model === "string") {
23669
+ info.model = model;
23670
+ }
23671
+ pipelineInfo.set(pipeline, info);
23672
+ }
23673
+ function getHuggingFaceTransformersPipelineInfo(pipeline) {
23674
+ return pipeline ? pipelineInfo.get(pipeline) : void 0;
23675
+ }
23676
+ var huggingFaceTransformersChannels = defineChannels(
23677
+ "@huggingface/transformers",
23678
+ {
23679
+ pipeline: channel({
23680
+ channelName: "pipeline",
23681
+ kind: "async"
23682
+ }),
23683
+ pipelineCall: channel({
23684
+ channelName: "pipeline.call",
23685
+ kind: "async"
23686
+ })
23687
+ },
23688
+ { instrumentationName: INSTRUMENTATION_NAMES.HUGGINGFACE }
23689
+ );
23690
+
23691
+ // src/instrumentation/plugins/huggingface-transformers-plugin.ts
23692
+ var REQUEST_METADATA_KEYS = [
23693
+ "temperature",
23694
+ "top_p",
23695
+ "max_tokens",
23696
+ "stop"
23697
+ ];
23698
+ var HuggingFaceTransformersPlugin = class extends BasePlugin {
23699
+ onEnable() {
23700
+ this.subscribeToPipelineFactory();
23701
+ this.unsubscribers.push(
23702
+ traceAsyncChannel(huggingFaceTransformersChannels.pipelineCall, {
23703
+ name: (_args, event) => {
23704
+ const task = getTask(event);
23705
+ const operation = task?.replaceAll("-", "_") ?? "unknown";
23706
+ return `huggingface.transformers.${operation}`;
23707
+ },
23708
+ type: "llm" /* LLM */,
23709
+ shouldTrace: (_args, event) => isSupportedHuggingFaceTransformersTask(
23710
+ getTask(event)
23711
+ ),
23712
+ extractInput: (args, event) => ({
23713
+ input: extractInput(
23714
+ getTask(event),
23715
+ args
23716
+ ),
23717
+ metadata: extractMetadata(
23718
+ event,
23719
+ args
23720
+ )
23721
+ }),
23722
+ extractOutput: (result, event) => extractOutput(
23723
+ getTask(event),
23724
+ result
23725
+ ),
23726
+ extractMetrics: () => ({})
23727
+ })
23728
+ );
23729
+ }
23730
+ onDisable() {
23731
+ this.unsubscribers = unsubscribeAll(this.unsubscribers);
23732
+ }
23733
+ subscribeToPipelineFactory() {
23734
+ const channel2 = huggingFaceTransformersChannels.pipeline.tracingChannel();
23735
+ const handlers = {
23736
+ asyncEnd: (event) => {
23737
+ if (typeof event.result !== "function") {
23738
+ return;
23739
+ }
23740
+ registerHuggingFaceTransformersPipeline(
23741
+ event.result,
23742
+ event.arguments?.[0],
23743
+ event.arguments?.[1]
23744
+ );
23745
+ }
23746
+ };
23747
+ channel2.subscribe(handlers);
23748
+ this.unsubscribers.push(() => channel2.unsubscribe(handlers));
23749
+ }
23750
+ };
23751
+ function getTask(event) {
23752
+ const self = event.self;
23753
+ const registeredTask = getHuggingFaceTransformersPipelineInfo(self)?.task;
23754
+ if (registeredTask !== void 0) {
23755
+ return registeredTask;
23756
+ }
23757
+ if (typeof self?.task === "string") {
23758
+ return self.task;
23759
+ }
23760
+ return void 0;
23761
+ }
23762
+ function extractMetadata(event, args) {
23763
+ const metadata = {
23764
+ provider: "huggingface"
23765
+ };
23766
+ const registeredModel = getHuggingFaceTransformersPipelineInfo(
23767
+ event.self
23768
+ )?.model;
23769
+ const model = registeredModel ?? modelIdentifier(event.self);
23770
+ if (model) {
23771
+ metadata.model = model;
23772
+ }
23773
+ const task = getTask(event);
23774
+ const options = task === "question-answering" ? args[2] : args[1];
23775
+ if (isObject(options)) {
23776
+ for (const key of REQUEST_METADATA_KEYS) {
23777
+ if (options[key] !== void 0) {
23778
+ metadata[key] = options[key];
23779
+ }
23780
+ }
23781
+ }
23782
+ return metadata;
23783
+ }
23784
+ function modelIdentifier(pipeline) {
23785
+ const model = pipeline?.model;
23786
+ if (!isObject(model)) {
23787
+ return void 0;
23788
+ }
23789
+ const config = isObject(model.config) ? model.config : void 0;
23790
+ for (const value of [
23791
+ config?._name_or_path,
23792
+ config?.name_or_path,
23793
+ config?.model_id,
23794
+ config?.modelId,
23795
+ model.name
23796
+ ]) {
23797
+ if (typeof value === "string" && value.length > 0) {
23798
+ return value;
23799
+ }
23800
+ }
23801
+ return void 0;
23802
+ }
23803
+ function extractInput(task, args) {
23804
+ switch (task) {
23805
+ case "feature-extraction":
23806
+ return args[0];
23807
+ case "question-answering": {
23808
+ const question = args[0];
23809
+ const context = args[1];
23810
+ if (Array.isArray(question) && Array.isArray(context) && question.every((value) => typeof value === "string") && context.every((value) => typeof value === "string")) {
23811
+ return question.map((value, index) => [
23812
+ {
23813
+ role: "user",
23814
+ content: `Context:
23815
+ ${context[index] ?? ""}
23816
+
23817
+ Question:
23818
+ ${value}`
23819
+ }
23820
+ ]);
23821
+ }
23822
+ if (typeof question === "string" && typeof context === "string") {
23823
+ return [
23824
+ {
23825
+ role: "user",
23826
+ content: `Context:
23827
+ ${context}
23828
+
23829
+ Question:
23830
+ ${question}`
23831
+ }
23832
+ ];
23833
+ }
23834
+ return { context, question };
23835
+ }
23836
+ }
23837
+ const input = args[0];
23838
+ if (task === "text-generation" && isChat(input)) {
23839
+ return input;
23840
+ }
23841
+ if (task === "text-generation" && Array.isArray(input) && input.every(isChat)) {
23842
+ return input;
23843
+ }
23844
+ if (typeof input === "string") {
23845
+ return [{ role: "user", content: input }];
23846
+ }
23847
+ if (Array.isArray(input) && input.every((value) => typeof value === "string")) {
23848
+ return input.map((value) => [
23849
+ {
23850
+ role: "user",
23851
+ content: value
23852
+ }
23853
+ ]);
23854
+ }
23855
+ return input;
23856
+ }
23857
+ function isChat(value) {
23858
+ return Array.isArray(value) && value.length > 0 && value.every(
23859
+ (message) => isObject(message) && typeof message.role === "string" && "content" in message
23860
+ );
23861
+ }
23862
+ function extractOutput(task, result) {
23863
+ switch (task) {
23864
+ case "feature-extraction":
23865
+ return summarizeEmbedding(result);
23866
+ case "question-answering":
23867
+ return choicesFromAnswers(result);
23868
+ default:
23869
+ return choicesFromGenerations(result);
23870
+ }
23871
+ }
23872
+ function summarizeEmbedding(result) {
23873
+ if (!isObject(result) || !Array.isArray(result.dims)) {
23874
+ return void 0;
23875
+ }
23876
+ const { dims } = result;
23877
+ if (dims.length === 0 || !dims.every((dimension) => typeof dimension === "number")) {
23878
+ return void 0;
23879
+ }
23880
+ if (dims.length === 1) {
23881
+ return { embedding_length: dims[0] };
23882
+ }
23883
+ if (dims.length === 2) {
23884
+ return {
23885
+ embedding_count: dims[0],
23886
+ embedding_length: dims[1]
23887
+ };
23888
+ }
23889
+ return {
23890
+ embedding_batch_count: dims[0],
23891
+ embedding_count: dims[1],
23892
+ embedding_length: dims.at(-1) ?? 0
23893
+ };
23894
+ }
23895
+ function choicesFromAnswers(result) {
23896
+ const answers = Array.isArray(result) ? result.flat() : [result];
23897
+ const choices = answers.flatMap((answer, index) => {
23898
+ if (!isObject(answer) || typeof answer.answer !== "string") {
23899
+ return [];
23900
+ }
23901
+ return [
23902
+ {
23903
+ index,
23904
+ finish_reason: "stop",
23905
+ message: {
23906
+ role: "assistant",
23907
+ content: answer.answer
23908
+ }
23909
+ }
23910
+ ];
23911
+ });
23912
+ return choices.length > 0 ? choices : void 0;
23913
+ }
23914
+ function choicesFromGenerations(result) {
23915
+ const generations = Array.isArray(result) ? result.flat() : [result];
23916
+ const choices = generations.flatMap((generation, index) => {
23917
+ if (!isObject(generation)) {
23918
+ return [];
23919
+ }
23920
+ const generated = generation.generated_text ?? generation.summary_text;
23921
+ let content;
23922
+ if (typeof generated === "string") {
23923
+ content = generated;
23924
+ } else if (isChat(generated)) {
23925
+ content = generated.at(-1)?.content;
23926
+ }
23927
+ if (typeof content !== "string") {
23928
+ return [];
23929
+ }
23930
+ return [
23931
+ {
23932
+ index,
23933
+ finish_reason: "stop",
23934
+ message: {
23935
+ role: "assistant",
23936
+ content
23937
+ }
23938
+ }
23939
+ ];
23940
+ });
23941
+ return choices.length > 0 ? choices : void 0;
23942
+ }
23943
+
23202
23944
  // src/instrumentation/plugins/openrouter-agent-channels.ts
23203
23945
  var openRouterAgentChannels = defineChannels(
23204
23946
  "@openrouter/agent",
@@ -23598,7 +24340,7 @@ function isWrappedTool(tool) {
23598
24340
  return Boolean(tool[OPENROUTER_WRAPPED_TOOL]);
23599
24341
  }
23600
24342
  function traceToolExecution(args) {
23601
- const tracingChannel2 = openRouterAgentChannels.toolExecute.tracingChannel();
24343
+ const tracingChannel = openRouterAgentChannels.toolExecute.tracingChannel();
23602
24344
  const input = args.args.length > 0 ? args.args[0] : void 0;
23603
24345
  const event = {
23604
24346
  arguments: [input],
@@ -23608,33 +24350,33 @@ function traceToolExecution(args) {
23608
24350
  toolCallId: args.toolCallId,
23609
24351
  toolName: args.toolName
23610
24352
  };
23611
- tracingChannel2.start.publish(event);
24353
+ tracingChannel.start.publish(event);
23612
24354
  try {
23613
24355
  const result = args.execute();
23614
- return publishToolResult(tracingChannel2, event, result);
24356
+ return publishToolResult(tracingChannel, event, result);
23615
24357
  } catch (error) {
23616
24358
  event.error = normalizeError(error);
23617
- tracingChannel2.error.publish(event);
24359
+ tracingChannel.error.publish(event);
23618
24360
  throw error;
23619
24361
  }
23620
24362
  }
23621
- function publishToolResult(tracingChannel2, event, result) {
24363
+ function publishToolResult(tracingChannel, event, result) {
23622
24364
  if (isPromiseLike(result)) {
23623
24365
  return result.then(
23624
24366
  (resolved) => {
23625
24367
  event.result = resolved;
23626
- tracingChannel2.asyncEnd.publish(event);
24368
+ tracingChannel.asyncEnd.publish(event);
23627
24369
  return resolved;
23628
24370
  },
23629
24371
  (error) => {
23630
24372
  event.error = normalizeError(error);
23631
- tracingChannel2.error.publish(event);
24373
+ tracingChannel.error.publish(event);
23632
24374
  throw error;
23633
24375
  }
23634
24376
  );
23635
24377
  }
23636
24378
  event.result = result;
23637
- tracingChannel2.asyncEnd.publish(event);
24379
+ tracingChannel.asyncEnd.publish(event);
23638
24380
  return result;
23639
24381
  }
23640
24382
  function getToolCallId(context) {
@@ -24540,7 +25282,7 @@ function isWrappedTool2(tool) {
24540
25282
  return Boolean(tool[OPENROUTER_WRAPPED_TOOL2]);
24541
25283
  }
24542
25284
  function traceToolExecution2(args) {
24543
- const tracingChannel2 = openRouterChannels.toolExecute.tracingChannel();
25285
+ const tracingChannel = openRouterChannels.toolExecute.tracingChannel();
24544
25286
  const input = args.args.length > 0 ? args.args[0] : void 0;
24545
25287
  const event = {
24546
25288
  arguments: [input],
@@ -24550,33 +25292,33 @@ function traceToolExecution2(args) {
24550
25292
  toolCallId: args.toolCallId,
24551
25293
  toolName: args.toolName
24552
25294
  };
24553
- tracingChannel2.start.publish(event);
25295
+ tracingChannel.start.publish(event);
24554
25296
  try {
24555
25297
  const result = args.execute();
24556
- return publishToolResult2(tracingChannel2, event, result);
25298
+ return publishToolResult2(tracingChannel, event, result);
24557
25299
  } catch (error) {
24558
25300
  event.error = normalizeError2(error);
24559
- tracingChannel2.error.publish(event);
25301
+ tracingChannel.error.publish(event);
24560
25302
  throw error;
24561
25303
  }
24562
25304
  }
24563
- function publishToolResult2(tracingChannel2, event, result) {
25305
+ function publishToolResult2(tracingChannel, event, result) {
24564
25306
  if (isPromiseLike(result)) {
24565
25307
  return result.then(
24566
25308
  (resolved) => {
24567
25309
  event.result = resolved;
24568
- tracingChannel2.asyncEnd.publish(event);
25310
+ tracingChannel.asyncEnd.publish(event);
24569
25311
  return resolved;
24570
25312
  },
24571
25313
  (error) => {
24572
25314
  event.error = normalizeError2(error);
24573
- tracingChannel2.error.publish(event);
25315
+ tracingChannel.error.publish(event);
24574
25316
  throw error;
24575
25317
  }
24576
25318
  );
24577
25319
  }
24578
25320
  event.result = result;
24579
- tracingChannel2.asyncEnd.publish(event);
25321
+ tracingChannel.asyncEnd.publish(event);
24580
25322
  return result;
24581
25323
  }
24582
25324
  function getToolCallId2(context) {
@@ -25766,7 +26508,7 @@ var GoogleADKPlugin = class extends BasePlugin {
25766
26508
  this.activeAgentSpans.clear();
25767
26509
  }
25768
26510
  subscribeToRunnerRunAsync() {
25769
- const tracingChannel2 = googleADKChannels.runnerRunAsync.tracingChannel();
26511
+ const tracingChannel = googleADKChannels.runnerRunAsync.tracingChannel();
25770
26512
  const states = /* @__PURE__ */ new WeakMap();
25771
26513
  const createState = (event) => {
25772
26514
  const params = event.arguments[0] ?? {};
@@ -25797,7 +26539,7 @@ var GoogleADKPlugin = class extends BasePlugin {
25797
26539
  return { span, startTime, events: [], contextKey };
25798
26540
  };
25799
26541
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart3(
25800
- tracingChannel2,
26542
+ tracingChannel,
25801
26543
  states,
25802
26544
  createState
25803
26545
  );
@@ -25849,14 +26591,14 @@ var GoogleADKPlugin = class extends BasePlugin {
25849
26591
  states.delete(event);
25850
26592
  }
25851
26593
  };
25852
- tracingChannel2.subscribe(handlers);
26594
+ tracingChannel.subscribe(handlers);
25853
26595
  this.unsubscribers.push(() => {
25854
26596
  unbindCurrentSpanStore?.();
25855
- tracingChannel2.unsubscribe(handlers);
26597
+ tracingChannel.unsubscribe(handlers);
25856
26598
  });
25857
26599
  }
25858
26600
  subscribeToAgentRunAsync() {
25859
- const tracingChannel2 = googleADKChannels.agentRunAsync.tracingChannel();
26601
+ const tracingChannel = googleADKChannels.agentRunAsync.tracingChannel();
25860
26602
  const states = /* @__PURE__ */ new WeakMap();
25861
26603
  const createState = (event) => {
25862
26604
  const parentContext = event.arguments[0];
@@ -25905,7 +26647,7 @@ var GoogleADKPlugin = class extends BasePlugin {
25905
26647
  return { span, startTime, events: [], contextKey, name: agentName };
25906
26648
  };
25907
26649
  const unbindCurrentSpanStore = bindCurrentSpanStoreToStart3(
25908
- tracingChannel2,
26650
+ tracingChannel,
25909
26651
  states,
25910
26652
  createState
25911
26653
  );
@@ -25957,14 +26699,14 @@ var GoogleADKPlugin = class extends BasePlugin {
25957
26699
  states.delete(event);
25958
26700
  }
25959
26701
  };
25960
- tracingChannel2.subscribe(handlers);
26702
+ tracingChannel.subscribe(handlers);
25961
26703
  this.unsubscribers.push(() => {
25962
26704
  unbindCurrentSpanStore?.();
25963
- tracingChannel2.unsubscribe(handlers);
26705
+ tracingChannel.unsubscribe(handlers);
25964
26706
  });
25965
26707
  }
25966
26708
  subscribeToToolRunAsync() {
25967
- const tracingChannel2 = googleADKChannels.toolRunAsync.tracingChannel();
26709
+ const tracingChannel = googleADKChannels.toolRunAsync.tracingChannel();
25968
26710
  const states = /* @__PURE__ */ new WeakMap();
25969
26711
  const handlers = {
25970
26712
  start: (event) => {
@@ -26031,9 +26773,9 @@ var GoogleADKPlugin = class extends BasePlugin {
26031
26773
  states.delete(event);
26032
26774
  }
26033
26775
  };
26034
- tracingChannel2.subscribe(handlers);
26776
+ tracingChannel.subscribe(handlers);
26035
26777
  this.unsubscribers.push(() => {
26036
- tracingChannel2.unsubscribe(handlers);
26778
+ tracingChannel.unsubscribe(handlers);
26037
26779
  });
26038
26780
  }
26039
26781
  };
@@ -26109,10 +26851,10 @@ function bindAsyncIterableToCurrentSpan(stream, span) {
26109
26851
  }
26110
26852
  return stream;
26111
26853
  }
26112
- function bindCurrentSpanStoreToStart3(tracingChannel2, states, create) {
26854
+ function bindCurrentSpanStoreToStart3(tracingChannel, states, create) {
26113
26855
  const state = _internalGetGlobalState();
26114
26856
  const contextManager = state?.contextManager;
26115
- const startChannel = tracingChannel2.start;
26857
+ const startChannel = tracingChannel.start;
26116
26858
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
26117
26859
  if (!startChannel?.bindStore || !currentSpanStore) {
26118
26860
  return void 0;
@@ -26364,15 +27106,32 @@ function aggregateUsageFromEvents(events) {
26364
27106
  if (usage.thoughtsTokenCount !== void 0) {
26365
27107
  aggregated.thoughtsTokenCount = (aggregated.thoughtsTokenCount ?? 0) + usage.thoughtsTokenCount;
26366
27108
  }
27109
+ if (usage.toolUsePromptTokenCount !== void 0) {
27110
+ aggregated.toolUsePromptTokenCount = (aggregated.toolUsePromptTokenCount ?? 0) + usage.toolUsePromptTokenCount;
27111
+ }
27112
+ for (const detailsField of [
27113
+ "promptTokensDetails",
27114
+ "cacheTokensDetails",
27115
+ "candidatesTokensDetails",
27116
+ "toolUsePromptTokensDetails"
27117
+ ]) {
27118
+ const details = usage[detailsField];
27119
+ if (details !== void 0) {
27120
+ aggregated[detailsField] = [
27121
+ ...aggregated[detailsField] ?? [],
27122
+ ...details
27123
+ ];
27124
+ }
27125
+ }
26367
27126
  }
26368
27127
  return hasUsage ? aggregated : void 0;
26369
27128
  }
26370
27129
  function populateUsageMetrics2(metrics, usage) {
26371
- if (usage.promptTokenCount !== void 0) {
26372
- metrics.prompt_tokens = usage.promptTokenCount;
27130
+ if (usage.promptTokenCount !== void 0 || usage.toolUsePromptTokenCount !== void 0) {
27131
+ metrics.prompt_tokens = (usage.promptTokenCount ?? 0) + (usage.toolUsePromptTokenCount ?? 0);
26373
27132
  }
26374
- if (usage.candidatesTokenCount !== void 0) {
26375
- metrics.completion_tokens = usage.candidatesTokenCount;
27133
+ if (usage.candidatesTokenCount !== void 0 || usage.thoughtsTokenCount !== void 0) {
27134
+ metrics.completion_tokens = (usage.candidatesTokenCount ?? 0) + (usage.thoughtsTokenCount ?? 0);
26376
27135
  }
26377
27136
  if (usage.totalTokenCount !== void 0) {
26378
27137
  metrics.tokens = usage.totalTokenCount;
@@ -26383,6 +27142,19 @@ function populateUsageMetrics2(metrics, usage) {
26383
27142
  if (usage.thoughtsTokenCount !== void 0) {
26384
27143
  metrics.completion_reasoning_tokens = usage.thoughtsTokenCount;
26385
27144
  }
27145
+ for (const detail of usage.promptTokensDetails ?? []) {
27146
+ if (detail.modality === "AUDIO" && detail.tokenCount !== void 0) {
27147
+ metrics.prompt_audio_tokens = (metrics.prompt_audio_tokens ?? 0) + detail.tokenCount;
27148
+ }
27149
+ }
27150
+ for (const detail of usage.candidatesTokensDetails ?? []) {
27151
+ if (detail.modality === "AUDIO" && detail.tokenCount !== void 0) {
27152
+ metrics.completion_audio_tokens = (metrics.completion_audio_tokens ?? 0) + detail.tokenCount;
27153
+ }
27154
+ if (detail.modality === "IMAGE" && detail.tokenCount !== void 0) {
27155
+ metrics.completion_image_tokens = (metrics.completion_image_tokens ?? 0) + detail.tokenCount;
27156
+ }
27157
+ }
26386
27158
  }
26387
27159
  function cleanMetrics4(metrics) {
26388
27160
  const cleaned = {};
@@ -27948,10 +28720,10 @@ var GenkitPlugin = class extends BasePlugin {
27948
28720
  this.subscribeToActionStream();
27949
28721
  }
27950
28722
  subscribeToActionRun() {
27951
- const tracingChannel2 = genkitChannels.actionRun.tracingChannel();
28723
+ const tracingChannel = genkitChannels.actionRun.tracingChannel();
27952
28724
  const states = /* @__PURE__ */ new WeakMap();
27953
28725
  const unbindCurrentSpanStore = bindActionCurrentSpanStoreToStart(
27954
- tracingChannel2,
28726
+ tracingChannel,
27955
28727
  states,
27956
28728
  (event) => startActionRunSpan(event)
27957
28729
  );
@@ -27988,17 +28760,17 @@ var GenkitPlugin = class extends BasePlugin {
27988
28760
  states.delete(event);
27989
28761
  }
27990
28762
  };
27991
- tracingChannel2.subscribe(handlers);
28763
+ tracingChannel.subscribe(handlers);
27992
28764
  this.unsubscribers.push(() => {
27993
28765
  unbindCurrentSpanStore?.();
27994
- tracingChannel2.unsubscribe(handlers);
28766
+ tracingChannel.unsubscribe(handlers);
27995
28767
  });
27996
28768
  }
27997
28769
  subscribeToActionSpan() {
27998
- const tracingChannel2 = genkitCoreChannels.actionSpan.tracingChannel();
28770
+ const tracingChannel = genkitCoreChannels.actionSpan.tracingChannel();
27999
28771
  const states = /* @__PURE__ */ new WeakMap();
28000
28772
  const unbindCurrentSpanStore = bindActionCurrentSpanStoreToStart(
28001
- tracingChannel2,
28773
+ tracingChannel,
28002
28774
  states,
28003
28775
  (event) => startActionSpan(event)
28004
28776
  );
@@ -28036,10 +28808,10 @@ var GenkitPlugin = class extends BasePlugin {
28036
28808
  states.delete(event);
28037
28809
  }
28038
28810
  };
28039
- tracingChannel2.subscribe(handlers);
28811
+ tracingChannel.subscribe(handlers);
28040
28812
  this.unsubscribers.push(() => {
28041
28813
  unbindCurrentSpanStore?.();
28042
- tracingChannel2.unsubscribe(handlers);
28814
+ tracingChannel.unsubscribe(handlers);
28043
28815
  });
28044
28816
  }
28045
28817
  subscribeToActionStream() {
@@ -28108,10 +28880,10 @@ function ensureActionSpanState(states, event, create) {
28108
28880
  }
28109
28881
  return created;
28110
28882
  }
28111
- function bindActionCurrentSpanStoreToStart(tracingChannel2, states, create) {
28883
+ function bindActionCurrentSpanStoreToStart(tracingChannel, states, create) {
28112
28884
  const state = _internalGetGlobalState();
28113
28885
  const contextManager = state?.contextManager;
28114
- const startChannel = tracingChannel2.start;
28886
+ const startChannel = tracingChannel.start;
28115
28887
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
28116
28888
  if (!startChannel?.bindStore || !currentSpanStore) {
28117
28889
  return void 0;
@@ -30473,7 +31245,7 @@ var LangChainPlugin = class extends BasePlugin {
30473
31245
  this.injectedManagers = /* @__PURE__ */ new WeakSet();
30474
31246
  }
30475
31247
  subscribeToConfigure(channel2) {
30476
- const tracingChannel2 = channel2.tracingChannel();
31248
+ const tracingChannel = channel2.tracingChannel();
30477
31249
  const handlers = {
30478
31250
  start: (event) => {
30479
31251
  injectHandlerIntoArguments(event.arguments);
@@ -30482,9 +31254,9 @@ var LangChainPlugin = class extends BasePlugin {
30482
31254
  this.injectHandler(event.result);
30483
31255
  }
30484
31256
  };
30485
- tracingChannel2.subscribe(handlers);
31257
+ tracingChannel.subscribe(handlers);
30486
31258
  this.unsubscribers.push(() => {
30487
- tracingChannel2.unsubscribe(handlers);
31259
+ tracingChannel.unsubscribe(handlers);
30488
31260
  });
30489
31261
  }
30490
31262
  injectHandler(result) {
@@ -30748,7 +31520,7 @@ var LangSmithPlugin = class extends BasePlugin {
30748
31520
  const inputs = preferOwnValue(run, previous, "inputs");
30749
31521
  const outputs = preferOwnValue(run, previous, "outputs");
30750
31522
  const error = errorMessage(preferOwnValue(run, previous, "error"));
30751
- const metadata = extractMetadata(run, previous);
31523
+ const metadata = extractMetadata2(run, previous);
30752
31524
  const tags = extractTags(preferOwnValue(run, previous, "tags"));
30753
31525
  const metrics = extractMetrics(run, previous);
30754
31526
  span.log({
@@ -30853,7 +31625,7 @@ function mapRunType(runType) {
30853
31625
  return "task" /* TASK */;
30854
31626
  }
30855
31627
  }
30856
- function extractMetadata(run, previous) {
31628
+ function extractMetadata2(run, previous) {
30857
31629
  const extra = preferOwnValue(run, previous, "extra");
30858
31630
  const rawMetadata = ownValue(extra, "metadata");
30859
31631
  if (!isRecord2(rawMetadata)) {
@@ -31984,9 +32756,9 @@ var StrandsAgentSDKPlugin = class extends BasePlugin {
31984
32756
  });
31985
32757
  }
31986
32758
  subscribeToMultiAgentStream(channel2, operation) {
31987
- const tracingChannel2 = channel2.tracingChannel();
32759
+ const tracingChannel = channel2.tracingChannel();
31988
32760
  const states = /* @__PURE__ */ new WeakMap();
31989
- const unbindAutoInstrumentationSuppression = bindAutoInstrumentationSuppressionToStart(tracingChannel2);
32761
+ const unbindAutoInstrumentationSuppression = bindAutoInstrumentationSuppressionToStart(tracingChannel);
31990
32762
  const handlers = {
31991
32763
  start: (event) => {
31992
32764
  const state = startMultiAgentStream(
@@ -32040,10 +32812,10 @@ var StrandsAgentSDKPlugin = class extends BasePlugin {
32040
32812
  states.delete(event);
32041
32813
  }
32042
32814
  };
32043
- tracingChannel2.subscribe(handlers);
32815
+ tracingChannel.subscribe(handlers);
32044
32816
  this.unsubscribers.push(() => {
32045
32817
  unbindAutoInstrumentationSuppression?.();
32046
- tracingChannel2.unsubscribe(handlers);
32818
+ tracingChannel.unsubscribe(handlers);
32047
32819
  });
32048
32820
  }
32049
32821
  };
@@ -32226,6 +32998,15 @@ function handleMultiAgentStreamEvent(state, event, activeChildParents) {
32226
32998
  logInstrumentationError5("Strands Agent SDK multi-agent event", error);
32227
32999
  }
32228
33000
  }
33001
+ function buildModelSpanInput(event, attachmentCache) {
33002
+ const systemPrompt = typeof event.agent?.systemPrompt === "string" && event.agent.systemPrompt.length > 0 ? event.agent.systemPrompt : void 0;
33003
+ const processedMessages = Array.isArray(event.agent?.messages) ? processStrandsInputAttachments(event.agent.messages, attachmentCache) : void 0;
33004
+ if (!systemPrompt) {
33005
+ return processedMessages;
33006
+ }
33007
+ const systemMessage = { role: "system", content: systemPrompt };
33008
+ return Array.isArray(processedMessages) ? [systemMessage, ...processedMessages] : [systemMessage];
33009
+ }
32229
33010
  function startModelSpan(state, event) {
32230
33011
  if (state.activeModel) {
32231
33012
  finalizeModelSpan(state);
@@ -32243,10 +33024,7 @@ function startModelSpan(state, event) {
32243
33024
  withSpanInstrumentationName(
32244
33025
  {
32245
33026
  event: {
32246
- input: Array.isArray(event.agent?.messages) ? processStrandsInputAttachments(
32247
- event.agent.messages,
32248
- state.attachmentCache
32249
- ) : void 0,
33027
+ input: buildModelSpanInput(event, state.attachmentCache),
32250
33028
  metadata
32251
33029
  },
32252
33030
  name: formatModelSpanName(model),
@@ -32886,6 +33664,555 @@ function logInstrumentationError5(context, error) {
32886
33664
  debugLogger.debug(`${context}:`, error);
32887
33665
  }
32888
33666
 
33667
+ // src/instrumentation/plugins/cloudflare-ai-chat-channels.ts
33668
+ var cloudflareAIChatChannels = defineChannels(
33669
+ "@cloudflare/ai-chat",
33670
+ {
33671
+ runExclusiveChatTurn: channel({
33672
+ channelName: "AIChatAgent._runExclusiveChatTurn",
33673
+ kind: "async"
33674
+ }),
33675
+ onChatResponse: channel({
33676
+ channelName: "AIChatAgent.onChatResponse",
33677
+ kind: "sync-stream"
33678
+ })
33679
+ },
33680
+ { instrumentationName: INSTRUMENTATION_NAMES.CLOUDFLARE_AI_CHAT }
33681
+ );
33682
+
33683
+ // src/instrumentation/plugins/cloudflare-ai-chat-instrumentation.ts
33684
+ var wrappedTurnRunners = /* @__PURE__ */ new WeakSet();
33685
+ var wrappedResponseHooks = /* @__PURE__ */ new WeakSet();
33686
+ function instrumentCloudflareAIChatAgent(agent) {
33687
+ try {
33688
+ const original = Reflect.get(agent, "_runExclusiveChatTurn");
33689
+ if (typeof original !== "function" || wrappedTurnRunners.has(original)) {
33690
+ return agent;
33691
+ }
33692
+ const wrapped = async function(...args) {
33693
+ return cloudflareAIChatChannels.runExclusiveChatTurn.tracePromise(
33694
+ () => Reflect.apply(original, this, args),
33695
+ {
33696
+ arguments: args,
33697
+ self: this
33698
+ }
33699
+ );
33700
+ };
33701
+ wrappedTurnRunners.add(wrapped);
33702
+ defineWrappedMethod(agent, "_runExclusiveChatTurn", original, wrapped);
33703
+ } catch (error) {
33704
+ debugLogger.debug("Failed to wrap @cloudflare/ai-chat turn runner:", error);
33705
+ }
33706
+ return agent;
33707
+ }
33708
+ function instrumentCloudflareAIChatResponseHook(agent) {
33709
+ try {
33710
+ const original = Reflect.get(agent, "onChatResponse");
33711
+ if (typeof original !== "function" || wrappedResponseHooks.has(original)) {
33712
+ return;
33713
+ }
33714
+ const wrapped = function(result) {
33715
+ const args = [result];
33716
+ return cloudflareAIChatChannels.onChatResponse.traceSync(
33717
+ () => Reflect.apply(original, this, args),
33718
+ {
33719
+ arguments: args,
33720
+ self: this
33721
+ }
33722
+ );
33723
+ };
33724
+ wrappedResponseHooks.add(wrapped);
33725
+ defineWrappedMethod(agent, "onChatResponse", original, wrapped);
33726
+ } catch (error) {
33727
+ debugLogger.debug(
33728
+ "Failed to wrap @cloudflare/ai-chat response hook:",
33729
+ error
33730
+ );
33731
+ }
33732
+ }
33733
+ function defineWrappedMethod(target, property, original, wrapped) {
33734
+ const ownDescriptor = Object.getOwnPropertyDescriptor(target, property);
33735
+ Object.defineProperty(target, property, {
33736
+ configurable: ownDescriptor?.configurable ?? true,
33737
+ enumerable: ownDescriptor?.enumerable ?? false,
33738
+ value: wrapped,
33739
+ writable: ownDescriptor && "writable" in ownDescriptor ? ownDescriptor.writable : true
33740
+ });
33741
+ try {
33742
+ Object.defineProperty(wrapped, "name", {
33743
+ configurable: true,
33744
+ value: original.name
33745
+ });
33746
+ } catch {
33747
+ }
33748
+ }
33749
+
33750
+ // src/instrumentation/plugins/cloudflare-ai-chat-plugin.ts
33751
+ var BLOCKED_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
33752
+ var RESPONSE_STATE_RETENTION_MS = 6e4;
33753
+ var CloudflareAIChatPlugin = class extends BasePlugin {
33754
+ activeStates = /* @__PURE__ */ new Set();
33755
+ activeTurns = /* @__PURE__ */ new WeakMap();
33756
+ eventStates = /* @__PURE__ */ new WeakMap();
33757
+ onEnable() {
33758
+ this.subscribeToResponseHook();
33759
+ this.subscribeToTurnRunner();
33760
+ }
33761
+ onDisable() {
33762
+ for (const unsubscribe of this.unsubscribers) {
33763
+ unsubscribe();
33764
+ }
33765
+ this.unsubscribers = [];
33766
+ for (const state of this.activeStates) {
33767
+ this.cleanupState(state);
33768
+ }
33769
+ this.activeStates.clear();
33770
+ }
33771
+ subscribeToTurnRunner() {
33772
+ const tracingChannel = cloudflareAIChatChannels.runExclusiveChatTurn.tracingChannel();
33773
+ const unbindCurrentSpanStore = this.bindCurrentSpanStore(tracingChannel);
33774
+ const handlers = {
33775
+ start: (event) => {
33776
+ this.ensureEventState(event);
33777
+ },
33778
+ asyncEnd: (event) => {
33779
+ this.finishEvent(event);
33780
+ },
33781
+ error: (event) => {
33782
+ this.finishEvent(event, event.error);
33783
+ }
33784
+ };
33785
+ tracingChannel.subscribe(handlers);
33786
+ this.unsubscribers.push(() => {
33787
+ unbindCurrentSpanStore?.();
33788
+ tracingChannel.unsubscribe(handlers);
33789
+ });
33790
+ }
33791
+ subscribeToResponseHook() {
33792
+ const tracingChannel = cloudflareAIChatChannels.onChatResponse.tracingChannel();
33793
+ const handlers = {
33794
+ start: (event) => {
33795
+ let state;
33796
+ try {
33797
+ const agent = asObject(event.self);
33798
+ const result = event.arguments[0];
33799
+ state = agent ? this.findResponseState(
33800
+ agent,
33801
+ stringValue3(ownValue2(result, "requestId"))
33802
+ ) : void 0;
33803
+ if (!state) {
33804
+ return;
33805
+ }
33806
+ state.responseObserved = true;
33807
+ const output = serializeMessage(ownValue2(result, "message"));
33808
+ const status = stringValue3(ownValue2(result, "status"));
33809
+ const error = ownValue2(result, "error");
33810
+ const input = ownValue2(result, "continuation") === true ? state.input : serializeMessages(readProperty(agent, "messages"))?.filter(
33811
+ (message) => typeof output?.id !== "string" || message.id !== output.id
33812
+ );
33813
+ state.span.log({
33814
+ ...input !== void 0 ? { input } : {},
33815
+ ...output !== void 0 ? { output } : {},
33816
+ ...status === "error" && error !== void 0 ? { error } : {}
33817
+ });
33818
+ } catch (error) {
33819
+ debugLogger.debug(
33820
+ "Failed to process @cloudflare/ai-chat response hook:",
33821
+ error
33822
+ );
33823
+ } finally {
33824
+ if (state?.settled) {
33825
+ this.cleanupState(state);
33826
+ }
33827
+ }
33828
+ }
33829
+ };
33830
+ tracingChannel.subscribe(handlers);
33831
+ this.unsubscribers.push(() => tracingChannel.unsubscribe(handlers));
33832
+ }
33833
+ bindCurrentSpanStore(tracingChannel) {
33834
+ const globalState = _internalGetGlobalState();
33835
+ const contextManager = globalState?.contextManager;
33836
+ const startChannel = tracingChannel.start;
33837
+ const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
33838
+ if (!startChannel || !currentSpanStore || !contextManager) {
33839
+ return void 0;
33840
+ }
33841
+ startChannel.bindStore(currentSpanStore, (event) => {
33842
+ const state = this.ensureEventState(event);
33843
+ return state ? contextManager.wrapSpanForStore(state.span) : currentSpanStore.getStore();
33844
+ });
33845
+ return () => startChannel.unbindStore(currentSpanStore);
33846
+ }
33847
+ ensureEventState(event) {
33848
+ const eventKey = event;
33849
+ const known = this.eventStates.get(eventKey);
33850
+ if (known) {
33851
+ return known;
33852
+ }
33853
+ try {
33854
+ const agent = asObject(event.self);
33855
+ const requestId = stringValue3(event.arguments[0]);
33856
+ const key = requestId ?? /* @__PURE__ */ Symbol("cloudflare-ai-chat-turn");
33857
+ const activeForAgent = agent ? this.getActiveTurns(agent) : void 0;
33858
+ const existing = activeForAgent?.get(key);
33859
+ const state = existing && !existing.settled ? existing : this.createTurnState(agent, key);
33860
+ if (existing && !existing.settled) {
33861
+ state.depth += 1;
33862
+ }
33863
+ this.eventStates.set(eventKey, state);
33864
+ this.bindTurnCallback(event, agent, state);
33865
+ if (agent) {
33866
+ instrumentCloudflareAIChatResponseHook(agent);
33867
+ }
33868
+ return state;
33869
+ } catch (error) {
33870
+ debugLogger.debug(
33871
+ "Failed to start @cloudflare/ai-chat instrumentation:",
33872
+ error
33873
+ );
33874
+ return void 0;
33875
+ }
33876
+ }
33877
+ createTurnState(agent, key) {
33878
+ const span = startSpan(
33879
+ withSpanInstrumentationName(
33880
+ {
33881
+ name: "AIChatAgent.onChatMessage",
33882
+ spanAttributes: { type: "task" /* TASK */ }
33883
+ },
33884
+ INSTRUMENTATION_NAMES.CLOUDFLARE_AI_CHAT
33885
+ )
33886
+ );
33887
+ const state = {
33888
+ agent,
33889
+ depth: 1,
33890
+ ended: false,
33891
+ key,
33892
+ responseObserved: false,
33893
+ settled: false,
33894
+ span
33895
+ };
33896
+ this.activeStates.add(state);
33897
+ if (agent) {
33898
+ this.getActiveTurns(agent).set(key, state);
33899
+ }
33900
+ return state;
33901
+ }
33902
+ bindTurnCallback(event, agent, state) {
33903
+ const callback = event.arguments[1];
33904
+ if (typeof callback !== "function") {
33905
+ return;
33906
+ }
33907
+ try {
33908
+ event.arguments[1] = function(...args) {
33909
+ return withCurrent(state.span, () => {
33910
+ try {
33911
+ const input = serializeMessages(readProperty(agent, "messages"));
33912
+ if (input !== void 0 && state.input === void 0) {
33913
+ state.input = input;
33914
+ state.span.log({ input });
33915
+ }
33916
+ } catch (error) {
33917
+ debugLogger.debug(
33918
+ "Failed to capture @cloudflare/ai-chat messages:",
33919
+ error
33920
+ );
33921
+ }
33922
+ return Reflect.apply(callback, this, args);
33923
+ });
33924
+ };
33925
+ } catch (error) {
33926
+ debugLogger.debug(
33927
+ "Failed to bind @cloudflare/ai-chat turn callback context:",
33928
+ error
33929
+ );
33930
+ }
33931
+ }
33932
+ finishEvent(event, error) {
33933
+ const eventKey = event;
33934
+ const state = this.eventStates.get(eventKey);
33935
+ if (!state || state.ended) {
33936
+ return;
33937
+ }
33938
+ this.eventStates.delete(eventKey);
33939
+ if (error !== void 0 && state.pendingError === void 0) {
33940
+ state.pendingError = error;
33941
+ }
33942
+ state.depth -= 1;
33943
+ if (state.depth === 0) {
33944
+ state.settled = true;
33945
+ this.endState(state);
33946
+ if (state.responseObserved || error !== void 0) {
33947
+ this.cleanupState(state);
33948
+ } else {
33949
+ state.cleanupTimer = setTimeout(
33950
+ () => this.cleanupState(state),
33951
+ RESPONSE_STATE_RETENTION_MS
33952
+ );
33953
+ if (typeof state.cleanupTimer === "object" && state.cleanupTimer !== null && "unref" in state.cleanupTimer && typeof state.cleanupTimer.unref === "function") {
33954
+ state.cleanupTimer.unref();
33955
+ }
33956
+ }
33957
+ }
33958
+ }
33959
+ endState(state) {
33960
+ if (state.ended) {
33961
+ return;
33962
+ }
33963
+ state.ended = true;
33964
+ try {
33965
+ if (state.pendingError !== void 0) {
33966
+ state.span.log({ error: state.pendingError });
33967
+ }
33968
+ } finally {
33969
+ state.span.end();
33970
+ }
33971
+ }
33972
+ cleanupState(state) {
33973
+ if (state.cleanupTimer !== void 0) {
33974
+ clearTimeout(state.cleanupTimer);
33975
+ state.cleanupTimer = void 0;
33976
+ }
33977
+ try {
33978
+ this.endState(state);
33979
+ } finally {
33980
+ this.activeStates.delete(state);
33981
+ if (state.agent) {
33982
+ const activeForAgent = this.activeTurns.get(state.agent);
33983
+ if (activeForAgent?.get(state.key) === state) {
33984
+ activeForAgent.delete(state.key);
33985
+ }
33986
+ }
33987
+ }
33988
+ }
33989
+ getActiveTurns(agent) {
33990
+ let turns = this.activeTurns.get(agent);
33991
+ if (!turns) {
33992
+ turns = /* @__PURE__ */ new Map();
33993
+ this.activeTurns.set(agent, turns);
33994
+ }
33995
+ return turns;
33996
+ }
33997
+ findResponseState(agent, requestId) {
33998
+ const turns = this.activeTurns.get(agent);
33999
+ if (!turns) {
34000
+ return void 0;
34001
+ }
34002
+ if (requestId !== void 0) {
34003
+ return turns.get(requestId);
34004
+ }
34005
+ const active = [...turns.values()];
34006
+ return active.length === 1 ? active[0] : void 0;
34007
+ }
34008
+ };
34009
+ function asObject(value) {
34010
+ return value !== null && (typeof value === "object" || typeof value === "function") ? value : void 0;
34011
+ }
34012
+ function readProperty(value, key) {
34013
+ const object = asObject(value);
34014
+ return object ? Reflect.get(object, key) : void 0;
34015
+ }
34016
+ function ownValue2(value, key) {
34017
+ const object = asObject(value);
34018
+ if (!object) {
34019
+ return void 0;
34020
+ }
34021
+ const descriptor = Object.getOwnPropertyDescriptor(object, key);
34022
+ return descriptor && "value" in descriptor ? descriptor.value : void 0;
34023
+ }
34024
+ function stringValue3(value) {
34025
+ return typeof value === "string" ? value : void 0;
34026
+ }
34027
+ function serializeMessages(value) {
34028
+ if (!Array.isArray(value)) {
34029
+ return void 0;
34030
+ }
34031
+ return value.flatMap((message) => {
34032
+ const serialized = serializeMessage(message);
34033
+ return serialized === void 0 ? [] : [serialized];
34034
+ });
34035
+ }
34036
+ function serializeMessage(value) {
34037
+ const message = asObject(value);
34038
+ if (!message) {
34039
+ return void 0;
34040
+ }
34041
+ const serialized = [];
34042
+ const id = ownValue2(message, "id");
34043
+ const role = ownValue2(message, "role");
34044
+ const parts = ownValue2(message, "parts");
34045
+ if (typeof id === "string") {
34046
+ serialized.push(["id", id]);
34047
+ }
34048
+ if (typeof role === "string") {
34049
+ serialized.push(["role", role]);
34050
+ }
34051
+ const sanitizedParts = sanitizeLoggedValue2(parts);
34052
+ if (sanitizedParts !== void 0) {
34053
+ serialized.push(["parts", sanitizedParts]);
34054
+ }
34055
+ return serialized.length > 0 ? Object.fromEntries(serialized) : void 0;
34056
+ }
34057
+ function sanitizeLoggedValue2(value, seen = /* @__PURE__ */ new WeakSet(), depth = 0) {
34058
+ if (value === null || typeof value === "string" || typeof value === "boolean") {
34059
+ return value;
34060
+ }
34061
+ if (typeof value === "number") {
34062
+ return Number.isFinite(value) ? value : void 0;
34063
+ }
34064
+ const object = asObject(value);
34065
+ if (!object || depth >= 20 || typeof value === "function") {
34066
+ return void 0;
34067
+ }
34068
+ if (seen.has(object)) {
34069
+ return "[Circular]";
34070
+ }
34071
+ seen.add(object);
34072
+ if (Array.isArray(value)) {
34073
+ return value.map((entry) => sanitizeLoggedValue2(entry, seen, depth + 1));
34074
+ }
34075
+ const entries = [];
34076
+ for (const [key, descriptor] of Object.entries(
34077
+ Object.getOwnPropertyDescriptors(object)
34078
+ )) {
34079
+ if (BLOCKED_KEYS.has(key) || !descriptor.enumerable || !("value" in descriptor)) {
34080
+ continue;
34081
+ }
34082
+ const sanitized = sanitizeLoggedValue2(descriptor.value, seen, depth + 1);
34083
+ if (sanitized !== void 0) {
34084
+ entries.push([key, sanitized]);
34085
+ }
34086
+ }
34087
+ return Object.fromEntries(entries);
34088
+ }
34089
+
34090
+ // src/instrumentation/plugins/cloudflare-agents-channels.ts
34091
+ var cloudflareAgentsChannels = defineChannels(
34092
+ "agents",
34093
+ {
34094
+ runAgentTool: channel({
34095
+ channelName: "Agent.runAgentTool",
34096
+ kind: "async"
34097
+ })
34098
+ },
34099
+ { instrumentationName: INSTRUMENTATION_NAMES.CLOUDFLARE_AGENTS }
34100
+ );
34101
+
34102
+ // src/instrumentation/plugins/cloudflare-agents-plugin.ts
34103
+ var CLOUDFLARE_WORKERS_CONTEXT = {
34104
+ span_origin: {
34105
+ environment: { type: "server", name: "cloudflare_workers" }
34106
+ }
34107
+ };
34108
+ var CloudflareAgentsPlugin = class extends BasePlugin {
34109
+ onEnable() {
34110
+ const channel2 = cloudflareAgentsChannels.runAgentTool.tracingChannel();
34111
+ const spans = /* @__PURE__ */ new WeakMap();
34112
+ const handlers = {
34113
+ start: (event) => {
34114
+ try {
34115
+ const agentClass = event.arguments[0];
34116
+ const options = event.arguments[1];
34117
+ if (ownValue3(options, "detached")) {
34118
+ return;
34119
+ }
34120
+ const name = ownValue3(agentClass, "name");
34121
+ if (typeof name !== "string" || name.length === 0) {
34122
+ debugLogger.warn(
34123
+ "Skipping Cloudflare Agents runAgentTool span because the child agent class has no name."
34124
+ );
34125
+ return;
34126
+ }
34127
+ const span = _internalStartSpanWithContext(
34128
+ withSpanInstrumentationName(
34129
+ {
34130
+ name,
34131
+ spanAttributes: { type: "tool" /* TOOL */ },
34132
+ event: {
34133
+ input: ownValue3(options, "input")
34134
+ }
34135
+ },
34136
+ INSTRUMENTATION_NAMES.CLOUDFLARE_AGENTS
34137
+ ),
34138
+ CLOUDFLARE_WORKERS_CONTEXT
34139
+ );
34140
+ spans.set(event, span);
34141
+ } catch (error) {
34142
+ logInstrumentationError6("start", error);
34143
+ }
34144
+ },
34145
+ asyncEnd: (event) => {
34146
+ const span = spans.get(event);
34147
+ if (!span) {
34148
+ return;
34149
+ }
34150
+ spans.delete(event);
34151
+ try {
34152
+ const status = ownValue3(event.result, "status");
34153
+ if (status === "completed") {
34154
+ span.log({ output: ownValue3(event.result, "output") });
34155
+ } else {
34156
+ const error = ownValue3(event.result, "error");
34157
+ if (typeof error === "string") {
34158
+ span.log({ error });
34159
+ }
34160
+ }
34161
+ } catch (error) {
34162
+ logInstrumentationError6("completion", error);
34163
+ } finally {
34164
+ safelyEndSpan(span);
34165
+ }
34166
+ },
34167
+ error: (event) => {
34168
+ const span = spans.get(event);
34169
+ if (!span) {
34170
+ return;
34171
+ }
34172
+ spans.delete(event);
34173
+ try {
34174
+ span.log({ error: event.error });
34175
+ } catch (error) {
34176
+ logInstrumentationError6("rejection", error);
34177
+ } finally {
34178
+ safelyEndSpan(span);
34179
+ }
34180
+ }
34181
+ };
34182
+ channel2.subscribe(handlers);
34183
+ this.unsubscribers.push(() => channel2.unsubscribe(handlers));
34184
+ }
34185
+ onDisable() {
34186
+ for (const unsubscribe of this.unsubscribers) {
34187
+ unsubscribe();
34188
+ }
34189
+ this.unsubscribers = [];
34190
+ }
34191
+ };
34192
+ function ownValue3(value, key) {
34193
+ if (!isObjectLike2(value)) {
34194
+ return void 0;
34195
+ }
34196
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
34197
+ return descriptor && "value" in descriptor ? descriptor.value : void 0;
34198
+ }
34199
+ function isObjectLike2(value) {
34200
+ return typeof value === "object" && value !== null || typeof value === "function";
34201
+ }
34202
+ function safelyEndSpan(span) {
34203
+ try {
34204
+ span.end();
34205
+ } catch (error) {
34206
+ logInstrumentationError6("span end", error);
34207
+ }
34208
+ }
34209
+ function logInstrumentationError6(operation, error) {
34210
+ debugLogger.error(
34211
+ `Failed to process Cloudflare Agents ${operation} instrumentation:`,
34212
+ error
34213
+ );
34214
+ }
34215
+
32889
34216
  // src/instrumentation/braintrust-plugin.ts
32890
34217
  var BraintrustPlugin = class extends BasePlugin {
32891
34218
  config;
@@ -32898,6 +34225,7 @@ var BraintrustPlugin = class extends BasePlugin {
32898
34225
  openAIAgentsPlugin = null;
32899
34226
  googleGenAIPlugin = null;
32900
34227
  huggingFacePlugin = null;
34228
+ huggingFaceTransformersPlugin = null;
32901
34229
  openRouterPlugin = null;
32902
34230
  openRouterAgentPlugin = null;
32903
34231
  mistralPlugin = null;
@@ -32912,6 +34240,8 @@ var BraintrustPlugin = class extends BasePlugin {
32912
34240
  langSmithPlugin = null;
32913
34241
  piCodingAgentPlugin = null;
32914
34242
  strandsAgentSDKPlugin = null;
34243
+ cloudflareAIChatPlugin = null;
34244
+ cloudflareAgentsPlugin = null;
32915
34245
  constructor(config = {}) {
32916
34246
  super();
32917
34247
  this.config = config;
@@ -32953,6 +34283,8 @@ var BraintrustPlugin = class extends BasePlugin {
32953
34283
  if (integrations.huggingface !== false) {
32954
34284
  this.huggingFacePlugin = new HuggingFacePlugin();
32955
34285
  this.huggingFacePlugin.enable();
34286
+ this.huggingFaceTransformersPlugin = new HuggingFaceTransformersPlugin();
34287
+ this.huggingFaceTransformersPlugin.enable();
32956
34288
  }
32957
34289
  if (integrations.openrouter !== false) {
32958
34290
  this.openRouterPlugin = new OpenRouterPlugin();
@@ -32998,6 +34330,14 @@ var BraintrustPlugin = class extends BasePlugin {
32998
34330
  this.strandsAgentSDKPlugin = new StrandsAgentSDKPlugin();
32999
34331
  this.strandsAgentSDKPlugin.enable();
33000
34332
  }
34333
+ if (integrations.cloudflareAIChat !== false) {
34334
+ this.cloudflareAIChatPlugin = new CloudflareAIChatPlugin();
34335
+ this.cloudflareAIChatPlugin.enable();
34336
+ }
34337
+ if (integrations.cloudflareAgents !== false) {
34338
+ this.cloudflareAgentsPlugin = new CloudflareAgentsPlugin();
34339
+ this.cloudflareAgentsPlugin.enable();
34340
+ }
33001
34341
  if (integrations.flue !== false) {
33002
34342
  this.fluePlugin = new FluePlugin();
33003
34343
  this.fluePlugin.enable();
@@ -33050,6 +34390,10 @@ var BraintrustPlugin = class extends BasePlugin {
33050
34390
  this.huggingFacePlugin.disable();
33051
34391
  this.huggingFacePlugin = null;
33052
34392
  }
34393
+ if (this.huggingFaceTransformersPlugin) {
34394
+ this.huggingFaceTransformersPlugin.disable();
34395
+ this.huggingFaceTransformersPlugin = null;
34396
+ }
33053
34397
  if (this.openRouterPlugin) {
33054
34398
  this.openRouterPlugin.disable();
33055
34399
  this.openRouterPlugin = null;
@@ -33094,6 +34438,14 @@ var BraintrustPlugin = class extends BasePlugin {
33094
34438
  this.strandsAgentSDKPlugin.disable();
33095
34439
  this.strandsAgentSDKPlugin = null;
33096
34440
  }
34441
+ if (this.cloudflareAIChatPlugin) {
34442
+ this.cloudflareAIChatPlugin.disable();
34443
+ this.cloudflareAIChatPlugin = null;
34444
+ }
34445
+ if (this.cloudflareAgentsPlugin) {
34446
+ this.cloudflareAgentsPlugin.disable();
34447
+ this.cloudflareAgentsPlugin = null;
34448
+ }
33097
34449
  if (this.fluePlugin) {
33098
34450
  this.fluePlugin.disable();
33099
34451
  this.fluePlugin = null;
@@ -33126,6 +34478,9 @@ var envIntegrationAliases = {
33126
34478
  strandsagentsdk: "strandsAgentSDK",
33127
34479
  "strands-agent-sdk": "strandsAgentSDK",
33128
34480
  "@strands-agents/sdk": "strandsAgentSDK",
34481
+ agents: "cloudflareAgents",
34482
+ "cloudflare-agents": "cloudflareAgents",
34483
+ cloudflareagents: "cloudflareAgents",
33129
34484
  anthropic: "anthropic",
33130
34485
  aisdk: "aisdk",
33131
34486
  "ai-sdk": "aisdk",
@@ -33133,6 +34488,9 @@ var envIntegrationAliases = {
33133
34488
  vercel: "vercel",
33134
34489
  claudeagentsdk: "claudeAgentSDK",
33135
34490
  "claude-agent-sdk": "claudeAgentSDK",
34491
+ cloudflareaichat: "cloudflareAIChat",
34492
+ "cloudflare-ai-chat": "cloudflareAIChat",
34493
+ "@cloudflare/ai-chat": "cloudflareAIChat",
33136
34494
  cursor: "cursor",
33137
34495
  "cursor-sdk": "cursorSDK",
33138
34496
  cursorsdk: "cursorSDK",
@@ -33147,6 +34505,8 @@ var envIntegrationAliases = {
33147
34505
  "google-genai": "googleGenAI",
33148
34506
  googlegenai: "googleGenAI",
33149
34507
  huggingface: "huggingface",
34508
+ "@huggingface/transformers": "huggingface",
34509
+ transformers: "huggingface",
33150
34510
  openrouter: "openrouter",
33151
34511
  openrouteragent: "openrouterAgent",
33152
34512
  "openrouter-agent": "openrouterAgent",
@@ -33185,6 +34545,7 @@ function getDefaultInstrumentationIntegrations() {
33185
34545
  googleADK: true,
33186
34546
  huggingface: true,
33187
34547
  claudeAgentSDK: true,
34548
+ cloudflareAIChat: true,
33188
34549
  cursor: true,
33189
34550
  cursorSDK: true,
33190
34551
  flue: true,
@@ -33204,7 +34565,8 @@ function getDefaultInstrumentationIntegrations() {
33204
34565
  langgraph: true,
33205
34566
  langsmith: true,
33206
34567
  piCodingAgent: true,
33207
- strandsAgentSDK: true
34568
+ strandsAgentSDK: true,
34569
+ cloudflareAgents: true
33208
34570
  };
33209
34571
  }
33210
34572
  function readDisabledInstrumentationEnvConfig(disabledList) {
@@ -33222,7 +34584,9 @@ function readDisabledInstrumentationEnvConfig(disabledList) {
33222
34584
  }
33223
34585
 
33224
34586
  // src/instrumentation/registry.ts
33225
- var REGISTRY_STATE_KEY = /* @__PURE__ */ Symbol.for("braintrust.registry");
34587
+ var REGISTRY_STATE_KEY = /* @__PURE__ */ Symbol.for(
34588
+ `braintrust.registry.global-hooks.v${GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION}`
34589
+ );
33226
34590
  function getSharedState() {
33227
34591
  const state = globalThis[/* @__PURE__ */ Symbol.for("braintrust-state")];
33228
34592
  return state && typeof state === "object" ? state : void 0;
@@ -33327,11 +34691,6 @@ function configureWorkerd() {
33327
34691
  if (runtimeAsyncLocalStorage) {
33328
34692
  isomorph_default.newAsyncLocalStorage = () => new runtimeAsyncLocalStorage();
33329
34693
  }
33330
- isomorph_default.newTracingChannel = (nameOrChannels) => (
33331
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
33332
- tracingChannel(nameOrChannels)
33333
- );
33334
- patchTracingChannel(tracingChannel);
33335
34694
  isomorph_default.getEnv = (name) => {
33336
34695
  if (typeof process === "undefined" || typeof process.env === "undefined") {
33337
34696
  return void 0;
@@ -33506,6 +34865,8 @@ __export(exports_exports, {
33506
34865
  wrapAnthropic: () => wrapAnthropic,
33507
34866
  wrapBedrockRuntime: () => wrapBedrockRuntime,
33508
34867
  wrapClaudeAgentSDK: () => wrapClaudeAgentSDK,
34868
+ wrapCloudflareAIChat: () => wrapCloudflareAIChat,
34869
+ wrapCloudflareAgent: () => wrapCloudflareAgent,
33509
34870
  wrapCohere: () => wrapCohere,
33510
34871
  wrapCopilotClient: () => wrapCopilotClient,
33511
34872
  wrapCursorSDK: () => wrapCursorSDK,
@@ -33514,6 +34875,7 @@ __export(exports_exports, {
33514
34875
  wrapGoogleGenAI: () => wrapGoogleGenAI,
33515
34876
  wrapGroq: () => wrapGroq,
33516
34877
  wrapHuggingFace: () => wrapHuggingFace,
34878
+ wrapHuggingFaceTransformers: () => wrapHuggingFaceTransformers,
33517
34879
  wrapLangSmithClient: () => wrapLangSmithClient,
33518
34880
  wrapLangSmithRunTrees: () => wrapLangSmithRunTrees,
33519
34881
  wrapLangSmithTraceable: () => wrapLangSmithTraceable,
@@ -34837,7 +36199,7 @@ function extractToolCallsFromBlocks(blocks) {
34837
36199
  if (!Array.isArray(blocks)) return [];
34838
36200
  return extractToolCallsFromSteps([{ content: blocks }]);
34839
36201
  }
34840
- function extractInput(params) {
36202
+ function extractInput2(params) {
34841
36203
  return params?.prompt ?? params?.messages ?? params?.system;
34842
36204
  }
34843
36205
  var V2_EXCLUDE_KEYS = /* @__PURE__ */ new Set([
@@ -34859,7 +36221,7 @@ function BraintrustMiddleware(config = {}) {
34859
36221
  params,
34860
36222
  model: modelFromWrapGenerate
34861
36223
  }) => {
34862
- const rawInput = extractInput(params);
36224
+ const rawInput = extractInput2(params);
34863
36225
  const processedInput = processInputAttachments(rawInput);
34864
36226
  const spanArgs = {
34865
36227
  name: config.spanInfo?.name || "ai-sdk.doGenerate",
@@ -34923,7 +36285,7 @@ function BraintrustMiddleware(config = {}) {
34923
36285
  }
34924
36286
  },
34925
36287
  wrapStream: async ({ doStream, params }) => {
34926
- const rawInput = extractInput(params);
36288
+ const rawInput = extractInput2(params);
34927
36289
  const processedInput = processInputAttachments(rawInput);
34928
36290
  const spanArgs = {
34929
36291
  name: config.spanInfo?.name || "ai-sdk.doStream",
@@ -37445,6 +38807,67 @@ function patchAgentSessionClass(AgentSession) {
37445
38807
  });
37446
38808
  }
37447
38809
 
38810
+ // src/wrappers/cloudflare-agent.ts
38811
+ var WRAPPED_RUN_AGENT_TOOL = /* @__PURE__ */ Symbol.for(
38812
+ "braintrust.cloudflare-agents.wrapped-run-agent-tool"
38813
+ );
38814
+ function wrapCloudflareAgent(Agent2) {
38815
+ if (typeof Agent2 !== "function") {
38816
+ warnUnsupportedAgent();
38817
+ return Agent2;
38818
+ }
38819
+ const prototypeDescriptor = Object.getOwnPropertyDescriptor(
38820
+ Agent2,
38821
+ "prototype"
38822
+ );
38823
+ const prototype = prototypeDescriptor && "value" in prototypeDescriptor ? prototypeDescriptor.value : void 0;
38824
+ if (!isObjectLike3(prototype)) {
38825
+ warnUnsupportedAgent();
38826
+ return Agent2;
38827
+ }
38828
+ if (ownValue4(prototype, WRAPPED_RUN_AGENT_TOOL) === true) {
38829
+ return Agent2;
38830
+ }
38831
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, "runAgentTool");
38832
+ if (!descriptor || typeof descriptor.value !== "function") {
38833
+ warnUnsupportedAgent();
38834
+ return Agent2;
38835
+ }
38836
+ const originalRunAgentTool = descriptor.value;
38837
+ Object.defineProperty(prototype, "runAgentTool", {
38838
+ ...descriptor,
38839
+ value: function wrappedRunAgentTool(...args) {
38840
+ const options = args[1];
38841
+ if (ownValue4(options, "detached")) {
38842
+ return Reflect.apply(originalRunAgentTool, this, args);
38843
+ }
38844
+ return cloudflareAgentsChannels.runAgentTool.tracePromise(
38845
+ () => Reflect.apply(originalRunAgentTool, this, args),
38846
+ { arguments: args, self: this }
38847
+ );
38848
+ }
38849
+ });
38850
+ Object.defineProperty(prototype, WRAPPED_RUN_AGENT_TOOL, {
38851
+ configurable: false,
38852
+ enumerable: false,
38853
+ value: true
38854
+ });
38855
+ return Agent2;
38856
+ }
38857
+ function ownValue4(value, key) {
38858
+ if (!isObjectLike3(value)) {
38859
+ return void 0;
38860
+ }
38861
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
38862
+ return descriptor && "value" in descriptor ? descriptor.value : void 0;
38863
+ }
38864
+ function isObjectLike3(value) {
38865
+ return typeof value === "object" && value !== null || typeof value === "function";
38866
+ }
38867
+ function warnUnsupportedAgent() {
38868
+ debugLogger.warn("Unsupported Cloudflare Agents Agent class. Not wrapping.");
38869
+ }
38870
+
37448
38871
  // src/wrappers/strands-agent-sdk.ts
37449
38872
  var WRAPPED_CLASS = /* @__PURE__ */ Symbol.for("braintrust.strands-agent-sdk.wrapped-class");
37450
38873
  var WRAPPED_INSTANCE = /* @__PURE__ */ Symbol.for(
@@ -37613,6 +39036,81 @@ async function consumeAsyncGenerator(generator) {
37613
39036
  return result.value;
37614
39037
  }
37615
39038
 
39039
+ // src/wrappers/cloudflare-ai-chat.ts
39040
+ var wrappedClasses = /* @__PURE__ */ new WeakMap();
39041
+ function wrapCloudflareAIChat(module) {
39042
+ if (!module || typeof module !== "object") {
39043
+ return module;
39044
+ }
39045
+ const candidate = module;
39046
+ let AIChatAgent;
39047
+ try {
39048
+ AIChatAgent = Reflect.get(candidate, "AIChatAgent");
39049
+ } catch (error) {
39050
+ debugLogger.debug("Failed to inspect @cloudflare/ai-chat module:", error);
39051
+ return module;
39052
+ }
39053
+ if (typeof AIChatAgent !== "function") {
39054
+ debugLogger.warn(
39055
+ "Unsupported @cloudflare/ai-chat module. AIChatAgent was not found; not wrapping."
39056
+ );
39057
+ return module;
39058
+ }
39059
+ const target = isModuleNamespace5(module) ? Object.setPrototypeOf({}, module) : candidate;
39060
+ return new Proxy(target, {
39061
+ get(target2, property, receiver) {
39062
+ const value = Reflect.get(target2, property, receiver);
39063
+ if (property === "AIChatAgent" && typeof value === "function") {
39064
+ return wrapAIChatAgentClass(
39065
+ value
39066
+ );
39067
+ }
39068
+ return value;
39069
+ }
39070
+ });
39071
+ }
39072
+ function wrapAIChatAgentClass(AgentClass) {
39073
+ const cached = wrappedClasses.get(AgentClass);
39074
+ if (cached) {
39075
+ return cached;
39076
+ }
39077
+ const wrapped = new Proxy(AgentClass, {
39078
+ get(target, property) {
39079
+ const value = Reflect.get(target, property, target);
39080
+ return typeof value === "function" ? value.bind(target) : value;
39081
+ },
39082
+ construct(target, args, newTarget) {
39083
+ const instance = Reflect.construct(
39084
+ target,
39085
+ args,
39086
+ newTarget
39087
+ );
39088
+ return instrumentCloudflareAIChatAgent(instance);
39089
+ }
39090
+ });
39091
+ wrappedClasses.set(AgentClass, wrapped);
39092
+ wrappedClasses.set(wrapped, wrapped);
39093
+ return wrapped;
39094
+ }
39095
+ function isModuleNamespace5(value) {
39096
+ if (!value || typeof value !== "object") {
39097
+ return false;
39098
+ }
39099
+ try {
39100
+ if (Reflect.get(value, Symbol.toStringTag) === "Module") {
39101
+ return true;
39102
+ }
39103
+ const keys = Object.keys(value);
39104
+ if (keys.length === 0) {
39105
+ return false;
39106
+ }
39107
+ const descriptor = Object.getOwnPropertyDescriptor(value, keys[0]);
39108
+ return descriptor ? !descriptor.configurable && !descriptor.writable : false;
39109
+ } catch {
39110
+ return false;
39111
+ }
39112
+ }
39113
+
37616
39114
  // src/wrappers/google-genai.ts
37617
39115
  function wrapGoogleGenAI(googleGenAI) {
37618
39116
  if (!googleGenAI || typeof googleGenAI !== "object") {
@@ -38265,6 +39763,120 @@ function wrapFeatureExtraction(original, endpointUrl) {
38265
39763
  };
38266
39764
  }
38267
39765
 
39766
+ // src/wrappers/huggingface-transformers.ts
39767
+ var PIPELINE_CONSTRUCTOR_KEYS = /* @__PURE__ */ new Set([
39768
+ "TextGenerationPipeline",
39769
+ "Text2TextGenerationPipeline",
39770
+ "SummarizationPipeline",
39771
+ "FeatureExtractionPipeline",
39772
+ "QuestionAnsweringPipeline"
39773
+ ]);
39774
+ var wrappedValues = /* @__PURE__ */ new WeakMap();
39775
+ function wrapHuggingFaceTransformers(transformers) {
39776
+ const pipelineTask = transformers?.task;
39777
+ if (typeof transformers === "function" && isSupportedHuggingFaceTransformersTask(pipelineTask)) {
39778
+ return wrapPipeline(transformers);
39779
+ }
39780
+ if (!isSupportedModule(transformers)) {
39781
+ return transformers;
39782
+ }
39783
+ const existing = wrappedValues.get(transformers);
39784
+ if (existing) {
39785
+ return existing;
39786
+ }
39787
+ const proxy = new Proxy(Object.create(transformers), {
39788
+ get(_target, property, receiver) {
39789
+ const value = Reflect.get(transformers, property, receiver);
39790
+ if (property === "pipeline" && typeof value === "function") {
39791
+ return wrapPipelineFactory(value);
39792
+ }
39793
+ if (typeof property === "string" && PIPELINE_CONSTRUCTOR_KEYS.has(property) && typeof value === "function") {
39794
+ return wrapPipelineConstructor(
39795
+ value
39796
+ );
39797
+ }
39798
+ return value;
39799
+ }
39800
+ });
39801
+ wrappedValues.set(transformers, proxy);
39802
+ wrappedValues.set(proxy, proxy);
39803
+ return proxy;
39804
+ }
39805
+ function isSupportedModule(value) {
39806
+ if (value === null || typeof value !== "object" && typeof value !== "function") {
39807
+ return false;
39808
+ }
39809
+ if (typeof Reflect.get(value, "pipeline") === "function") {
39810
+ return true;
39811
+ }
39812
+ for (const key of PIPELINE_CONSTRUCTOR_KEYS) {
39813
+ if (typeof Reflect.get(value, key) === "function") {
39814
+ return true;
39815
+ }
39816
+ }
39817
+ return false;
39818
+ }
39819
+ function wrapPipelineFactory(factory) {
39820
+ const existing = wrappedValues.get(factory);
39821
+ if (existing) {
39822
+ return existing;
39823
+ }
39824
+ const wrapped = function(...args) {
39825
+ const [task] = args;
39826
+ const context = {
39827
+ arguments: args
39828
+ };
39829
+ return huggingFaceTransformersChannels.pipeline.tracePromise(() => Reflect.apply(factory, this, args), context).then((pipeline) => {
39830
+ if (isSupportedHuggingFaceTransformersTask(pipeline.task ?? task)) {
39831
+ return wrapPipeline(pipeline);
39832
+ }
39833
+ return pipeline;
39834
+ });
39835
+ };
39836
+ wrappedValues.set(factory, wrapped);
39837
+ wrappedValues.set(wrapped, wrapped);
39838
+ return wrapped;
39839
+ }
39840
+ function wrapPipelineConstructor(constructor) {
39841
+ const existing = wrappedValues.get(constructor);
39842
+ if (existing) {
39843
+ return existing;
39844
+ }
39845
+ const proxy = new Proxy(constructor, {
39846
+ construct(target, args, newTarget) {
39847
+ const pipeline = Reflect.construct(target, args, newTarget);
39848
+ if (isSupportedHuggingFaceTransformersTask(pipeline.task)) {
39849
+ return wrapPipeline(pipeline);
39850
+ }
39851
+ return pipeline;
39852
+ }
39853
+ });
39854
+ wrappedValues.set(constructor, proxy);
39855
+ wrappedValues.set(proxy, proxy);
39856
+ return proxy;
39857
+ }
39858
+ function wrapPipeline(pipeline) {
39859
+ const existing = wrappedValues.get(pipeline);
39860
+ if (existing) {
39861
+ return existing;
39862
+ }
39863
+ const proxy = new Proxy(pipeline, {
39864
+ apply(target, thisArg, args) {
39865
+ const context = {
39866
+ arguments: args,
39867
+ self: target
39868
+ };
39869
+ return huggingFaceTransformersChannels.pipelineCall.tracePromise(
39870
+ () => Reflect.apply(target, thisArg, args),
39871
+ context
39872
+ );
39873
+ }
39874
+ });
39875
+ wrappedValues.set(pipeline, proxy);
39876
+ wrappedValues.set(proxy, proxy);
39877
+ return proxy;
39878
+ }
39879
+
38268
39880
  // src/wrappers/openrouter-agent.ts
38269
39881
  function wrapOpenRouterAgent(agent) {
38270
39882
  const candidate = agent;
@@ -38981,7 +40593,7 @@ function wrapNamespaceExport(namespace, exportName, marker, wrap2) {
38981
40593
  );
38982
40594
  return namespace;
38983
40595
  }
38984
- const target = isModuleNamespace5(namespace) ? Object.setPrototypeOf({}, namespace) : candidate;
40596
+ const target = isModuleNamespace6(namespace) ? Object.setPrototypeOf({}, namespace) : candidate;
38985
40597
  const moduleNamespace = target !== candidate;
38986
40598
  let wrappedExport;
38987
40599
  return new Proxy(target, {
@@ -39015,7 +40627,7 @@ function wrapNamespaceExport(namespace, exportName, marker, wrap2) {
39015
40627
  }
39016
40628
  });
39017
40629
  }
39018
- function isModuleNamespace5(value) {
40630
+ function isModuleNamespace6(value) {
39019
40631
  if (!value || typeof value !== "object") {
39020
40632
  return false;
39021
40633
  }
@@ -43653,6 +45265,8 @@ export {
43653
45265
  wrapAnthropic,
43654
45266
  wrapBedrockRuntime,
43655
45267
  wrapClaudeAgentSDK,
45268
+ wrapCloudflareAIChat,
45269
+ wrapCloudflareAgent,
43656
45270
  wrapCohere,
43657
45271
  wrapCopilotClient,
43658
45272
  wrapCursorSDK,
@@ -43661,6 +45275,7 @@ export {
43661
45275
  wrapGoogleGenAI,
43662
45276
  wrapGroq,
43663
45277
  wrapHuggingFace,
45278
+ wrapHuggingFaceTransformers,
43664
45279
  wrapLangSmithClient,
43665
45280
  wrapLangSmithRunTrees,
43666
45281
  wrapLangSmithTraceable,